Compare commits

..
47 Commits
Author SHA1 Message Date
Kevin Yue a708ce0115 chore: release 2.6.2 2026-06-22 20:33:14 +08:00
Kevin Yue 02cf4a0b26 ci: parallelize gpgui release builds 2026-06-22 12:51:52 +08:00
Kevin Yue 370189cbee fix: resolve release changelog path 2026-06-22 12:42:47 +08:00
Kevin Yue 6746cf64c3 fix: complete 2.6.1 release updates 2026-06-22 11:46:26 +08:00
Kevin Yue 40739739b5 fix: correct direct gateway browser auth mode 2026-06-22 08:24:48 +08:00
Kevin Yue dc7a200b93 ci: avoid Docker Hub auth pulls in release builds 2026-06-21 22:28:49 +08:00
Kevin Yue f49b6471f3 ci: reduce release Docker pull pressure 2026-06-21 22:25:28 +08:00
Kevin Yue 4da922aa3b chore: prepare 2.6.1 release 2026-06-21 22:15:09 +08:00
Kevin Yue ecc9c9f09c feat: auto-select browser for external auth 2026-06-21 20:59:13 +08:00
Kevin Yue b32002710b fix: support NixOS prebuilt GUI package 2026-06-21 20:08:19 +08:00
Kevin Yue 7b6d20a003 fix: substitute NixOS gpservice wrapper path 2026-06-21 15:26:52 +08:00
Kevin Yue d27029fad8 fix: match NixOS polkit service path 2026-06-21 15:21:51 +08:00
Kevin Yue 1b488ba696 fix: launch NixOS GUI service outside FHS env 2026-06-21 14:32:13 +08:00
Kevin Yue f78f7c9bc8 fix: prefer NixOS host wrappers in prebuilt package 2026-06-21 14:03:42 +08:00
Kevin Yue 7e11693ce3 Merge branch 'feature/nix-prebuilt-binaries'
# Conflicts:
#	.github/workflows/build.yaml
#	flake.nix
2026-06-21 12:46:18 +08:00
Kevin Yue c601fa9aa2 feat: add prebuilt Nix package 2026-06-21 12:20:28 +08:00
Kevin Yue 536a43773f feat: add prebuilt Nix package (#622) 2026-06-21 11:57:57 +08:00
Kevin Yue ae4cbedd3b doc: update NixOS installation instructions 2026-06-20 22:11:06 +08:00
Kevin Yue fe55d11fc4 ci: use main PPA publish action 2026-06-20 19:39:26 +08:00
github-actions[bot] 34f1feaf43 chore: update flake hashes for v2.6.0 (#621) 2026-06-20 19:12:58 +08:00
Kevin Yue f640b4d325 Merge branch 'fix/settings-crash-wayland-thread-safety' 2026-06-20 19:08:23 +08:00
Kevin Yue a35b4a289e chore: release 2.6.0 2026-06-20 18:21:58 +08:00
Kevin Yue a7a5d9bf96 fix: recover desktop session env for browser auth 2026-06-19 23:25:05 +08:00
Kevin Yue 888dc93643 refactor: align GP profile and packaging flow
Main changes:

- Refactor connect/auth flows around a single OS profile and host identity model, including gateway fallback and cookie-on-stdin handling.

- Align request parameters, HIP host-id propagation, SAML webview user-agent behavior, and portal default-browser handling with observed official client behavior.

- Add opt-in cookie cache support and Microsoft Defender HIP reporting while keeping host-id validation explicit.

- Add BSD build, packaging, release artifact, and provenance support with FreeBSD/OpenBSD path and dependency cleanup.

- Update NixOS install documentation and dependency compatibility fixes.
2026-06-19 21:23:29 +08:00
Rafa FlorestaandRafa Floresta f98e0336dc fix(gpapi): send host-id so the portal issues the auth-override cookie (#616)
PAN-OS binds the portal authentication-override cookie (portal-userauthcookie)
to the client's host-id. GpParams never had a host-id, so to_params() omitted it
from prelogin, getconfig and gateway login (prelogin even lists it in
REQUIRED_PARAMS, but it was never produced and got silently dropped).

On portals configured for SAML at both the portal and the gateway, the portal
then returns portal-userauthcookie=empty. With no cookie to present, the gateway
login falls back to a second, gateway-level SAML that the server rejects with
saml-auth-status=-1.

Add a stable host_id to GpParams (defaulting to host_utils::derive_uuid, the same
per-machine UUID used for HIP reports) and emit "host-id" from to_params(), so
prelogin, getconfig and gateway login all carry a consistent host-id. The portal
then issues a real portal-userauthcookie, which the gateway accepts; the failing
gateway-SAML path is never taken.

Fixes #491

Co-authored-by: Rafa Floresta <[email protected]>
2026-06-19 14:39:56 +08:00
Guangyuan Weng 7a571f9b27 feat(gpclient): cache portal-cookie to skip SAML on reconnect (#608) 2026-06-19 14:38:17 +08:00
bstock-rpandbstock84 67de92044f feat: add Microsoft Defender anti-malware HIP reporting support for linux (#618)
Co-authored-by: bstock84 <[email protected]>
2026-06-19 14:29:54 +08:00
Kevin Yue 7d63836e35 ci: support remote auth in docker image 2026-05-09 22:43:44 +08:00
Kevin Yue 3e23fc7d22 ci: add Alpine docker runtime libraries 2026-05-09 20:53:34 +08:00
Kevin Yue 8bf05d381e ci: dynamically link Alpine docker build 2026-05-09 20:36:24 +08:00
Kevin Yue 1ab36a1137 fix: gate gtk dependency behind tauri feature 2026-05-09 20:21:37 +08:00
Kevin Yue 18b788e664 ci: align docker packaging path 2026-05-09 20:10:24 +08:00
Kevin Yue ebadab8f06 ci: publish docker images by digest 2026-05-09 20:02:59 +08:00
Kevin Yue 81d13deaab refactor: simplify SAML browser selection 2026-05-09 09:24:26 +08:00
Kevin Yue 6f91a79081 docs: add minimal Alpine gpclient image 2026-05-09 09:04:28 +08:00
Kevin Yue 4d252fa31c ci: simplify gpgui matrix names 2026-05-09 07:45:32 +08:00
Kevin Yue 398475c649 ci: preserve gpgui check names 2026-05-09 07:41:21 +08:00
Kevin Yue 13d4aa398c ci: matrix gpgui libc builds 2026-05-09 07:38:24 +08:00
Kevin Yue 9423665fe5 ci: remove unsupported release action input 2026-05-09 01:26:26 +08:00
Kevin Yue 5e8dbfa26d ci: disambiguate APK release assets 2026-05-09 01:14:23 +08:00
github-actions[bot] d96b3f9c0d chore: update flake hashes for v2.5.4 (#607)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-08 17:03:26 +00:00
Kevin Yue 7720942681 ci: keep gpgui matrices running after failures 2026-05-09 00:11:39 +08:00
Kevin Yue f129ca7ea1 chore: release 2.5.4 2026-05-08 23:56:07 +08:00
Kevin Yue 628d0febdd ci: keep build-gp matrix running after failures 2026-05-08 23:07:21 +08:00
Kevin Yue add284d3b4 ci: always build arm packages 2026-05-08 22:39:21 +08:00
Kevin Yue a3f2224952 ci: add Alpine APK packaging 2026-05-08 22:24:15 +08:00
github-actions[bot] 966bcc554b chore: update flake hashes for v2.5.3 (#605) 2026-05-08 08:32:04 +08:00
113 changed files with 11583 additions and 2947 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.build
.git
.vendor
apps/gpgui-helper/node_modules
target
vendor.tar.xz
+425 -38
View File
@@ -10,6 +10,16 @@ on:
description: 'gpgui branch to use for the snapshot release'
required: true
default: dev
build_bsd:
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
required: true
default: false
type: boolean
build_bsd_arm64:
description: 'Build optional FreeBSD/OpenBSD arm64 packages for the snapshot release. Slow and disabled by default'
required: true
default: false
type: boolean
push:
paths-ignore:
- LICENSE
@@ -29,25 +39,8 @@ concurrency:
cancel-in-progress: true
jobs:
# Include arm64 for tagged releases and manual snapshot releases.
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 for tagged releases and manual snapshot releases.
if [[ "${{ github.ref }}" == "refs/tags/"* || "${{ github.event_name }}" == "workflow_dispatch" ]]; 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:
runs-on: ubuntu-latest
needs: [setup-matrix]
steps:
- uses: pnpm/action-setup@v5
with:
@@ -137,13 +130,18 @@ jobs:
if-no-files-found: error
build-gp:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
needs:
- setup-matrix
- tarball
strategy:
fail-fast: false
matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
package: [deb, rpm, pkg, binary, ubuntu-rolling]
os:
- runner: ubuntu-latest
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 }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
steps:
@@ -156,19 +154,17 @@ jobs:
with:
name: artifact-source
path: build-gp-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --pull=always --rm \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --pull=always --rm \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_INSTALLED=0 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
@@ -184,14 +180,83 @@ jobs:
path: |
build-gp-${{ matrix.package }}/artifacts/*
build-gpgui:
needs:
- setup-matrix
build-docker-image:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
strategy:
fail-fast: false
matrix:
os: ${{fromJson(needs.setup-matrix.outputs.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:
strategy:
fail-fast: false
matrix:
os:
- 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 }}
name: build-gpgui (${{ matrix.os.arch }})
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
with:
@@ -217,40 +282,300 @@ jobs:
run: |
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build gpgui in Docker
run: |
docker run --pull=always --rm \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:gpgui-builder-tauri2
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
- name: Install gpgui in Docker
run: |
cd gpgui-source
tar -xJf *.bin.tar.xz
docker run --pull=always --rm \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:gpgui-builder-tauri2 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
with:
name: artifact-gpgui-${{ matrix.os.arch }}
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
gh-release:
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
setup-bsd-matrix:
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.matrix.outputs.enabled }}
matrix: ${{ steps.matrix.outputs.matrix }}
steps:
- name: Build matrix
id: matrix
env:
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
BUILD_BSD: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd }}
BUILD_BSD_ARM64: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd_arm64 }}
run: |
python3 - <<'PY'
import json
import os
build_bsd = os.environ["IS_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
build_bsd_arm64 = os.environ["BUILD_BSD_ARM64"] == "true"
include = []
def add(os_name, arch):
include.append({
"os": os_name,
"arch": arch,
"workspace": f"{os_name}-{arch}-source",
"artifact": f"artifact-bsd-{os_name}-{arch}",
"package_target": f"package-{os_name}",
"artifact_dir": os_name,
})
if build_bsd:
add("freebsd", "x86_64")
add("openbsd", "x86_64")
if build_bsd_arm64:
add("freebsd", "arm64")
add("openbsd", "arm64")
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"enabled={str(bool(include)).lower()}\n")
output.write(f"matrix={json.dumps({'include': include}, separators=(',', ':'))}\n")
PY
build-gpgui-frontend:
needs: setup-bsd-matrix
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-frontend && mkdir gpgui-frontend
- 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 }}
path: gpgui-frontend/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: gpgui-frontend/gpgui
- name: Build gpgui frontend
run: |
cd gpgui-frontend/gpgui/app
pnpm install --frozen-lockfile
pnpm build
- name: Upload gpgui frontend
uses: actions/upload-artifact@v7
with:
name: bsd-gpgui-frontend
if-no-files-found: error
path: gpgui-frontend/gpgui/app/dist/**
build-bsd:
needs:
- setup-bsd-matrix
- build-gpgui-frontend
if: ${{ needs.setup-bsd-matrix.outputs.enabled == 'true' }}
runs-on: ubuntu-latest
name: build-${{ matrix.os }} (${{ matrix.arch }})
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-bsd-matrix.outputs.matrix) }}
steps:
- name: Prepare workspace
run: rm -rf "${{ matrix.workspace }}" && mkdir "${{ matrix.workspace }}"
- 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 }}
path: ${{ matrix.workspace }}/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: ${{ matrix.workspace }}/gpgui
- name: Download gpgui frontend
uses: actions/download-artifact@v8
with:
name: bsd-gpgui-frontend
path: ${{ matrix.workspace }}/gpgui/app/dist
- name: Build on FreeBSD
if: ${{ matrix.os == 'freebsd' }}
uses: vmactions/freebsd-vm@v1
with:
release: "14.3"
arch: ${{ matrix.arch }}
usesh: true
prepare: |
pkg install -y \
git \
rust \
libiconv \
gettext-tools \
autoconf \
automake \
libtool \
patch \
gmake \
pkgconf \
libxml2 \
gnutls \
p11-kit \
nettle \
gmp \
gnome-keyring \
libayatana-appindicator \
polkit \
webkit2-gtk_41
run: |
set -eu
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/app/src-tauri
cargo build --release --workspace
cd ../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg install -y ".build/${{ matrix.artifact_dir }}"/artifacts/*.pkg
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Build on OpenBSD
if: ${{ matrix.os == 'openbsd' }}
uses: vmactions/openbsd-vm@v1
with:
release: "7.9"
arch: ${{ matrix.arch }}
usesh: true
prepare: |
pkg_add -z \
git \
rust \
libiconv \
gettext-tools \
autoconf-2.72 \
automake-1.17 \
libtool \
patch \
gmake \
pkgconf \
libxml \
gnutls \
p11-kit \
nettle \
gmp \
gnome-keyring \
polkit \
webkitgtk41
ln -sf /usr/local/bin/autoreconf-2.72 /usr/local/bin/autoreconf
ln -sf /usr/local/bin/autoconf-2.72 /usr/local/bin/autoconf
ln -sf /usr/local/bin/autoheader-2.72 /usr/local/bin/autoheader
ln -sf /usr/local/bin/autom4te-2.72 /usr/local/bin/autom4te
ln -sf /usr/local/bin/aclocal-1.17 /usr/local/bin/aclocal
ln -sf /usr/local/bin/automake-1.17 /usr/local/bin/automake
run: |
set -eu
export AUTOCONF_VERSION=2.72
export AUTOMAKE_VERSION=1.17
cd "${{ matrix.workspace }}/gp"
cargo build --release --workspace
cd ../gpgui/app/src-tauri
cargo build --release --workspace
cd ../../../gp
gmake "${{ matrix.package_target }}" GPGUI_BINARY=../gpgui/target/release/gpgui
pkg_add -D unsigned ".build/${{ matrix.artifact_dir }}"/artifacts/*.tgz
gpclient --version
gpauth --version
gpgui --version
rm -rf target ../gpgui/target
find ".build/${{ matrix.artifact_dir }}" -mindepth 1 -maxdepth 1 ! -name artifacts -exec rm -rf {} +
- name: Upload BSD package
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.artifact }}
if-no-files-found: error
path: |
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
gh-release:
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
needs:
- tarball
- tarball-offline
- build-gp
- build-docker-image
- build-gpgui
- setup-bsd-matrix
- build-gpgui-frontend
- build-bsd
steps:
- name: Check required jobs
env:
NEEDS_JSON: ${{ toJson(needs) }}
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
run: |
python3 - <<'PY'
import json
import os
import sys
needs = json.loads(os.environ["NEEDS_JSON"])
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
is_tag = os.environ["IS_TAG"] == "true"
failed = []
for name, data in needs.items():
result = data["result"]
if result in {"failure", "cancelled"}:
failed.append(f"{name}: {result}")
elif name in {"build-gp", "build-docker-image"} and result == "skipped" and is_tag:
continue
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
continue
elif result == "skipped":
failed.append(f"{name}: {result}")
if failed:
print("Required jobs did not complete successfully:")
for item in failed:
print(f" - {item}")
sys.exit(1)
PY
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
@@ -268,9 +593,71 @@ jobs:
with:
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: Generate release asset checksums
env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh "$RELEASE_TAG" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
- name: Attest release assets
uses: actions/attest-build-provenance@v4
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Create GH release
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
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"
+16 -4
View File
@@ -79,13 +79,24 @@ jobs:
needs: [check, resolve-series]
name: publish-ppa (${{ matrix.series }})
runs-on: ubuntu-latest
container:
image: ubuntu:${{ matrix.series }}
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Install container tools
run: |
apt-get update
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
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code
@@ -118,6 +129,7 @@ jobs:
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/1/g" .build/debian/rules
# Update the control file with the correct Rust version
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control
@@ -125,7 +137,7 @@ jobs:
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
- name: Publish to PPA
uses: yuezk/publish-ppa-package@gp
uses: yuezk/publish-ppa-package@main
with:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
+173 -7
View File
@@ -30,11 +30,21 @@ on:
description: 'Build PKG package'
required: true
default: true
release-apk:
type: boolean
description: 'Build APK package'
required: true
default: true
release-binary:
type: boolean
description: 'Build binary package'
required: true
default: true
release-docker:
type: boolean
description: 'Publish Docker image'
required: true
default: true
gh-release:
type: boolean
description: 'Update GitHub release'
@@ -79,7 +89,7 @@ jobs:
}
const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && value)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
.map(([key, value]) => key.replace('release-', ''))
return JSON.stringify({
@@ -106,12 +116,10 @@ jobs:
--pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --pull=always --rm \
docker run --rm \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
@@ -120,7 +128,7 @@ jobs:
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --pull=always --rm \
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
@@ -134,18 +142,176 @@ jobs:
path: |
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:
needs:
- build
runs-on: ubuntu-latest
if: ${{ inputs.gh-release }}
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
steps:
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
path: gh-release/gp
submodules: recursive
- name: Download artifact
uses: actions/download-artifact@v8
with:
path: gh-release
- name: Generate release notes
id: release-notes
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-notes.sh "${{ inputs.tag }}" > .build/release-notes.md
echo "path=$GITHUB_WORKSPACE/gh-release/gp/.build/release-notes.md" >> "$GITHUB_OUTPUT"
- 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: Generate release asset checksums
id: release-assets
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh all "$GITHUB_WORKSPACE/gh-release" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
{
echo 'files<<EOF'
cat .build/release-assets.txt
echo EOF
} >> "$GITHUB_OUTPUT"
- name: Attest release assets
uses: actions/attest-build-provenance@v4
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Update release
uses: softprops/action-gh-release@v1
with:
@@ -153,5 +319,5 @@ jobs:
prerelease: ${{ contains(github.ref, 'snapshot') }}
fail_on_unmatched_files: true
tag_name: ${{ inputs.tag }}
files: |
gh-release/artifact-*/*
body_path: ${{ steps.release-notes.outputs.path }}
files: ${{ steps.release-assets.outputs.files }}
+80 -34
View File
@@ -6,9 +6,6 @@ on:
version:
description: "Release version. Defaults to Cargo.toml workspace version."
required: false
release:
types:
- published
permissions:
contents: write
@@ -26,7 +23,7 @@ jobs:
- name: Update flake hashes
env:
RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
RELEASE_VERSION: ${{ inputs.version }}
run: |
if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION"
@@ -34,36 +31,85 @@ jobs:
scripts/update-flake-hashes.sh
fi
- name: Upload updated flake
uses: actions/upload-artifact@v7
with:
name: updated-flake
path: flake.nix
if-no-files-found: error
validate-nix-prebuilt:
needs:
- update-flake-hashes
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
nixpkgs: nixos-25.11
- runner: ubuntu-latest
nixpkgs: nixos-26.05
- runner: ubuntu-24.04-arm
nixpkgs: nixos-25.11
- runner: ubuntu-24.04-arm
nixpkgs: nixos-26.05
name: validate-nix-prebuilt (${{ matrix.nixpkgs }}, ${{ matrix.runner }})
runs-on: ${{ matrix.runner }}
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
submodules: recursive
- name: Download updated flake
uses: actions/download-artifact@v8
with:
name: updated-flake
path: .
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Build prebuilt Nix package
run: |
nix build .#prebuilt \
--override-input nixpkgs "github:NixOS/nixpkgs/${{ matrix.nixpkgs }}" \
--extra-experimental-features "nix-command flakes" \
--print-build-logs
- name: Inspect prebuilt Nix package
run: |
test -x result/bin/gpclient
test -x result/bin/gpauth
test -x result/bin/gpservice
test -x result/bin/gpgui-helper
test -x result/bin/gpgui
test ! -L result/bin/gpservice
head -n1 result/bin/gpclient | grep '^#!'
head -n1 result/bin/gpservice | grep '^#!'
grep -q '/run/wrappers/bin/pkexec' result/bin/gpclient
grep -q 'gpservice_public=.*/bin/gpservice' result/bin/gpclient
grep -q 'exec .*/bin/gpservice' result/bin/gpservice
! grep -q '@gpservice_public@\|@gpservice_fhs@\|\$out/bin/gpservice' result/bin/gpclient result/bin/gpservice
! grep -R '/usr/bin/gp' result/share
open-pull-request:
needs:
- validate-nix-prebuilt
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Download updated flake
uses: actions/download-artifact@v8
with:
name: updated-flake
path: .
- 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
RELEASE_VERSION: ${{ inputs.version }}
run: scripts/open-flake-hashes-pr.sh "$RELEASE_VERSION"
+1
View File
@@ -8,6 +8,7 @@
.cargo
.build
SNAPSHOT
SOURCE_COMMIT
# Tauri generated files
gen
Generated
+559 -529
View File
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package]
rust-version = "1.89"
version = "2.5.3"
version = "2.6.2"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024"
@@ -19,7 +19,7 @@ license = "GPL-3.0"
[workspace.dependencies]
anyhow = "1.0"
askama = "0.14"
askama = "0.16"
base64 = "0.22"
chrono = "0.4"
clap = { version = "4", features = ["derive"] }
@@ -31,10 +31,10 @@ env_logger = "0.11"
is_executable = "1.0"
log = "0.4"
regex = "1"
reqwest = { version = "0.12", features = ["native-tls", "json"] }
reqwest = { version = "0.13", features = ["native-tls", "json", "form", "query"] }
openssl = "0.10"
pem = "3"
xmltree = "0.12"
xmltree = { version = "0.12", features = ["attribute-order"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Use 0.36 as newer versions requires Rust 1.88+
@@ -48,7 +48,7 @@ axum = "0.8"
futures = "0.3"
futures-util = "0.3"
uzers = "0.12"
whoami = "1"
whoami = "2"
thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
@@ -58,12 +58,12 @@ sha256 = "1"
which = "8"
uuid = "1"
netdev = "0.40"
machine-uid = "0.5"
humantime = "2"
# Tauri dependencies
tauri = { version = "2" }
specta = "=2.0.0-rc.20"
proptest = "1"
[profile.release]
opt-level = 'z' # Optimize for size
+150 -6
View File
@@ -1,4 +1,5 @@
.SHELLFLAGS += -e
SHELL := /bin/sh
.SHELLFLAGS := -ec
INCLUDE_GUI ?= 0
CARGO ?= cargo
@@ -7,6 +8,17 @@ RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0
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
RPM_SOURCE ?= %{name}.tar.gz
@@ -19,6 +31,12 @@ PUBLISH ?= 0
# Indicates whether to build the GUI components
BUILD_GUI_HELPER ?= 1
# Indicates whether to build embedded webview auth support into gpauth
BUILD_WEBVIEW_AUTH ?= 1
PREFIX ?= /usr/local
BSD_FLAVOR ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
GPGUI_BINARY ?= ../gpgui/target/release/gpgui
export DEBEMAIL = [email protected]
export DEBFULLNAME = Kevin Yue
export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false")
@@ -54,11 +72,13 @@ clean-tarball:
rm -rf .vendor
rm -rf vendor.tar.xz
rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball
mkdir -p .cargo
mkdir -p .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build
@@ -77,8 +97,8 @@ download-gui:
if [ $(INCLUDE_GUI) -eq 1 ]; then \
echo "Downloading GlobalProtect GUI..."; \
mkdir -p .build/gpgui; \
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).bin.tar.xz; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz; \
tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \
else \
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
@@ -96,11 +116,18 @@ build-rs:
rm -vf rust-toolchain.toml; \
fi
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice
# Build gpauth with or without embedded webview auth support
if [ $(BUILD_WEBVIEW_AUTH) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth; \
else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth --no-default-features; \
fi
# Only build the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth -p gpgui-helper; \
else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth --no-default-features; \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper; \
fi
clean:
@@ -139,6 +166,98 @@ install:
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
install -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
install-bsd:
@echo "Installing $(PKG_NAME) for BSD under $(PREFIX)..."
install -d $(DESTDIR)$(PREFIX)/bin
install -m 755 target/release/gpclient $(DESTDIR)$(PREFIX)/bin/gpclient
install -m 755 target/release/gpauth $(DESTDIR)$(PREFIX)/bin/gpauth
install -m 755 target/release/gpservice $(DESTDIR)$(PREFIX)/bin/gpservice
if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
install -m 755 target/release/gpgui-helper $(DESTDIR)$(PREFIX)/bin/gpgui-helper; \
fi
if [ -x "$(GPGUI_BINARY)" ]; then \
install -m 755 "$(GPGUI_BINARY)" $(DESTDIR)$(PREFIX)/bin/gpgui; \
fi
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script
install -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh
install -d $(DESTDIR)$(PREFIX)/share/applications
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps
install -m 644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps/gpgui.svg
install -m 644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps/gpgui.png
install -m 644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256@2/apps/gpgui.png
install -d $(DESTDIR)$(PREFIX)/share/polkit-1/actions
install -m 644 packaging/bsd/com.yuezk.gpgui.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy
clean-bsd-package:
rm -rf .build/$(BSD_FLAVOR)
bsd-gpgui-tarball:
test -x "$(GPGUI_BINARY)"
rm -rf .build/$(BSD_FLAVOR)/gpgui
mkdir -p .build/$(BSD_FLAVOR)/artifacts .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)
cp "$(GPGUI_BINARY)" .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)/
tar -cf - -C .build/$(BSD_FLAVOR)/gpgui gpgui_$(VERSION) | xz -c > .build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz
file=.build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz; \
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$$file" | cut -d ' ' -f 1; \
elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$$file"; \
else cksum -a sha256 "$$file" | awk '{print $$1}'; fi > "$$file.sha256"
package-freebsd: BSD_FLAVOR=freebsd
package-freebsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/freebsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
find .build/freebsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/freebsd/pkgroot$(PREFIX)/||' | sort > .build/freebsd/PLIST
freebsd_major=$$(freebsd-version -u | sed 's/\..*//'); \
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
sed \
-e 's/@PKG_NAME@/$(PKG_NAME)/g' \
-e 's/@VERSION@/$(VERSION)/g' \
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
-e 's|@PREFIX@|$(PREFIX)|g' \
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/+MANIFEST
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/+MANIFEST -p .build/freebsd/PLIST -o .build/freebsd/artifacts
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
mv .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION).pkg .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION)-freebsd-$$freebsd_arch.pkg
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=freebsd GPGUI_BINARY="$(GPGUI_BINARY)"
package-openbsd: BSD_FLAVOR=openbsd
package-openbsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/openbsd/pkgroot .build/openbsd/artifacts
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
find .build/openbsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/openbsd/pkgroot$(PREFIX)/||' | sort > .build/openbsd/PLIST
comment=$$(cat .build/openbsd/+COMMENT); \
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \
pkg_create \
-B .build/openbsd/pkgroot \
-D COMMENT="$$comment" \
-d .build/openbsd/+DESC \
-f .build/openbsd/PLIST \
-p $(PREFIX) \
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
-P sysutils/polkit:polkit-*:$$polkit_pkg \
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
uninstall:
@echo "Uninstalling $(PKG_NAME)..."
@@ -184,10 +303,15 @@ init-debian: clean-debian tarball
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
fi
# Remove the WebKitGTK build dependency only if neither gpauth webview auth nor gpgui-helper needs it
if [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
fi
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
rm -f .build/deb/$(PKG)/debian/changelog
@@ -270,6 +394,26 @@ init-pkgbuild: clean-pkgbuild tarball
pkgbuild: init-pkgbuild
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:
rm -rf .build/binary
+100 -41
View File
@@ -20,8 +20,10 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
- [Other RPM-based Distributions](#other-rpm-based-distributions)
- [Alpine Linux](#alpine-linux)
- [Gentoo](#gentoo)
- [NixOS](#nixos)
- [Official Docker Image](#official-docker-image)
- [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions)
@@ -79,6 +81,8 @@ gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-
```
**Browser Options:**
- Use `--browser` to auto-select Chrome, Firefox, then the system default browser
- Use `--browser default` to use the system default browser
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
@@ -186,6 +190,16 @@ Download the latest RPM package from the [releases](https://github.com/yuezk/Glo
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
Available via the `guru` and `lamdness` overlays:
@@ -200,56 +214,101 @@ sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
This repository includes a flake for NixOS integration.
If you want a quick user-level install, you can install it directly from the flake:
```bash
nix profile add github:yuezk/GlobalProtect-openconnect
```
If you want it managed as part of your NixOS system configuration, use the steps below.
#### Installation Steps
1. Add the flake to your `flake.nix`:
Add the flake input and package to your `flake.nix`:
```nix
{
inputs = {
# ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
```nix
{
inputs = {
# ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
};
outputs = { self, nixpkgs, globalprotect-openconnect, ... }:
let
system = "x86_64-linux"; # or "aarch64-linux" for ARM64
hostname = "<your-host>";
in {
nixosConfigurations.${hostname} = nixpkgs.lib.nixosSystem {
inherit system;
modules = [
./configuration.nix
{
services.ayatana-indicators.enable = true;
environment.systemPackages = [
globalprotect-openconnect.packages.${system}.default
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
];
}
];
};
};
}
```
outputs = { nixpkgs, ... }@inputs: {
nixosConfigurations.<your-host> = nixpkgs.lib.nixosSystem {
specialArgs = { inherit inputs; };
modules = [
./configuration.nix
];
};
};
}
```
Apply:
2. Add the package to your `configuration.nix`:
```bash
sudo nixos-rebuild switch
loginctl terminate-user "$USER"
```
```nix
{ config, pkgs, inputs, ... }:
After logging back in to GNOME, enable AppIndicator support if needed:
{
# ... other configurations
environment.systemPackages = with pkgs; [
# ... other packages
] ++ [
inputs.globalprotect-openconnect.packages.${pkgs.stdenv.hostPlatform.system}.default
];
}
```
```bash
gnome-extensions enable [email protected]
```
3. Apply the changes:
### Official Docker Image
```bash
sudo nixos-rebuild switch
```
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
@@ -307,7 +366,7 @@ This project includes a DevContainer configuration that provides a consistent, r
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
```
To build without the GUI helper run the same command as above, but with `BUILD_GUI=0` passed as an argument to `make`.
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:**
+1 -1
View File
@@ -21,7 +21,7 @@ clap.workspace = true
env_logger.workspace = true
log.workspace = true
serde_json.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tempfile.workspace = true
compile-time.workspace = true
+59
View File
@@ -1,4 +1,63 @@
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=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")]
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())
}
+148 -21
View File
@@ -1,17 +1,24 @@
use auth::{BrowserAuthenticator, auth_prelogin};
use clap::Parser;
use common::constants::GP_USER_AGENT;
use gpapi::{
auth::{SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
gp_params::{ClientOs, GpParams},
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
utils::{normalize_server, openssl},
};
use log::info;
use serde_json::json;
use tempfile::NamedTempFile;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)]
#[command(
@@ -41,14 +48,27 @@ struct Cli {
#[arg(long, help = "The SAML authentication request")]
saml_request: Option<String>,
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
#[arg(long, value_enum, default_value_t = Os::default())]
os: Os,
#[arg(long)]
os_version: Option<String>,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "Override the GlobalProtect client version reported to the server")]
client_version: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
fix_openssl: bool,
@@ -62,8 +82,8 @@ struct Cli {
#[arg(
long,
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable",
default_missing_value = "default",
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser.",
default_missing_value = "auto",
num_args=0..=1
)]
browser: Option<String>,
@@ -114,10 +134,14 @@ impl Cli {
let server = normalize_server(&self.server)?;
let gp_params = self.build_gp_params();
info!(
"gpauth auth host-id: {}",
gp_params.os_profile().host_identity().host_id()
);
let auth_request = match self.saml_request.as_deref() {
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&server, &gp_params).await?,
None => auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await?,
};
#[cfg(feature = "webview-auth")]
@@ -130,10 +154,11 @@ impl Cli {
let browser = self.browser.as_deref().or(Some("default"));
if let Some(browser) = browser {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
let authenticator = BrowserAuthenticator::new(&auth_request, browser);
let auth_result = authenticator.authenticate().await;
print_auth_result(auth_result);
print_auth_result(auth_result, Some(&auth_host_id));
// explicitly drop openssl_conf to avoid the unused variable warning
drop(openssl_conf);
@@ -147,15 +172,36 @@ impl Cli {
}
fn build_gp_params(&self) -> GpParams {
let gp_params = GpParams::builder()
.user_agent(&self.user_agent)
.client_os(ClientOs::from(&self.os))
.os_version(self.os_version.clone())
GpParams::builder(self.build_os_profile())
.ignore_tls_errors(self.ignore_tls_errors)
.certificate(self.certificate.clone())
.sslkey(self.sslkey.clone())
.key_password(self.key_password.clone())
.is_gateway(self.gateway)
.build();
.build()
}
gp_params
fn build_os_profile(&self) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(self.os));
if let Some(host_id) = self.host_id.as_deref() {
builder = builder.host_id_override(host_id);
}
if let Some(client_version) = self.client_version.as_deref() {
builder = builder.client_version(client_version);
}
builder.build()
}
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.default_browser || self.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
true
}
}
}
@@ -177,11 +223,92 @@ pub async fn run() {
}
}
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>) {
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
let auth_result = match auth_result {
Ok(auth_data) => SamlAuthResult::Success(auth_data),
Ok(auth_data) => {
let auth_data = match host_id {
Some(host_id) => auth_data.with_host_id(host_id),
None => auth_data,
};
SamlAuthResult::Success(auth_data)
}
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
println!("{}", json!(auth_result));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn os_defaults_to_runtime_os() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
assert_eq!(cli.os, Os::default());
}
#[test]
fn host_id_arg_sets_profile_host_id_seed() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.host_identity().host_id(), "host-seed");
}
#[test]
fn browser_arg_requests_external_browser() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "firefox"]).expect("gpauth args should parse");
assert!(cli.external_browser_requested());
}
#[test]
fn browser_without_value_uses_auto_mode() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--browser"]).expect("gpauth args should parse");
assert_eq!(cli.browser.as_deref(), Some("auto"));
assert!(cli.external_browser_requested());
}
#[test]
fn browser_default_keeps_system_default_mode() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "default"]).expect("gpauth args should parse");
assert_eq!(cli.browser.as_deref(), Some("default"));
assert!(cli.external_browser_requested());
}
#[test]
fn client_version_arg_sets_profile_client_version() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn client_certificate_args_parse() {
let cli = Cli::try_parse_from([
"gpauth",
"portal.example.com",
"--certificate",
"/tmp/client.pem",
"--sslkey",
"/tmp/client.key",
"--key-password",
"secret",
])
.expect("gpauth args should parse");
assert_eq!(cli.certificate.as_deref(), Some("/tmp/client.pem"));
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
assert_eq!(cli.key_password.as_deref(), Some("secret"));
}
}
+4 -1
View File
@@ -13,6 +13,8 @@ pub async fn authenticate(
clean: bool,
mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
tauri::Builder::default()
.setup(move |app| {
let app_handle = app.handle().clone();
@@ -20,10 +22,11 @@ pub async fn authenticate(
tauri::async_runtime::spawn(async move {
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
.with_auth_request(&auth_request)
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
.with_clean(clean);
let auth_result = authenticator.authenticate(&app_handle).await;
print_auth_result(auth_result);
print_auth_result(auth_result, Some(&auth_host_id));
// Ensure the app exits after the authentication process
app_handle.exit(0);
+2
View File
@@ -20,6 +20,7 @@ inquire = "0.9"
log.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
whoami.workspace = true
@@ -29,6 +30,7 @@ directories.workspace = true
compile-time.workspace = true
netdev.workspace = true
xmltree.workspace = true
uuid = { workspace = true, features = ["v5"] }
[features]
default = ["webview-auth"]
+56
View File
@@ -0,0 +1,56 @@
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())
}
+13 -6
View File
@@ -19,7 +19,14 @@ use crate::{
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
pub(crate) struct SharedArgs<'a> {
pub(crate) fix_openssl: bool,
@@ -147,11 +154,11 @@ fn init_logger(cli: &Cli) {
// Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = &cli.command {
let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() {
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
if !auth_data.is_empty()
&& let Ok(log_file) = File::create(temp_dir().join("gpcallback.log"))
{
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
}
-681
View File
@@ -1,681 +0,0 @@
use std::{
borrow::Cow,
cell::RefCell,
fs,
sync::{Arc, Mutex},
};
use anyhow::{Context, bail};
use clap::Args;
use common::constants::{GP_CLIENT_VERSION, GP_USER_AGENT};
use gpapi::{
auth::SamlAuthResult,
clap::{ToVerboseArg, args::Os},
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login},
gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
process::{
auth_launcher::SamlAuthLauncher,
users::{get_non_root_user, get_user_by_name},
},
utils::{host_utils, request::RequestIdentityError, shutdown_signal},
};
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::{info, warn};
use openconnect::Vpn;
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{
GP_CLIENT_LOCK_FILE,
cli::SharedArgs,
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
gateway: Option<String>,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
passwd_on_stdin: bool,
#[arg(long, help = "Read the cookie from standard input")]
cookie_on_stdin: bool,
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
interface: Option<String>,
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
as_gateway: bool,
#[arg(
long,
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
default_missing_value = "",
num_args=0..=1
)]
hip: Option<String>,
#[arg(long, help = "The user used to run the HIP script")]
hip_user: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "Deprecated: Use the '--hip-user' option instead")]
csd_user: Option<String>,
#[arg(long, help = "Deprecated: Use the '--hip' option instead")]
csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
disable_ipv6: bool,
#[arg(
long,
help = "The user agent to use, if not specified, it will be generated based on the OS and client version"
)]
user_agent: Option<String>,
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os,
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>,
#[arg(long, help = "The GP client version to emulate, e.g., '6.2.4-49'")]
client_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
local_hostname: Option<String>,
#[arg(
long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command"
)]
dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
no_xmlpost: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
default_browser: bool,
#[cfg(feature = "webview-auth")]
#[arg(
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.",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
}
impl ConnectArgs {
fn default_os() -> Os {
#[cfg(target_os = "macos")]
return Os::Mac;
#[cfg(target_os = "windows")]
return Os::Windows;
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
return Os::Linux;
}
fn os_version(&self) -> &str {
if let Some(os_version) = self.os_version.as_deref() {
return os_version;
}
match self.os {
Os::Linux => host_utils::get_linux_os_string(),
Os::Windows => host_utils::get_windows_os_string(),
Os::Mac => host_utils::get_macos_os_string(),
}
}
}
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs<'a>,
latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
Self {
args,
shared_args,
latest_key_password: Default::default(),
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
}
}
fn user_agent(&self) -> Cow<'_, str> {
if let Some(user_agent) = self.args.user_agent.as_deref() {
Cow::Borrowed(user_agent)
} else {
let client_version = self.args.client_version.as_deref().unwrap_or(GP_CLIENT_VERSION);
Cow::Owned(format!(
"{}/{} ({})",
GP_USER_AGENT,
client_version,
self.args.os_version()
))
}
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder();
builder
.user_agent(&self.user_agent())
.client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version().to_owned())
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone());
if let Some(local_hostname) = self.args.local_hostname.as_deref() {
builder.computer(local_hostname);
}
builder.build()
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
#[cfg(feature = "webview-auth")]
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
// Warn if deprecated options are used and will be removed in the future
if self.args.csd_user.is_some() {
warn!(
"The '--csd-user' option is deprecated and will be removed in future releases, please use the '--hip-user' option instead"
);
}
if self.args.csd_wrapper.is_some() {
warn!(
"The '--csd-wrapper' option is deprecated and will be removed in future releases, please use the '--hip' option instead"
);
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
// Decrypt the private key error, ask for the key password
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
if as_gateway {
info!("Treating the server as a gateway");
return self
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
.await;
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
.await?;
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.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
portal_config.sort_gateways(prelogin.region());
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into();
let login_session = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(login_session) => login_session,
Err(err) => {
info!("Gateway login failed: {}", err);
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
return self
.connect_gateway_with_prelogin(portal, gateway, client_version, allow_extend_session)
.await;
}
};
// Use the client version from the command line argument if specified, otherwise
// use the version from the portal config if available
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
}
async fn connect_gateway_with_prelogin(
&self,
portal: &str,
gateway: &str,
client_version: Option<&str>,
allow_extend_session: bool,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let login_session = self.login_gateway(gateway, &cred, &gp_params).await?;
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
}
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(
&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 (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user)?;
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned();
let os_version = self.args.os_version().to_owned();
let client_version = client_version.map(|s| s.to_owned());
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
user_agent: self.user_agent().into_owned(),
os: ClientOs::from(&self.args.os),
os_version: os_version.clone(),
client_version: client_version.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
.script_tun(self.args.script_tun)
.user_agent(self.user_agent().into_owned())
.os(Some(os))
.os_version(Some(os_version))
.client_version(client_version)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.hip(hip)
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost)
.build()?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
// Listen for the interrupt signal in the background
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
vpn_clone.disconnect();
});
vpn.connect(move |vpn_session_info| {
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
fs::remove_file(GP_CLIENT_LOCK_FILE)?;
}
Ok(())
}
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
if self.args.cookie_on_stdin {
return self.read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let browser = if prelogin.support_default_browser() {
self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") {
bail!(
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
);
} else {
None
};
let os_version = self.args.os_version();
let verbose = self.shared_args.verbose.to_verbose_arg();
let user_agent = self.user_agent();
let auth_launcher = SamlAuthLauncher::new(&self.args.server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.user_agent(&user_agent)
.os(self.args.os.as_str())
.os_version(Some(&os_version))
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser)
.verbose(verbose);
#[cfg(feature = "webview-auth")]
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher
.hidpi(self.args.hidpi)
.clean(self.args.clean)
.default_browser(use_default_browser);
let cred = auth_launcher.launch().await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = self.obtain_password(prelogin)?;
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
// If the cookie has been read from stdin, use it directly
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
info!("Reusing the cookie read from standard input");
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
}
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
// Considering that the gateway connection may fail even though the cookie read
// from stdin is correct. It may retry the gateway connection, so we need to
// save the cookie read from stdin to avoid reading stdin again.
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
Credential::try_from(auth_result)
}
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
let password = if self.args.passwd_on_stdin {
// If the password has been read from stdin, use it directly
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
info!("Reusing the password read from standard input");
return Ok(password.clone());
}
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let password = input.trim_end().to_owned();
// Considering that the gateway connection may fail even though the password read
// from stdin is correct. It may retry the gateway connection, so we need to
// save the password read from stdin to avoid reading stdin again.
self.password_from_stdin.replace(Some(password.clone()));
password
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
Ok(password)
}
fn determine_hip_script(&self) -> (bool, Option<String>) {
if let Some(hip) = &self.args.hip {
return if hip.is_empty() {
(true, None)
} else {
(true, Some(hip.clone()))
};
}
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
}
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
}
self.args.csd_user.clone()
}
}
fn write_pid_file() {
let pid = std::process::id();
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) {
warn!("Failed to write PID file: {}", err);
} else {
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
}
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
if let Some(user) = user {
get_user_by_name(user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
+401
View File
@@ -0,0 +1,401 @@
use clap::Args;
use gpapi::{
clap::args::Os,
cookie_store,
gp_params::CscMode,
os_profile::{ClientOs, OsProfile},
};
use log::warn;
use std::path::PathBuf;
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
pub(super) gateway: Option<String>,
#[arg(
long,
conflicts_with = "gateway",
help = "Automatically try gateways in priority order until gateway auth/config succeeds, without prompting"
)]
pub(super) auto_gateway: bool,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
pub(super) user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
pub(super) passwd_on_stdin: bool,
#[arg(long, help = "Read the gpauth authentication result from standard input")]
pub(super) cookie_on_stdin: bool,
#[arg(
long,
help = "Read and write the portal cookie cache, optionally specify the cache file path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) cookie_cache: Option<String>,
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
pub(super) script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
pub(super) interface: Option<String>,
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
pub(super) script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
pub(super) as_gateway: bool,
#[arg(
long,
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) hip: Option<String>,
#[arg(long, help = "The user used to run the HIP script")]
pub(super) hip_user: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
pub(super) certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
pub(super) sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
pub(super) key_password: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_user: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
pub(super) reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
pub(super) mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
pub(super) disable_ipv6: bool,
#[arg(long = "user-agent", hide = true)]
pub(super) deprecated_user_agent: Option<String>,
#[arg(long = "os-version", hide = true)]
pub(super) deprecated_os_version: Option<String>,
#[arg(long, help = "Override the client version reported to the server, e.g., '6.2.4-49'")]
pub(super) client_version: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())]
pub(super) os: Os,
#[arg(long, value_enum, default_value_t = CscMode::Auto, help = "CSC support mode: auto, yes, or no")]
pub(super) csc: CscMode,
#[arg(long, help = "Disable DTLS and ESP")]
pub(super) no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
pub(super) local_hostname: Option<String>,
#[arg(
long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command"
)]
pub(super) dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
pub(super) no_xmlpost: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
pub(super) hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
pub(super) clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
pub(super) default_browser: bool,
#[arg(
long,
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
default_missing_value = "auto",
num_args=0..=1
)]
pub(super) browser: Option<String>,
}
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
build_os_profile_with_host_id(args, None)
}
pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<&str>) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(args.os));
if let Some(client_version) = args.client_version.as_deref() {
builder = builder.client_version(client_version.to_string());
}
if let Some(local_hostname) = args.local_hostname.as_deref() {
builder = builder.computer_name_override(local_hostname.to_string());
}
if let Some(host_id) = host_id {
builder = builder.host_id_override(host_id);
}
builder.build()
}
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
args.cookie_cache.as_deref().map(|path| {
let custom = (!path.is_empty()).then_some(path);
cookie_store::cookie_path(custom)
})
}
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
if args.csd_user.is_some() {
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
}
if args.csd_wrapper.is_some() {
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
}
if args.deprecated_user_agent.is_some() {
warn!("Deprecated option --user-agent is ignored; user agent is derived from --os");
}
if args.deprecated_os_version.is_some() {
warn!("Deprecated option --os-version is ignored; OS version is derived from --os");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(clap::Parser)]
struct ConnectArgsTestCli {
#[command(flatten)]
args: ConnectArgs,
}
#[test]
fn parses_csc_mode_values() {
use clap::ValueEnum;
assert_eq!(CscMode::from_str("auto", false), Ok(CscMode::Auto));
assert_eq!(CscMode::from_str("yes", false), Ok(CscMode::Yes));
assert_eq!(CscMode::from_str("no", false), Ok(CscMode::No));
assert!(CscMode::from_str("maybe", false).is_err());
}
#[test]
fn auto_gateway_flag_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--auto-gateway"])
.expect("--auto-gateway alone should parse");
assert!(cli.args.auto_gateway);
assert!(cli.args.gateway.is_none());
}
#[test]
fn auto_gateway_help_describes_auth_config_retry() {
use clap::CommandFactory;
let help = ConnectArgsTestCli::command().render_long_help().to_string();
assert!(help.contains("--auto-gateway"));
assert!(help.contains("Automatically try gateways in priority order until gateway auth/config succeeds"));
}
#[test]
fn gateway_flag_alone_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1"])
.expect("--gateway alone should parse");
assert!(!cli.args.auto_gateway);
assert_eq!(cli.args.gateway.as_deref(), Some("gw1"));
}
#[test]
fn browser_without_value_uses_auto_mode() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser"])
.expect("--browser without value should parse");
assert_eq!(cli.args.browser.as_deref(), Some("auto"));
}
#[test]
fn browser_default_keeps_system_default_mode() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser", "default"])
.expect("--browser default should parse");
assert_eq!(cli.args.browser.as_deref(), Some("default"));
}
#[test]
fn os_defaults_to_runtime_os() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert_eq!(cli.args.os, Os::default());
}
#[test]
fn deprecated_profile_override_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
assert_eq!(cli.args.deprecated_user_agent.as_deref(), Some("legacy-agent"));
assert_eq!(cli.args.deprecated_os_version.as_deref(), Some("legacy-os"));
assert_eq!(cli.args.client_version.as_deref(), Some("legacy-client"));
}
#[test]
fn deprecated_profile_override_flags_do_not_affect_os_profile() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--os",
"Linux",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
let profile = build_os_profile(&cli.args);
assert_ne!(profile.user_agent(), "legacy-agent");
assert_ne!(profile.os_version(), "legacy-os");
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn stdin_host_id_sets_profile_runtime_identity_seed() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--os", "Linux"])
.expect("connect args should parse");
let profile = build_os_profile_with_host_id(&cli.args, Some("auth-host-id"));
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn cookie_cache_is_disabled_by_default() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert!(cli.args.cookie_cache.is_none());
assert!(cookie_cache_path(&cli.args).is_none());
}
#[test]
fn cookie_cache_accepts_default_path_without_value() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache"])
.expect("--cookie-cache without value should parse");
assert_eq!(cli.args.cookie_cache.as_deref(), Some(""));
assert!(cookie_cache_path(&cli.args).is_some());
}
#[test]
fn cookie_cache_accepts_custom_path() {
use clap::Parser;
let cli =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache", "/tmp/gp-cookie.json"])
.expect("--cookie-cache with value should parse");
assert_eq!(
cookie_cache_path(&cli.args).as_deref(),
Some(std::path::Path::new("/tmp/gp-cookie.json"))
);
}
#[test]
fn deprecated_hip_alias_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--csd-user",
"legacy-user",
"--csd-wrapper",
"/tmp/legacy-hip.sh",
])
.expect("deprecated HIP alias flags should remain parse-compatible");
assert_eq!(cli.args.csd_user.as_deref(), Some("legacy-user"));
assert_eq!(cli.args.csd_wrapper.as_deref(), Some("/tmp/legacy-hip.sh"));
}
#[test]
fn auto_gateway_and_gateway_are_mutually_exclusive() {
use clap::Parser;
use clap::error::ErrorKind;
let result =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1", "--auto-gateway"]);
let err = match result {
Ok(_) => panic!("--gateway and --auto-gateway must conflict"),
Err(err) => err,
};
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
}
+271
View File
@@ -0,0 +1,271 @@
use anyhow::{Context, bail};
use gpapi::{
auth::SamlAuthResult,
clap::ToVerboseArg,
credential::{Credential, PasswordCredential},
portal::{Prelogin, StandardPrelogin},
process::auth_launcher::SamlAuthLauncher,
};
use inquire::{Password, PasswordDisplayMode, Text};
use log::info;
use super::ConnectHandler;
#[derive(Default)]
pub(super) struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
pub(super) 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
}
}
impl ConnectHandler<'_> {
pub(super) fn prepare_cookie_from_stdin(&self) -> anyhow::Result<()> {
if !self.args.cookie_on_stdin || self.cookie_from_stdin.borrow().is_some() {
return Ok(());
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Ok(())
}
pub(super) async fn obtain_credential(
&self,
prelogin: &Prelogin,
server: &str,
gateway_browser_auth_allowed: bool,
) -> anyhow::Result<Credential> {
if should_read_stdin_credential(self.args.cookie_on_stdin, self.args.as_gateway, prelogin.is_gateway()) {
return self.read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let external_browser_supported = can_use_external_browser_auth(
prelogin.support_default_browser(),
is_gateway,
gateway_browser_auth_allowed,
);
let browser = if external_browser_supported {
self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") {
bail!(
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
);
} else {
None
};
let verbose = self.shared_args.verbose.to_verbose_arg();
let os_profile = self.os_profile.borrow().clone();
let key_password = self.latest_key_password.borrow().clone();
let auth_launcher = SamlAuthLauncher::new(server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.os_profile(&os_profile)
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.as_deref())
.sslkey(self.args.sslkey.as_deref())
.key_password(key_password.as_deref())
.browser(browser)
.verbose(verbose);
#[cfg(feature = "webview-auth")]
let use_default_browser = external_browser_supported && 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")]
let auth_launcher = auth_launcher
.hidpi(self.args.hidpi)
.clean(clean_auth)
.default_browser(use_default_browser);
let cred = auth_launcher.launch().await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = self.obtain_password(prelogin)?;
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
info!("Reusing the cookie read from standard input");
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Credential::try_from(auth_result)
}
fn read_auth_result_from_stdin(&self) -> anyhow::Result<SamlAuthResult> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
Ok(auth_result)
}
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
let password = if self.args.passwd_on_stdin {
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
info!("Reusing the password read from standard input");
return Ok(password.clone());
}
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let password = input.trim_end().to_owned();
self.password_from_stdin.replace(Some(password.clone()));
password
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
Ok(password)
}
}
fn should_read_stdin_credential(cookie_on_stdin: bool, as_gateway: bool, prelogin_is_gateway: bool) -> bool {
cookie_on_stdin && (!prelogin_is_gateway || as_gateway)
}
fn can_use_external_browser_auth(
saml_support_default_browser: bool,
is_gateway: bool,
gateway_browser_auth_allowed: bool,
) -> bool {
saml_support_default_browser && (!is_gateway || gateway_browser_auth_allowed)
}
fn log_stdin_host_id(host_id: Option<&str>) {
match host_id {
Some(host_id) => info!("stdin auth result host-id: {}", host_id),
None => info!("stdin auth result host-id: <none>"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_auth_state_is_consumed_once_for_webview() {
let mut state = CleanAuthState::new(true);
assert!(state.consume_for_webview(true));
assert!(!state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_is_not_consumed_by_external_browser() {
let mut state = CleanAuthState::new(true);
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));
}
#[test]
fn stdin_credential_is_allowed_for_portal_auth() {
assert!(should_read_stdin_credential(true, false, false));
}
#[test]
fn stdin_credential_is_allowed_for_direct_gateway_auth() {
assert!(should_read_stdin_credential(true, true, true));
}
#[test]
fn stdin_credential_is_not_reused_for_gateway_fallback_auth() {
assert!(!should_read_stdin_credential(true, false, true));
}
#[test]
fn stdin_credential_is_not_used_when_flag_is_disabled() {
assert!(!should_read_stdin_credential(false, false, false));
assert!(!should_read_stdin_credential(false, true, true));
}
#[test]
fn portal_saml_can_use_default_browser_when_supported() {
assert!(can_use_external_browser_auth(true, false, false));
}
#[test]
fn gateway_saml_requires_gateway_browser_auth_allowance() {
assert!(!can_use_external_browser_auth(true, true, false));
assert!(can_use_external_browser_auth(true, true, true));
}
#[test]
fn default_browser_auth_requires_saml_support() {
assert!(!can_use_external_browser_auth(false, false, true));
assert!(!can_use_external_browser_auth(false, true, true));
}
}
+505
View File
@@ -0,0 +1,505 @@
use std::{
fs,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
};
use gpapi::{
cookie_store,
credential::{AuthCookieCredential, Credential},
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
gp_params::GpParams,
os_profile::OsProfile,
portal::prelogin,
process::users::{get_non_root_user, get_user_by_name},
utils::shutdown_signal,
};
use inquire::Text;
use log::{info, warn};
use openconnect::{Vpn, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{
GP_CLIENT_LOCK_FILE,
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
use super::{ConnectHandler, args::cookie_cache_path};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GatewayConnectFailureStage {
BeforeTunnel,
AfterTunnel,
}
#[derive(Debug)]
pub(super) struct GatewayConnectError {
stage: GatewayConnectFailureStage,
error: anyhow::Error,
}
impl GatewayConnectError {
fn before_tunnel(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::BeforeTunnel,
error,
}
}
fn after_tunnel(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::AfterTunnel,
error,
}
}
pub(super) fn is_before_tunnel(&self) -> bool {
self.stage == GatewayConnectFailureStage::BeforeTunnel
}
pub(super) fn as_error(&self) -> &anyhow::Error {
&self.error
}
pub(super) fn into_error(self) -> anyhow::Error {
self.error
}
}
impl ConnectHandler<'_> {
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<()> {
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
if !stored.auth_cookie.can_authenticate_gateway() {
warn!(
"Cached portal cookie for {} is not usable for gateway authentication. Clearing cache.",
stored.server
);
cookie_store::clear(&path);
return None;
}
info!(
"Using cached portal cookie for {} (saved_at={}, gateway={})",
stored.server, stored.saved_at, stored.last_gateway
);
let cred: Credential = (&stored.auth_cookie).into();
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params, None).await {
Ok(session) => session,
Err(err) => {
warn!(
"Cached portal cookie rejected by gateway {}: {}. Clearing cache and falling back to portal auth.",
stored.last_gateway, err
);
cookie_store::clear(&path);
return None;
}
};
match self
.connect_gateway(
server,
&stored.last_gateway,
&login_session.cookie,
false,
login_session.extension_auth,
)
.await
{
Ok(()) => Some(()),
Err(err) => {
warn!("Gateway connect failed after cached-cookie login: {}", err.as_error());
None
}
}
}
pub(super) async fn connect_gateway_with_prelogin(
&self,
portal: &str,
gateway: &str,
allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let gateway_browser_auth_allowed = true;
let prelogin = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()).await?;
let cred = self
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
.await?;
let login_session = self
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.await?;
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await
.map_err(GatewayConnectError::into_error)
}
/// Connect to a gateway using the official client's auth flow:
///
/// 1. Call gateway prelogin and retain the response (SAML data is held as a fallback).
/// 2. If the portal provided auth cookies, attempt gateway login using them.
/// 3. If that login succeeds, proceed directly to the VPN connection.
/// 4. If no portal auth cookies exist or portal-cookie login fails, use the retained gateway prelogin response to authenticate
/// against the gateway (SAML or username/password) and obtain a gateway-issued
/// credential.
/// 5. Retry gateway login with the gateway credential (now carrying the gateway's
/// `prelogin-cookie`) and connect on success.
pub(super) async fn connect_gateway_with_fallback(
&self,
portal: &str,
gateway: &str,
portal_cred: &AuthCookieCredential,
allow_extend_session: bool,
portal_config_default_browser: bool,
gateway_context: GatewayLoginContext,
) -> Result<(), GatewayConnectError> {
info!("Connecting to gateway with portal-cookie first, gateway prelogin fallback...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let gateway_browser_auth_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
let gateway_prelogin = prelogin(gateway, &gp_params, self.prelogin_options(gateway_browser_auth_allowed))
.await
.map_err(GatewayConnectError::before_tunnel)?;
if portal_cred.can_authenticate_gateway() {
let portal_cred_for_login: Credential = portal_cred.into();
match self
.login_gateway(gateway, &portal_cred_for_login, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => {
info!("Gateway login with portal auth cookies succeeded");
self.save_cookie_cache(portal, gateway, portal_cred);
return self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await;
}
Err(err) => {
info!("Gateway login with portal auth cookies failed: {}", err);
info!("Falling back to gateway prelogin authentication...");
}
}
} else {
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
}
let gateway_cred = match self
.obtain_credential(&gateway_prelogin, gateway, gateway_browser_auth_allowed)
.await
{
Ok(cred) => cred,
Err(err) => {
self.print_direct_gateway_recommendation(gateway);
return Err(GatewayConnectError::before_tunnel(err));
}
};
let login_session = match self
.login_gateway(gateway, &gateway_cred, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => login_session,
Err(err) => {
self.print_direct_gateway_recommendation(gateway);
return Err(GatewayConnectError::before_tunnel(err));
}
};
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
allow_extend_session,
login_session.extension_auth,
)
.await
}
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
let Some(path) = cookie_cache_path(self.args) else {
return;
};
if !auth_cookie.can_authenticate_gateway() {
return;
}
let stored = cookie_store::StoredCookie::new(
portal.to_string(),
auth_cookie.username().to_string(),
self.os_profile.borrow().host_identity().host_id().to_string(),
gateway.to_string(),
auth_cookie.clone(),
);
match cookie_store::save(&path, &stored) {
Ok(()) => info!("Saved portal cookie cache to {}", path.display()),
Err(err) => warn!("Failed to save portal cookie cache to {}: {}", path.display(), err),
}
}
fn print_direct_gateway_recommendation(&self, gateway: &str) {
if !self.args.cookie_on_stdin {
return;
}
eprintln!("\nNOTE: Gateway authentication failed after portal login.");
eprintln!("NOTE: If this server also accepts direct gateway login, try:");
eprintln!("NOTE: {}", direct_gateway_command(gateway));
}
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
loop {
let login = match gateway_context {
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?,
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) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(
&self,
portal: &str,
gateway: &str,
cookie: &str,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> Result<(), GatewayConnectError> {
let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user).map_err(GatewayConnectError::before_tunnel)?;
let os_profile = self.os_profile.borrow().clone();
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
os_profile: os_profile.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_builder = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
.script_tun(self.args.script_tun)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.hip(hip)
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost);
let vpn = apply_os_profile(vpn_builder, &os_profile)
.build()
.map_err(|err| GatewayConnectError::before_tunnel(err.into()))?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
let tunnel_established = Arc::new(AtomicBool::new(false));
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
vpn_clone.disconnect();
});
let connect_result = vpn.connect(move |vpn_session_info| {
tunnel_established_on_connect.store(true, Ordering::SeqCst);
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);
});
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
fs::remove_file(GP_CLIENT_LOCK_FILE).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
}
classify_openconnect_result(connect_result, tunnel_established)
}
fn determine_hip_script(&self) -> (bool, Option<String>) {
if let Some(hip) = &self.args.hip {
return if hip.is_empty() {
(true, None)
} else {
(true, Some(hip.clone()))
};
}
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
}
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
}
self.args.csd_user.clone()
}
}
fn classify_openconnect_result(exit_code: i32, tunnel_established: bool) -> Result<(), GatewayConnectError> {
if exit_code == 0 {
return Ok(());
}
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
if tunnel_established {
Err(GatewayConnectError::after_tunnel(error))
} else {
Err(GatewayConnectError::before_tunnel(error))
}
}
fn direct_gateway_command(gateway: &str) -> String {
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
}
fn write_pid_file() {
let pid = std::process::id();
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) {
warn!("Failed to write PID file: {}", err);
} else {
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
}
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
if let Some(user) = user {
get_user_by_name(user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
builder
.os(Some(profile.client_os().to_openconnect_os().to_string()))
.os_version(Some(profile.os_version().to_string()))
.client_version(Some(profile.client_version().to_string()))
.host_id(Some(profile.host_identity().host_id().to_string()))
.user_agent(Some(profile.user_agent().to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn openconnect_success_is_not_a_gateway_failure() {
assert!(classify_openconnect_result(0, false).is_ok());
assert!(classify_openconnect_result(0, true).is_ok());
}
#[test]
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
let err = classify_openconnect_result(1, false).expect_err("nonzero exit should fail");
assert!(err.is_before_tunnel());
}
#[test]
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
let err = classify_openconnect_result(1, true).expect_err("nonzero exit should fail");
assert!(!err.is_before_tunnel());
}
#[test]
fn direct_gateway_recommendation_uses_gateway_server() {
assert_eq!(
direct_gateway_command("gateway.example.test"),
"gpauth --gateway gateway.example.test | sudo gpclient connect gateway.example.test --as-gateway --cookie-on-stdin"
);
}
}
+314
View File
@@ -0,0 +1,314 @@
mod args;
mod credential;
mod gateway;
use std::cell::RefCell;
use anyhow::bail;
use gpapi::{
error::PortalError,
gateway::{GatewayLoginContext, GatewaySelection},
gp_params::GpParams,
os_profile::OsProfile,
portal::{PreloginOptions, prelogin, retrieve_config},
utils::request::RequestIdentityError,
};
use inquire::{Password, PasswordDisplayMode, Select};
use log::{info, warn};
use crate::cli::SharedArgs;
pub(crate) use args::ConnectArgs;
use args::{build_os_profile, build_os_profile_with_host_id, warn_deprecated_connect_args};
use credential::CleanAuthState;
use gateway::GatewayConnectError;
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs<'a>,
os_profile: RefCell<OsProfile>,
latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
warn_deprecated_connect_args(args);
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self {
args,
shared_args,
os_profile: RefCell::new(build_os_profile(args)),
latest_key_password: Default::default(),
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
}
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(self.os_profile.borrow().clone());
builder
.csc_mode(self.args.csc)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone());
builder.build()
}
pub(super) fn prelogin_options(&self, gateway_browser_auth_allowed: bool) -> PreloginOptions {
PreloginOptions::default()
.external_browser_requested(self.external_browser_requested())
.gateway_external_browser_allowed(gateway_browser_auth_allowed)
}
pub(super) fn direct_gateway_prelogin_options(&self) -> PreloginOptions {
self.prelogin_options(true)
}
pub(super) fn gateway_browser_auth_allowed(&self, portal_config_default_browser: bool) -> bool {
gateway_browser_auth_allowed(portal_config_default_browser, self.external_browser_requested())
}
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.args.default_browser || self.args.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
self.args.browser.is_some()
}
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
#[cfg(feature = "webview-auth")]
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
self.prepare_cookie_from_stdin()?;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server, server, false, None).await;
}
if !self.args.cookie_on_stdin {
if let Some(()) = self.try_cached_cookie(server).await {
return Ok(());
}
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server, server, false, None).await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
let cred = self.obtain_credential(&prelogin, portal, false).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
portal_config.sort_gateways(prelogin.region());
let auth_cookie = match cred.password() {
Some(password) => portal_config.auth_cookie().clone().with_password(password),
None => portal_config.auth_cookie().clone(),
};
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
info!("Portal config default-browser: {}", portal_config_default_browser);
if self.args.auto_gateway {
let gateways = portal_config.gateways();
if gateways.is_empty() {
bail!("No gateways available in portal config for auto-gateway selection");
}
info!(
"Auto-gateway mode: trying {} gateway(s) in priority order",
gateways.len()
);
let mut last_err: Option<anyhow::Error> = None;
for gateway in &gateways {
info!("Auto-gateway: attempting gateway {}", gateway);
let gateway_context =
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(portal_config.connect_method());
match self
.connect_gateway_with_fallback(
portal,
gateway.server(),
&auth_cookie,
allow_extend_session,
portal_config_default_browser,
gateway_context,
)
.await
{
Ok(()) => return Ok(()),
Err(err) => {
if !err.is_before_tunnel() {
return Err(err.into_error());
}
warn!(
"Auto-gateway: gateway {} failed before tunnel setup: {}",
gateway,
err.as_error()
);
last_err = Some(err.into_error());
}
}
}
let detail = last_err
.map(|e| e.to_string())
.unwrap_or_else(|| "unknown error".to_string());
bail!(
"Auto-gateway: all {} gateway(s) failed to connect; last error: {}",
gateways.len(),
detail
);
}
let gateway_selection = if self.args.gateway.is_some() {
GatewaySelection::Manual
} else {
GatewaySelection::Auto
};
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let gateway_context =
GatewayLoginContext::new(selected_gateway, gateway_selection).with_connect_method(portal_config.connect_method());
self
.connect_gateway_with_fallback(
portal,
gateway,
&auth_cookie,
allow_extend_session,
portal_config_default_browser,
gateway_context,
)
.await
.map_err(GatewayConnectError::into_error)
}
fn apply_stdin_host_id(&self, host_id: Option<&str>) {
let Some(host_id) = host_id else {
return;
};
self
.os_profile
.replace(build_os_profile_with_host_id(self.args, Some(host_id)));
info!(
"connect profile host-id: {}",
self.os_profile.borrow().host_identity().host_id()
);
}
}
fn gateway_browser_auth_allowed(portal_config_default_browser: bool, external_browser_requested: bool) -> bool {
portal_config_default_browser || external_browser_requested
}
#[cfg(test)]
mod tests {
use super::gateway_browser_auth_allowed;
#[test]
fn gateway_browser_auth_is_allowed_by_portal_config() {
assert!(gateway_browser_auth_allowed(true, false));
}
#[test]
fn gateway_browser_auth_is_allowed_by_explicit_browser_request() {
assert!(gateway_browser_auth_allowed(false, true));
}
#[test]
fn gateway_browser_auth_is_disabled_without_portal_config_or_user_request() {
assert!(!gateway_browser_auth_allowed(false, false));
}
}
+343 -137
View File
@@ -1,8 +1,13 @@
use askama::Template;
use clap::Args;
use gpapi::{clap::args::Os, utils::host_utils};
use gpapi::{
clap::args::Os,
os_profile::{ClientOs, OsProfile, OsProfileBuilder},
};
use log::debug;
use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use xmltree::Element;
#[derive(Template)]
@@ -14,27 +19,45 @@ struct HipReportTemplate<'a> {
month: String,
year: String,
user_name: &'a str,
host_info: HostInfo<'a>,
host_info: HostInfo,
md5: &'a str,
}
#[derive(Debug, Clone, Deserialize)]
struct DefenderInfo {
#[serde(rename = "appVersion")]
app_version: String,
#[serde(rename = "engineVersion")]
engine_version: String,
#[serde(rename = "definitionsVersion")]
definitions_version: String,
#[serde(rename = "realTimeProtectionEnabled")]
real_time_protection_enabled: RealTimeProtection,
}
#[derive(Debug, Clone, Deserialize)]
struct RealTimeProtection {
value: bool,
}
/// Host information for HIP reporting
struct HostInfo<'a> {
struct HostInfo {
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
os_vendor: &'a str,
os_vendor: String,
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
os_version: &'a str,
/// Only for macOS and Windows
os_version: String,
/// Per-OS machine identifier (UUID for Linux/Windows, MAC for macOS)
host_id: String,
/// Common for all OSes
host_name: String,
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
software_version: &'a str,
software_version: String,
domain: String,
network_interfaces: Vec<NetworkInterface>,
defender: Option<DefenderInfo>,
}
impl<'a> HostInfo<'a> {
impl HostInfo {
/// Get the first available IPv4 address from network interfaces
pub fn default_ipv4(&self) -> &str {
self
@@ -103,8 +126,11 @@ pub(crate) struct HipArgs {
#[arg(long, value_enum, help = "The client OS")]
client_os: Os,
#[arg(long, help = "The OS version string, e.g., Apple Mac OS X 10.15.7")]
os_version: String,
#[arg(long, hide = true)]
os_version: Option<String>,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "The authentication cookie")]
cookie: String,
@@ -121,11 +147,13 @@ pub(crate) struct HipArgs {
pub(crate) struct HipHandler<'a> {
args: &'a HipArgs,
profile: OsProfile,
}
impl<'a> HipHandler<'a> {
pub(crate) fn new(args: &'a HipArgs) -> Self {
Self { args }
let profile = build_os_profile(args);
Self { args, profile }
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
@@ -164,34 +192,57 @@ impl<'a> HipHandler<'a> {
format_xml(&report)
}
/// Collect host information based on the client OS
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo<'a> {
let collector = HostInfoCollector::new(self.args, cookie_params);
match self.args.client_os {
Os::Linux => collector.collect_linux(),
Os::Mac => collector.collect_macos(),
Os::Windows => collector.collect_windows(),
}
/// Collect host information using the configured OsProfile.
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo {
HostInfoCollector::new(&self.profile, self.args, cookie_params).collect()
}
}
/// Construct an `OsProfile` from CLI args, falling back to per-OS defaults
/// for any value not supplied on the command line.
fn build_os_profile(args: &HipArgs) -> OsProfile {
let client_os = ClientOs::from(args.client_os);
let mut builder = OsProfileBuilder::new(client_os).client_version(args.client_version.clone());
if let Some(host_id) = args.host_id.as_deref() {
debug!("HIP host-id override supplied: {}", host_id);
builder = builder.host_id_override(host_id);
}
let profile = builder.build();
debug!(
"HIP OS profile host-id: runtime={}, projected={}, client_os={}",
profile.host_identity().host_id(),
profile.host_id(),
client_os.as_str()
);
profile
}
// ============================================================================
// Host Information Collector
// ============================================================================
/// Helper struct for collecting host information
struct HostInfoCollector<'a> {
/// Helper struct for collecting host information.
///
/// Identity values (vendor, host_id, computer name, software version) come
/// from the configured `OsProfile`, while runtime state (network interfaces,
/// IP addresses) is enumerated here from the underlying machine.
struct HostInfoCollector<'p, 'a> {
profile: &'p OsProfile,
args: &'a HipArgs,
cookie_params: &'a HashMap<String, String>,
}
impl<'a> HostInfoCollector<'a> {
fn new(args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
Self { args, cookie_params }
impl<'p, 'a> HostInfoCollector<'p, 'a> {
fn new(profile: &'p OsProfile, args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
Self {
profile,
args,
cookie_params,
}
}
/// Get domain from cookie parameters
/// Domain belongs to the runtime user/session, not the simulated OS, so
/// it is sourced from the auth cookie when available.
fn get_domain(&self) -> String {
self
.cookie_params
@@ -217,125 +268,128 @@ impl<'a> HostInfoCollector<'a> {
}
}
/// Collect Linux-specific host information
fn collect_linux(&self) -> HostInfo<'a> {
let iface = self.collect_network_interface();
/// Single entry point for collecting host info — dispatches per-OS
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
fn collect(&self) -> HostInfo {
let runtime_iface = self.collect_network_interface();
let primary = self.adapt_primary_interface(&runtime_iface);
// Use the fixed interface name enp1s0f0 for Linux if it is not on Linux
let iface = NetworkInterface {
#[cfg(target_os = "linux")]
name: iface.name,
#[cfg(target_os = "linux")]
description: iface.description,
#[cfg(not(target_os = "linux"))]
name: "enp1s0f0".to_string(),
#[cfg(not(target_os = "linux"))]
description: "enp1s0f0".to_string(),
mac_address: iface.mac_address,
ipv4: iface.ipv4,
ipv6: iface.ipv6,
};
let mut interfaces = vec![primary.clone()];
interfaces.extend(self.extra_interfaces(&primary));
HostInfo {
os_vendor: "Linux",
os_version: &self.args.os_version,
host_id: host_utils::derive_uuid(&[]),
host_name: whoami::devicename(),
software_version: "",
domain: String::new(),
network_interfaces: vec![iface],
os_vendor: self.profile.os_vendor().to_string(),
os_version: self.profile.os_version().to_string(),
host_id: self.profile.host_id().to_string(),
host_name: self.profile.computer().to_string(),
software_version: self.profile.software_version().to_string(),
domain: self.domain_for_profile(),
network_interfaces: interfaces,
defender: self.defender_for_profile(),
}
}
/// Collect macOS-specific host information
fn collect_macos(&self) -> HostInfo<'a> {
let iface = self.collect_network_interface();
// macOS use the mac address as host ID
let host_id = iface
.mac_address
.as_ref()
.map(|s| s.to_string())
.unwrap_or_else(|| "00:00:00:00:00:00".to_string());
// Use the fixed interface name en0 for macOS if it is not on macOS
let iface = NetworkInterface {
#[cfg(target_os = "macos")]
name: iface.name,
#[cfg(target_os = "macos")]
description: iface.description,
#[cfg(not(target_os = "macos"))]
name: "en0".to_string(),
#[cfg(not(target_os = "macos"))]
description: "en0".to_string(),
mac_address: iface.mac_address,
ipv4: iface.ipv4,
ipv6: iface.ipv6,
/// Build the primary network interface with OS-appropriate naming and
/// MAC formatting. When emulating a different OS, the runtime interface
/// name/description are replaced with the canonical placeholder for the
/// target OS.
fn adapt_primary_interface(&self, runtime: &NetworkInterface) -> NetworkInterface {
let (name, description) = if self.profile.is_native() {
(runtime.name.clone(), runtime.description.clone())
} else {
placeholder_interface_for(self.profile, runtime)
};
HostInfo {
os_vendor: "Apple",
os_version: &self.args.os_version,
host_id,
host_name: whoami::devicename(),
software_version: host_utils::get_macos_version(),
domain: self.get_domain(),
network_interfaces: vec![iface],
NetworkInterface {
name,
description,
mac_address: format_mac_for(self.profile, runtime.mac_address.clone()),
ipv4: runtime.ipv4.clone(),
ipv6: runtime.ipv6.clone(),
}
}
/// Collect Windows-specific host information
fn collect_windows(&self) -> HostInfo<'a> {
// Use the actual machine ID on Windows
#[cfg(target_os = "windows")]
let host_id = host_utils::get_machine_id().to_string();
#[cfg(not(target_os = "windows"))]
let host_id = host_utils::derive_uuid(&[]);
let iface = self.collect_network_interface();
// Use the fixed interface name if it is not on Windows
let iface = NetworkInterface {
#[cfg(target_os = "windows")]
name: iface.name,
#[cfg(target_os = "windows")]
description: iface.description,
#[cfg(not(target_os = "windows"))]
name: derive_windows_network_name(&iface),
#[cfg(not(target_os = "windows"))]
description: "PANGP Virtual Ethernet Adapter Secure".to_string(),
// mac address on windows should replace ':' with '-'
mac_address: iface.mac_address.map(|mac| mac.replace(':', "-")),
ipv4: iface.ipv4,
ipv6: iface.ipv6,
};
// Add the local loopback interface
let loopback_iface = NetworkInterface {
name: derive_windows_network_name(&iface),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
};
let ifaces = vec![iface, loopback_iface];
HostInfo {
os_vendor: "Microsoft",
os_version: &self.args.os_version,
host_id,
host_name: whoami::devicename(),
software_version: host_utils::get_windows_version(),
domain: self.get_domain(),
network_interfaces: ifaces,
/// Additional interfaces appended after the primary. Only Windows
/// emits the software loopback interface in HIP reports.
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> {
match self.profile.client_os() {
ClientOs::Windows => vec![NetworkInterface {
name: derive_windows_network_name(self.profile.host_id(), primary),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
}],
ClientOs::Linux | ClientOs::Mac => vec![],
}
}
/// Linux HIP reports omit the domain field; macOS/Windows include it
/// from the auth cookie.
fn domain_for_profile(&self) -> String {
match self.profile.client_os() {
ClientOs::Linux => String::new(),
ClientOs::Mac | ClientOs::Windows => self.get_domain(),
}
}
fn defender_for_profile(&self) -> Option<DefenderInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_microsoft_defender_blocking(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
}
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
let output = Command::new("mdatp")
.arg("health")
.arg("--output")
.arg("json")
.output()
.ok()?;
if !output.status.success() {
debug!("mdatp health command failed");
return None;
}
let json = String::from_utf8(output.stdout).ok()?;
let defender = parse_defender_info(&json)?;
debug!("Detected Microsoft Defender: {:?}", defender);
Some(defender)
}
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
serde_json::from_str(json).ok()
}
// ============================================================================
// Per-OS interface helpers (selected via OsProfile, not cfg)
// ============================================================================
/// Canonical interface name/description for the target OS when the runtime
/// is a different OS (i.e. emulation).
fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> (String, String) {
match profile.client_os() {
ClientOs::Linux => ("enp1s0f0".to_string(), "enp1s0f0".to_string()),
ClientOs::Mac => ("en0".to_string(), "en0".to_string()),
ClientOs::Windows => (
derive_windows_network_name(profile.host_id(), runtime),
"PANGP Virtual Ethernet Adapter Secure".to_string(),
),
}
}
/// MAC address formatting per target OS. Windows uses hyphen separators;
/// Linux and macOS preserve the colon-separated form returned by the
/// platform.
fn format_mac_for(profile: &OsProfile, mac: Option<String>) -> Option<String> {
match profile.client_os() {
ClientOs::Windows => mac.map(|m| m.replace(':', "-")),
ClientOs::Linux | ClientOs::Mac => mac,
}
}
// ============================================================================
@@ -364,11 +418,163 @@ fn format_xml(xml_str: &str) -> anyhow::Result<String> {
Ok(String::from_utf8(xml_buf)?)
}
fn derive_windows_network_name(iface: &NetworkInterface) -> String {
let seeds = [
fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> String {
let seed = format!(
"{}-{}-{}",
host_id,
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
iface.name.as_str(),
];
iface.name
);
format!("{{{}}}", host_utils::derive_uuid(&seeds).to_uppercase())
format!(
"{{{}}}",
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, seed.as_bytes())
.to_string()
.to_uppercase()
)
}
#[cfg(test)]
mod tests {
use super::*;
use gpapi::os_profile::runtime_client_os;
fn make_hip_args(client_os: Os) -> HipArgs {
HipArgs {
client_version: "6.2.4-49".to_string(),
client_os,
os_version: Some("test-os-version".to_string()),
host_id: None,
cookie: String::new(),
client_ip: None,
client_ipv6: None,
md5: "deadbeef".to_string(),
}
}
fn make_profile(client_os: ClientOs) -> OsProfile {
OsProfileBuilder::new(client_os).build()
}
#[test]
fn host_info_os_vendor_is_linux_for_linux_profile() {
let args = make_hip_args(Os::Linux);
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Linux");
}
#[test]
fn host_info_os_vendor_is_apple_for_mac_profile() {
let args = make_hip_args(Os::Mac);
let profile = make_profile(ClientOs::Mac);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Apple");
}
#[test]
fn host_info_os_vendor_is_microsoft_for_windows_profile() {
let args = make_hip_args(Os::Windows);
let profile = make_profile(ClientOs::Windows);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_vendor, "Microsoft");
}
#[test]
fn host_info_host_id_comes_from_os_profile() {
let args = make_hip_args(Os::Linux);
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn host_info_host_id_independent_of_runtime_for_each_os() {
// host_id should reflect the OsProfile's machine identity for every
// simulated OS, regardless of the runtime platform.
for (client_os, os_arg) in [
(ClientOs::Linux, Os::Linux),
(ClientOs::Mac, Os::Mac),
(ClientOs::Windows, Os::Windows),
] {
let args = make_hip_args(os_arg);
let profile = make_profile(client_os);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
}
#[test]
fn hip_os_version_argument_is_ignored() {
let args = make_hip_args(Os::Linux);
let profile = build_os_profile(&args);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(info.os_version, profile.os_version());
assert_ne!(info.os_version, "test-os-version");
}
#[test]
fn host_id_argument_sets_profile_runtime_identity() {
let mut args = make_hip_args(Os::default());
args.host_id = Some("auth-host-id".to_string());
let profile = build_os_profile(&args);
assert_eq!(profile.client_os(), runtime_client_os());
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn host_info_uses_host_id_argument_for_native_profile() {
let mut args = make_hip_args(Os::default());
args.host_id = Some("auth-host-id".to_string());
let profile = build_os_profile(&args);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect();
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn parses_microsoft_defender_health_json() {
let defender = parse_defender_info(
r#"{
"appVersion": "101.25042.0000",
"engineVersion": "1.1.25040.2",
"definitionsVersion": "1.429.201.0",
"realTimeProtectionEnabled": { "value": true }
}"#,
)
.expect("defender health json should parse");
assert_eq!(defender.app_version, "101.25042.0000");
assert_eq!(defender.engine_version, "1.1.25040.2");
assert_eq!(defender.definitions_version, "1.429.201.0");
assert!(defender.real_time_protection_enabled.value);
}
#[test]
fn rejects_invalid_microsoft_defender_health_json() {
assert!(parse_defender_info("{}").is_none());
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ impl<'a> LaunchGuiHandler<'a> {
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
// `launch-gui`cannot be run as root
let user = whoami::username();
let user = whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))?;
if user == "root" {
anyhow::bail!("`launch-gui` cannot be run as root");
}
+14 -21
View File
@@ -1,9 +1,8 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session},
gp_params::ClientOs,
os_profile::OsProfile,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
@@ -21,10 +20,7 @@ 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) os_profile: OsProfile,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
@@ -34,12 +30,7 @@ pub(crate) struct SessionContextInput {
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_user_agent(input.os_profile.user_agent().to_string())
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
@@ -181,15 +172,17 @@ mod tests {
}
#[test]
fn builds_session_context_from_cli_runtime_values() {
fn builds_session_context_from_os_profile() {
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Mac)
.client_version("6.3.1-12".to_string())
.build();
let expected_user_agent = profile.user_agent().to_string();
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()),
os_profile: profile,
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
@@ -200,10 +193,10 @@ mod tests {
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().user_agent().as_deref(),
Some(expected_user_agent.as_str())
);
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"));
+13
View File
@@ -218,7 +218,20 @@
</entry>
{% elif host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
{% if let Some(defender) = &host_info.defender -%}
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>{% if defender.real_time_protection_enabled.value %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
{% else -%}
<list/>
{% endif -%}
</entry>
<entry name="disk-backup">
<list/>
+12 -12
View File
@@ -11,27 +11,27 @@
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.10",
"@mui/material": "^7.3.10",
"@tauri-apps/api": "^2.11.0",
"react": "^19.2.5",
"react-dom": "^19.2.5"
"@mui/icons-material": "^7.3.11",
"@mui/material": "^7.3.11",
"@tauri-apps/api": "^2.11.1",
"react": "^19.2.7",
"react-dom": "^19.2.7"
},
"devDependencies": {
"@tauri-apps/cli": "^2.11.1",
"@types/node": "^25.6.0",
"@types/react": "^19.2.14",
"@tauri-apps/cli": "^2.11.2",
"@types/node": "^25.9.4",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.59.2",
"@typescript-eslint/parser": "^8.59.2",
"@vitejs/plugin-react": "^6.0.1",
"@typescript-eslint/eslint-plugin": "^8.61.1",
"@typescript-eslint/parser": "^8.61.1",
"@vitejs/plugin-react": "^6.0.2",
"eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.8.3",
"typescript": "^6.0.3",
"vite": "^8.0.10"
"vite": "^8.0.16"
},
"packageManager": "[email protected]"
}
+571 -550
View File
File diff suppressed because it is too large. Load diff
+59
View File
@@ -1,3 +1,62 @@
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=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()
}
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())
}
+8 -1
View File
@@ -7,7 +7,14 @@ use log::info;
use crate::app::App;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const GP_API_KEY: &[u8; 32] = &[0; 32];
#[derive(Parser)]
+8 -2
View File
@@ -15,6 +15,12 @@ const SNAPSHOT: &str = match option_env!("SNAPSHOT") {
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 {
win: WebviewWindow,
}
@@ -110,8 +116,8 @@ impl GuiUpdater {
};
let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
release_tag, arch
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}{}.bin.tar.xz",
release_tag, arch, GUI_LIBC_SUFFIX
);
let checksum_url = format!("{}.sha256", file_url);
+60
View File
@@ -0,0 +1,60 @@
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())
}
+8 -1
View File
@@ -16,7 +16,14 @@ use tokio::sync::{mpsc, watch};
use crate::{vpn_task::VpnTask, ws_server::WsServer};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)]
#[command(version = VERSION)]
+7 -8
View File
@@ -3,7 +3,6 @@ use std::{
io::BufReader,
ops::ControlFlow,
os::unix::fs::PermissionsExt,
path::PathBuf,
sync::Arc,
};
@@ -17,7 +16,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
use common::constants::GP_GUI_BINARY;
use common::binary_paths;
use futures::{SinkExt, StreamExt};
use gpapi::{
service::{event::WsEvent, request::UpdateGuiRequest},
@@ -67,8 +66,8 @@ pub async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) ->
// Unpack GPGUI archive, gpgui_2.0.0_{arch}.bin.tar.xz and install it
async fn install_gui(src: &str) -> anyhow::Result<()> {
let path = PathBuf::from(GP_GUI_BINARY);
let Some(dir) = path.parent() else {
let target = binary_paths::gpgui();
let Some(dir) = target.parent() else {
bail!("Failed to get parent directory of GUI binary");
};
@@ -81,13 +80,13 @@ async fn install_gui(src: &str) -> anyhow::Result<()> {
for entry in ar.entries()? {
let mut entry = entry?;
let path = entry.path()?;
let entry_path = entry.path()?;
if let Some(name) = path.file_name() {
if let Some(name) = entry_path.file_name() {
let name = name.to_string_lossy();
if name == "gpgui" {
let mut file = File::create(GP_GUI_BINARY)?;
let mut file = File::create(&target)?;
std::io::copy(&mut entry, &mut file)?;
break;
}
@@ -95,7 +94,7 @@ async fn install_gui(src: &str) -> anyhow::Result<()> {
}
// Make the binary executable
fs::set_permissions(GP_GUI_BINARY, Permissions::from_mode(0o755)).await?;
fs::set_permissions(target, Permissions::from_mode(0o755)).await?;
Ok(())
}
+1
View File
@@ -46,6 +46,7 @@ impl VpnTaskContext {
.os(args.openconnect_os())
.os_version(args.os_version())
.client_version(args.client_version())
.host_id(args.host_id())
.certificate(args.certificate())
.sslkey(args.sslkey())
.key_password(args.key_password())
+14 -3
View File
@@ -1,9 +1,15 @@
use std::sync::Arc;
use axum::extract::ws::Message;
use common::constants::GP_AUTH_BINARY;
use common::binary_paths;
use gpapi::{
service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpn_state::VpnState},
os_profile::HostIdentity,
service::{
event::WsEvent,
request::WsRequest,
vpn_env::{HostInfo, VpnEnv},
vpn_state::VpnState,
},
utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction},
};
use log::{info, warn};
@@ -59,11 +65,16 @@ impl WsServerContext {
// Send current VPN state to new client
info!("Sending current environment to new client");
let host_info = HostInfo {
host_identity: HostIdentity::collect(),
};
let vpn_env = VpnEnv {
vpn_state: self.vpn_state_rx.borrow().clone(),
vpnc_script: find_vpnc_script().map(|s| s.to_owned()),
csd_wrapper: find_csd_wrapper().map(|s| s.to_owned()),
auth_executable: GP_AUTH_BINARY.to_owned(),
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
host_info,
};
if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await {
+58
View File
@@ -1,5 +1,63 @@
# Changelog
## 2.6.2
### Fixed
- Fixed gateway fallback browser authentication when external browser authentication is explicitly requested.
- Added logging for portal config default-browser behavior.
- Added GUI managed configuration support with `gpgui.conf`, including reset to managed config.
- Improved GUI config directory migration and managed license auto activation.
## 2.6.1
### Changed
- Improved external browser authentication so `--browser` chooses Chrome first, then Firefox, then the system default browser.
- Improved NixOS prebuilt package integration for launching helper binaries and desktop services.
- Updated the release process to publish GitHub release notes from the changelog.
### Fixed
- Fixed NixOS GUI launch failures caused by package-local binary paths.
- Fixed NixOS tray icon setup documentation for GNOME desktops.
- Fixed browser authentication for portals that require a client certificate.
- Fixed release automation so Nix flake hash updates are run manually after release assets are available.
## 2.6.0
### Added
- Added automatic gateway selection with fallback to the next available gateway when early gateway connection steps fail.
- Added optional cookie cache support for faster reconnects.
- Added Microsoft Defender status reporting in HIP reports.
- Added support for portals that require client-side checks before connection.
- Added FreeBSD and OpenBSD package builds and release artifacts.
- Added build provenance attestations for release assets.
### Changed
- Improved compatibility with official GlobalProtect client request behavior.
- Improved SAML authentication behavior in the embedded webview.
- Improved default browser authentication handling.
- Improved host identity consistency across authentication, connection, and HIP flows.
- Improved GUI gateway selection behavior and made the selection list more compact.
- Updated NixOS installation instructions.
### Fixed
- Fixed a crash when opening settings on KDE/Wayland.
- Fixed browser authentication when `gpclient` is started with `sudo`.
- Fixed gateway fallback behavior when using `gpauth | gpclient --cookie-on-stdin`.
- Fixed inconsistent host ID handling between GUI, CLI, OpenConnect, and HIP.
- Fixed portal and gateway authentication cookie handling in several edge cases.
- Fixed GUI connection state issues around gateway switching and cached credentials.
## 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)).
+1 -1
View File
@@ -29,7 +29,7 @@ regex = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true }
html-escape = { version = "0.2.13", optional = true }
[target.'cfg(not(target_os = "macos"))'.dependencies]
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
webkit2gtk = { version = "2", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
+5 -1
View File
@@ -1,7 +1,7 @@
use std::io::Cursor;
use log::info;
use tiny_http::{Header, Response, Server};
use tiny_http::{Header, Method, Response, Server};
use uuid::Uuid;
pub(super) struct AuthServer {
@@ -30,6 +30,10 @@ impl AuthServer {
if req.url() != format!("/{}", self.auth_id) {
let forbidden = Response::from_string("forbidden").with_status_code(403);
let _ = req.respond(forbidden);
} else if req.method() == &Method::Head {
if let Err(err) = req.respond(Response::empty(200)) {
info!("failed to respond to HEAD request: {}", err);
}
} else {
let auth_response = build_auth_response(auth_request);
if let Err(err) = req.respond(auth_response) {
+38 -9
View File
@@ -11,6 +11,7 @@ use tokio::{
use crate::browser::auth_server::AuthServer;
pub enum Browser<'a> {
Auto,
Default,
Chrome,
Firefox,
@@ -21,6 +22,7 @@ pub enum Browser<'a> {
impl<'a> Browser<'a> {
pub fn from_str(browser: &'a str) -> Self {
match browser.to_lowercase().as_str() {
"auto" => Browser::Auto,
"default" => Browser::Default,
"chrome" => Browser::Chrome,
"firefox" => Browser::Firefox,
@@ -31,6 +33,7 @@ impl<'a> Browser<'a> {
fn as_str(&self) -> &str {
match self {
Browser::Auto => "auto",
Browser::Default => "default",
Browser::Chrome => "chrome",
Browser::Firefox => "firefox",
@@ -87,6 +90,15 @@ Note that the URL is only valid for a single use.
info!("Launching the default browser...");
webbrowser::open(&auth_url)?;
}
Browser::Auto => {
if let Some(app) = find_auto_browser_path() {
info!("Launching browser: {}", app);
open::with_detached(&auth_url, app)?;
} else {
info!("No preferred browser found; launching the default browser...");
webbrowser::open(&auth_url)?;
}
}
_ => {
let app = find_browser_path(&self.browser);
@@ -124,19 +136,25 @@ async fn detect_local_ip() -> anyhow::Result<String> {
fn find_browser_path(browser: &Browser) -> String {
match browser {
Browser::Chrome => {
const CHROME_VARIANTS: &[&str] = &["google-chrome-stable", "google-chrome", "chromium"];
CHROME_VARIANTS
.iter()
.find_map(|&browser_name| which::which(browser_name).ok())
.map(|path| path.to_string_lossy().to_string())
.unwrap_or_else(|| browser.as_str().to_string())
}
Browser::Chrome => find_chrome_path().unwrap_or_else(|| browser.as_str().to_string()),
_ => browser.as_str().to_string(),
}
}
fn find_auto_browser_path() -> Option<String> {
find_chrome_path().or_else(|| find_program_path("firefox"))
}
fn find_chrome_path() -> Option<String> {
["google-chrome-stable", "google-chrome", "chromium"]
.iter()
.find_map(|browser_name| find_program_path(browser_name))
}
fn find_program_path(name: &str) -> Option<String> {
which::which(name).ok().map(|path| path.to_string_lossy().to_string())
}
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// Start a local server to receive the browser authentication data
let listener = TcpListener::bind("127.0.0.1:0").await?;
@@ -176,3 +194,14 @@ fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
let auth_data = SamlAuthData::from_gpcallback(data.trim())?;
Ok(auth_data)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn browser_auto_is_distinct_from_system_default() {
assert!(matches!(Browser::from_str("auto"), Browser::Auto));
assert!(matches!(Browser::from_str("default"), Browser::Default));
}
}
+11 -3
View File
@@ -1,7 +1,7 @@
use anyhow::bail;
use gpapi::{
gp_params::GpParams,
portal::{Prelogin, prelogin},
portal::{Prelogin, PreloginOptions, prelogin},
};
#[cfg(feature = "browser-auth")]
@@ -15,8 +15,16 @@ mod webview;
#[cfg(feature = "webview-auth")]
pub use webview::*;
pub async fn auth_prelogin(server: &str, gp_params: &GpParams) -> anyhow::Result<String> {
match prelogin(server, gp_params).await? {
pub async fn auth_prelogin(
server: &str,
gp_params: &GpParams,
external_browser_requested: bool,
gateway_external_browser_allowed: bool,
) -> anyhow::Result<String> {
let options = PreloginOptions::default()
.external_browser_requested(external_browser_requested)
.gateway_external_browser_allowed(gateway_external_browser_allowed);
match prelogin(server, gp_params, options).await? {
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
}
+14 -2
View File
@@ -1,8 +1,20 @@
mod auth_messenger;
mod webview_auth;
#[cfg_attr(not(target_os = "macos"), path = "webview/unix.rs")]
#[cfg_attr(target_os = "macos", path = "webview/macos.rs")]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[path = "webview/gtk.rs"]
mod platform_impl;
#[cfg(target_os = "macos")]
#[path = "webview/macos.rs"]
mod platform_impl;
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
pub use webview_auth::WebviewAuthenticator;
+4 -4
View File
@@ -7,7 +7,7 @@ use tokio_util::sync::CancellationToken;
#[derive(Debug)]
pub(crate) enum AuthDataLocation {
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
Headers,
Body,
}
@@ -15,7 +15,7 @@ pub(crate) enum AuthDataLocation {
#[derive(Debug)]
pub(crate) enum AuthError {
/// Failed to load page due to TLS error
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
TlsError,
/// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc.
@@ -34,7 +34,7 @@ impl AuthError {
}
}
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
impl AuthError {
pub fn not_found_in_headers() -> Self {
Self::NotFound(AuthDataLocation::Headers)
@@ -155,7 +155,7 @@ impl AuthMessenger {
}
}
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
use log::warn;
@@ -5,8 +5,8 @@ use gpapi::utils::redact::redact_uri;
use log::warn;
use tauri::webview::PlatformWebview;
use webkit2gtk::{
LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, WebsiteDataManagerExt,
gio::Cancellable, glib::GString,
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
WebsiteDataManagerExt, gio::Cancellable, glib::GString,
};
use super::{
@@ -33,6 +33,26 @@ impl PlatformWebviewExt for PlatformWebview {
bail!("Failed to get website data manager");
}
fn user_agent(&self) -> anyhow::Result<String> {
let Some(settings) = self.inner().settings() else {
bail!("Failed to get webview settings");
};
settings
.user_agent()
.map(GString::into)
.ok_or_else(|| anyhow::anyhow!("Failed to get webview user agent"))
}
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
let Some(settings) = self.inner().settings() else {
bail!("Failed to get webview settings");
};
settings.set_user_agent(Some(user_agent));
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
self.inner().load_uri(url);
Ok(())
+25 -1
View File
@@ -1,7 +1,8 @@
use anyhow::bail;
use block2::RcBlock;
use log::warn;
use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSString, NSURL, NSURLRequest};
use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest};
use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview;
@@ -13,6 +14,29 @@ impl PlatformWebviewExt for PlatformWebview {
Ok(())
}
fn user_agent(&self) -> anyhow::Result<String> {
unsafe {
let wv: &NSObject = &*self.inner().cast();
let Some(value) = wv.valueForKey(&NSString::from_str("userAgent")) else {
bail!("Failed to get webview user agent");
};
let Some(user_agent) = value.downcast_ref::<NSString>() else {
bail!("Webview user agent is not a string");
};
Ok(user_agent.to_string())
}
}
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
wv.setCustomUserAgent(Some(&NSString::from_str(user_agent)));
}
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
+203 -9
View File
@@ -1,7 +1,12 @@
use std::{sync::Arc, time::Duration};
use anyhow::bail;
use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri};
use gpapi::{
auth::SamlAuthData,
gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::redact::redact_uri,
};
use log::{info, warn};
use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
@@ -16,6 +21,10 @@ use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
pub trait PlatformWebviewExt {
fn ignore_tls_errors(&self) -> anyhow::Result<()>;
fn user_agent(&self) -> anyhow::Result<String>;
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()>;
fn load_url(&self, url: &str) -> anyhow::Result<()>;
fn load_html(&self, html: &str) -> anyhow::Result<()>;
@@ -33,7 +42,7 @@ pub trait PlatformWebviewExt {
}
}
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub trait GetHeader {
fn get_header(&self, key: &str) -> Option<String>;
}
@@ -42,6 +51,7 @@ pub struct WebviewAuthenticator<'a> {
server: &'a str,
gp_params: &'a GpParams,
auth_request: Option<&'a str>,
webview_user_agent: Option<WebviewUserAgent>,
clean: bool,
is_retrying: tokio::sync::RwLock<bool>,
@@ -53,6 +63,7 @@ impl<'a> WebviewAuthenticator<'a> {
server,
gp_params,
auth_request: None,
webview_user_agent: None,
clean: false,
is_retrying: Default::default(),
}
@@ -63,6 +74,11 @@ impl<'a> WebviewAuthenticator<'a> {
self
}
pub fn with_webview_user_agent(mut self, user_agent: WebviewUserAgent) -> Self {
self.webview_user_agent = Some(user_agent);
self
}
pub fn with_clean(mut self, clean: bool) -> Self {
self.clean = clean;
self
@@ -116,7 +132,7 @@ impl<'a> WebviewAuthenticator<'a> {
match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!("Authentication cancelled"),
AuthEvent::RaiseWindow => self.raise_window(&auth_window),
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
AuthEvent::Error(AuthError::NotFound(location)) => {
info!(
@@ -168,15 +184,16 @@ impl<'a> WebviewAuthenticator<'a> {
let auth_request = match self.auth_request {
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&self.server, &self.gp_params).await?,
None => auth_prelogin(&self.server, &self.gp_params, false, false).await?,
};
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
let webview_user_agent = self.webview_user_agent.clone();
// Set up webview
auth_window.with_webview(move |wv| {
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
use super::platform_impl::PlatformWebviewOnResponse;
wv.on_response(Box::new(move |response| match response {
@@ -190,7 +207,7 @@ impl<'a> WebviewAuthenticator<'a> {
wv.ignore_tls_errors()?;
}
wv.load_auth_request(&auth_request)
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
}();
if let Err(result) = tx.send(result) {
@@ -240,10 +257,15 @@ impl<'a> WebviewAuthenticator<'a> {
document.body.appendChild(loading);
"#)?;
let auth_request = auth_prelogin(&self.server, &self.gp_params).await?;
let auth_request = auth_prelogin(&self.server, &self.gp_params, false, false).await?;
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let webview_user_agent = self.webview_user_agent.clone();
auth_window.with_webview(move |wv| {
let result = wv.load_auth_request(&auth_request);
let result = || -> anyhow::Result<()> {
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
}();
if let Err(result) = tx.send(result) {
warn!("Failed to send retry auth result: {:?}", result);
}
@@ -265,7 +287,7 @@ impl<'a> WebviewAuthenticator<'a> {
#[cfg(target_os = "macos")]
let result = auth_window.show();
#[cfg(not(target_os = "macos"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let result = {
use gpapi::utils::window::WindowExt;
auth_window.raise()
@@ -276,3 +298,175 @@ impl<'a> WebviewAuthenticator<'a> {
}
}
}
fn load_auth_request_with_user_agent(
wv: &impl PlatformWebviewExt,
plan: Option<&WebviewUserAgent>,
auth_request: &str,
) -> anyhow::Result<()> {
if let Some(plan) = plan {
let user_agent = compose_webview_user_agent(plan, || wv.user_agent())?;
wv.set_user_agent(&user_agent)?;
}
wv.load_auth_request(auth_request)
}
fn compose_webview_user_agent(
plan: &WebviewUserAgent,
native_user_agent: impl FnOnce() -> anyhow::Result<String>,
) -> anyhow::Result<String> {
let (prefix, default_user_agent, transform) = match plan {
WebviewUserAgent::Native { prefix, transform } => (prefix.as_str(), native_user_agent()?, *transform),
WebviewUserAgent::Projected {
prefix,
default_user_agent,
} => (
prefix.as_str(),
default_user_agent.clone(),
WebviewUserAgentTransform::None,
),
};
let default_user_agent = apply_webview_user_agent_transform(transform, &default_user_agent);
prepend_webview_user_agent_prefix(prefix, &default_user_agent)
}
fn apply_webview_user_agent_transform(transform: WebviewUserAgentTransform, user_agent: &str) -> String {
match transform {
WebviewUserAgentTransform::None => user_agent.to_string(),
WebviewUserAgentTransform::LinuxPanGpuiVersion => linux_pan_gpui_user_agent(user_agent),
}
}
fn linux_pan_gpui_user_agent(user_agent: &str) -> String {
if user_agent.contains("PanGPUI Version/10.0") {
return user_agent.to_string();
}
let Some(start) = user_agent.find("Version/") else {
return user_agent.to_string();
};
let end = user_agent[start..]
.find(char::is_whitespace)
.map(|offset| start + offset)
.unwrap_or(user_agent.len());
format!("{}PanGPUI Version/10.0{}", &user_agent[..start], &user_agent[end..])
}
fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) -> anyhow::Result<String> {
let prefix = prefix.trim();
if prefix.is_empty() {
return Ok(default_user_agent.to_string());
}
let default_user_agent = default_user_agent.trim();
if default_user_agent.is_empty() {
bail!("Failed to read default webview user agent");
}
if default_user_agent.starts_with(prefix) {
return Ok(default_user_agent.to_string());
}
Ok(format!("{} {}", prefix, default_user_agent))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prepends_prefix_to_default_user_agent() {
let user_agent = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "Mozilla/5.0").unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0");
}
#[test]
fn leaves_already_prefixed_user_agent_unchanged() {
let user_agent =
prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "PAN GlobalProtect/6.3.3 Mozilla/5.0").unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0");
}
#[test]
fn blank_prefix_leaves_default_user_agent_unchanged() {
let user_agent = prepend_webview_user_agent_prefix(" ", "Mozilla/5.0").unwrap();
assert_eq!(user_agent, "Mozilla/5.0");
}
#[test]
fn non_blank_prefix_requires_default_user_agent() {
let err = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", " ").unwrap_err();
assert!(err.to_string().contains("default webview user agent"));
}
#[test]
fn native_plan_reads_native_default_user_agent() {
let plan = WebviewUserAgent::Native {
prefix: "PAN GlobalProtect/6.3.3".to_string(),
transform: WebviewUserAgentTransform::None,
};
let user_agent = compose_webview_user_agent(&plan, || Ok("Mozilla/5.0".to_string())).unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0");
}
#[test]
fn linux_transform_replaces_version_token_with_pan_gpui_version() {
let user_agent = linux_pan_gpui_user_agent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/60.5 Safari/605.1.15",
);
assert_eq!(
user_agent,
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/605.1.15"
);
}
#[test]
fn linux_transform_does_not_duplicate_pan_gpui_version() {
let user_agent = linux_pan_gpui_user_agent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1",
);
assert_eq!(
user_agent,
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1"
);
}
#[test]
fn native_linux_plan_applies_pan_gpui_transform_before_prefix() {
let plan = WebviewUserAgent::Native {
prefix: "PAN GlobalProtect/6.3.3".to_string(),
transform: WebviewUserAgentTransform::LinuxPanGpuiVersion,
};
let user_agent =
compose_webview_user_agent(&plan, || Ok("Mozilla/5.0 Version/60.5 Safari/605.1.15".to_string())).unwrap();
assert_eq!(
user_agent,
"PAN GlobalProtect/6.3.3 Mozilla/5.0 PanGPUI Version/10.0 Safari/605.1.15"
);
}
#[test]
fn projected_plan_uses_profile_default_user_agent() {
let plan = WebviewUserAgent::Projected {
prefix: "PAN GlobalProtect/6.3.3".to_string(),
default_user_agent: "Mozilla/5.0 projected".to_string(),
};
let user_agent = compose_webview_user_agent(&plan, || {
panic!("projected webview user agent should not read the native default")
})
.unwrap();
assert_eq!(user_agent, "PAN GlobalProtect/6.3.3 Mozilla/5.0 projected");
}
}
+58
View File
@@ -0,0 +1,58 @@
use std::{
env,
path::{Path, PathBuf},
};
use crate::constants::{GP_AUTH_BINARY, GP_CLIENT_BINARY, GP_GUI_BINARY, GP_GUI_HELPER_BINARY, GP_SERVICE_BINARY};
pub fn gpclient() -> PathBuf {
resolve("GP_CLIENT_BINARY", "gpclient", GP_CLIENT_BINARY)
}
pub fn gpservice() -> PathBuf {
resolve("GP_SERVICE_BINARY", "gpservice", GP_SERVICE_BINARY)
}
pub fn gpauth() -> PathBuf {
resolve("GP_AUTH_BINARY", "gpauth", GP_AUTH_BINARY)
}
pub fn gpgui() -> PathBuf {
resolve("GP_GUI_BINARY", "gpgui", GP_GUI_BINARY)
}
pub fn gpgui_helper() -> PathBuf {
resolve("GP_GUI_HELPER_BINARY", "gpgui-helper", GP_GUI_HELPER_BINARY)
}
fn resolve(env_key: &str, binary_name: &str, default_path: &str) -> PathBuf {
env::var_os(env_key)
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.or_else(|| sibling_binary(binary_name))
.unwrap_or_else(|| PathBuf::from(default_path))
}
fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
let current_exe = env::current_exe().ok()?;
let bin_dir = current_exe.parent()?;
let binary = bin_dir.join(binary_name);
is_file(&binary).then_some(binary)
}
fn is_file(path: &Path) -> bool {
path.is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_path_is_used_when_no_sibling_exists() {
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
assert_eq!(path, PathBuf::from("/usr/bin/gp-test"));
}
}
+35 -6
View File
@@ -1,5 +1,7 @@
pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION: &str = "6.3.0-33";
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
@@ -27,16 +29,43 @@ 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 - BSD package layout
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth";
// Release binaries - Linux
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_AUTH_BINARY: &str = "/usr/bin/gpauth";
// Debug binaries are set in build.rs via environment variables
+1
View File
@@ -1 +1,2 @@
pub mod binary_paths;
pub mod constants;
+7 -7
View File
@@ -32,10 +32,11 @@ uzers.workspace = true
serde_urlencoded.workspace = true
md5.workspace = true
sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
netdev.workspace = true
os_info = { version = "3", default-features = false }
# Optional dependencies for features
tauri = { workspace = true, optional = true }
@@ -45,16 +46,15 @@ clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true }
# Dependencies for macOS and Windows only
[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies]
os_info = { version = "3", default-features = false }
# Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = "0.18"
gtk = { version = "0.18", optional = true }
[dev-dependencies]
proptest.workspace = true
[features]
tauri = ["dep:tauri"]
tauri = ["dep:tauri", "dep:gtk"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
logger = ["dep:env_logger", "dep:log-reload"]
+83 -4
View File
@@ -9,7 +9,7 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SamlAuthData {
#[serde(alias = "un")]
@@ -17,9 +17,11 @@ pub struct SamlAuthData {
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
host_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum SamlAuthResult {
Success(SamlAuthData),
@@ -33,6 +35,13 @@ impl SamlAuthResult {
SamlAuthResult::Failure(_) => false,
}
}
pub fn host_id(&self) -> Option<&str> {
match self {
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
SamlAuthResult::Failure(_) => None,
}
}
}
impl SamlAuthData {
@@ -62,9 +71,16 @@ impl SamlAuthData {
prelogin_cookie: Some(prelogin_cookie),
portal_userauthcookie: Some(portal_userauthcookie),
token: None,
host_id: None,
})
}
pub fn with_host_id(mut self, host_id: impl Into<String>) -> Self {
let host_id = host_id.into();
self.host_id = (!host_id.trim().is_empty()).then_some(host_id);
self
}
pub fn from_html(html: &str) -> AuthDataParseResult {
match parse_xml_tag(html, "saml-auth-status") {
Some(status) if status == "1" => {
@@ -72,7 +88,11 @@ impl SamlAuthData {
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)
let auth_data =
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!(
"SAML auth status: {}",
@@ -102,6 +122,7 @@ impl SamlAuthData {
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
auth_data.log_summary("gpcallback-cas");
return Ok(auth_data);
}
@@ -122,9 +143,32 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
pub fn host_id(&self) -> Option<&str> {
self.host_id.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> {
@@ -160,11 +204,46 @@ mod tests {
#[test]
fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHBvcnRhbC11c2VyYXV0aGNvb2tpZT5wb3J0YWwtdXNlcmF1dGhjb29raWU8L3BvcnRhbC11c2VyYXV0aGNvb2tpZT48c2FtbC11c2VybmFtZT54eXpAZW1haWwuY29tPC9zYW1sLXVzZXJuYW1lPjxzYW1sLXNsbz5ubzwvc2FtbC1zbG8+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie"));
}
#[test]
fn auth_result_success_can_carry_host_id() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
None,
)
.unwrap()
.with_host_id("host-seed");
let result = SamlAuthResult::Success(auth_data);
assert_eq!(result.host_id(), Some("host-seed"));
let value = serde_json::to_value(result).unwrap();
assert_eq!(value["success"]["hostId"], "host-seed");
}
#[test]
fn auth_result_success_omits_empty_host_id() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
None,
)
.unwrap()
.with_host_id(" ");
let result = SamlAuthResult::Success(auth_data);
assert_eq!(result.host_id(), None);
let value = serde_json::to_value(result).unwrap();
assert!(value["success"].get("hostId").is_none());
}
}
+38 -37
View File
@@ -1,37 +1,22 @@
use clap::{ValueEnum, builder::PossibleValue};
use crate::gp_params::ClientOs;
use crate::{
gp_params::CscMode,
os_profile::{ClientOs, runtime_client_os},
};
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Os {
#[value(name = "Linux")]
Linux,
#[value(name = "Windows")]
Windows,
#[value(name = "Mac")]
Mac,
}
impl Os {
pub fn as_str(&self) -> &'static str {
match self {
Os::Linux => "Linux",
Os::Windows => "Windows",
Os::Mac => "Mac",
}
}
}
impl From<&str> for Os {
fn from(os: &str) -> Self {
match os.to_lowercase().as_str() {
"linux" => Os::Linux,
"windows" => Os::Windows,
"mac" => Os::Mac,
_ => Os::Linux,
}
}
}
impl From<&Os> for ClientOs {
fn from(value: &Os) -> Self {
impl From<Os> for ClientOs {
fn from(value: Os) -> Self {
match value {
Os::Linux => ClientOs::Linux,
Os::Windows => ClientOs::Windows,
@@ -40,25 +25,41 @@ impl From<&Os> for ClientOs {
}
}
impl ValueEnum for Os {
impl Default for Os {
fn default() -> Self {
match runtime_client_os() {
ClientOs::Linux => Os::Linux,
ClientOs::Windows => Os::Windows,
ClientOs::Mac => Os::Mac,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_os_uses_runtime_client_os() {
assert_eq!(ClientOs::from(Os::default()), runtime_client_os());
}
}
impl ValueEnum for CscMode {
fn value_variants<'a>() -> &'a [Self] {
&[Os::Linux, Os::Windows, Os::Mac]
&[CscMode::Auto, CscMode::Yes, CscMode::No]
}
fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
match self {
Os::Linux => Some(PossibleValue::new("Linux")),
Os::Windows => Some(PossibleValue::new("Windows")),
Os::Mac => Some(PossibleValue::new("Mac")),
}
fn to_possible_value(&self) -> Option<PossibleValue> {
Some(PossibleValue::new(self.as_str()))
}
fn from_str(input: &str, _: bool) -> Result<Self, String> {
match input.to_lowercase().as_str() {
"linux" => Ok(Os::Linux),
"windows" => Ok(Os::Windows),
"mac" => Ok(Os::Mac),
_ => Err(format!("Invalid OS: {}", input)),
"auto" => Ok(CscMode::Auto),
"yes" => Ok(CscMode::Yes),
"no" => Ok(CscMode::No),
_ => Err(format!("Invalid CSC mode: {}", input)),
}
}
}
+190
View File
@@ -0,0 +1,190 @@
use std::{
fs,
io::Write,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use crate::credential::AuthCookieCredential;
const STORE_VERSION: u32 = 1;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StoredCookie {
pub version: u32,
pub server: String,
pub username: String,
pub host_id: String,
pub last_gateway: String,
pub auth_cookie: AuthCookieCredential,
pub saved_at: u64,
}
impl StoredCookie {
pub fn new(
server: String,
username: String,
host_id: String,
last_gateway: String,
auth_cookie: AuthCookieCredential,
) -> Self {
let saved_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
Self {
version: STORE_VERSION,
server,
username,
host_id,
last_gateway,
auth_cookie,
saved_at,
}
}
}
pub fn cookie_path(custom: Option<&str>) -> PathBuf {
if let Some(p) = custom {
return PathBuf::from(p);
}
let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
PathBuf::from(home).join(".config/gpclient/cookie.json")
}
pub fn load(path: &Path, server: &str, host_id: &str) -> Option<StoredCookie> {
let bytes = fs::read(path).ok()?;
let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?;
if stored.version != STORE_VERSION || stored.server != server || stored.host_id != host_id {
return None;
}
Some(stored)
}
pub fn save(path: &Path, stored: &StoredCookie) -> anyhow::Result<()> {
let parent = path
.parent()
.ok_or_else(|| anyhow::anyhow!("cookie path has no parent directory"))?;
fs::create_dir_all(parent)?;
set_private_dir_permissions(parent)?;
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(&serde_json::to_vec(stored)?)?;
tmp.flush()?;
set_private_file_permissions(tmp.path())?;
tmp.persist(path)?;
Ok(())
}
pub fn clear(path: &Path) {
let _ = fs::remove_file(path);
}
use permissions::{set_private_dir_permissions, set_private_file_permissions};
mod permissions {
use std::path::Path;
#[cfg(unix)]
mod unix {
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
pub(super) fn set_private_dir(path: &Path) -> anyhow::Result<()> {
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
Ok(())
}
pub(super) fn set_private_file(path: &Path) -> anyhow::Result<()> {
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
Ok(())
}
#[cfg(test)]
pub(super) fn file_mode(path: &Path) -> Option<u32> {
Some(fs::metadata(path).ok()?.permissions().mode() & 0o777)
}
}
pub(super) fn set_private_dir_permissions(path: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
unix::set_private_dir(path)?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
pub(super) fn set_private_file_permissions(path: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
unix::set_private_file(path)?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)]
pub(super) fn file_mode(path: &Path) -> Option<u32> {
#[cfg(unix)]
return unix::file_mode(path);
#[cfg(not(unix))]
{
let _ = path;
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> StoredCookie {
StoredCookie::new(
"vpn.example.com".to_string(),
"alice".to_string(),
"host-1".to_string(),
"gw1.example.com".to_string(),
AuthCookieCredential::new("alice", "user-auth", "prelogon-auth"),
)
}
#[test]
fn roundtrip_and_mode_0600() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("cookie.json");
let s = sample();
save(&path, &s).unwrap();
if let Some(mode) = permissions::file_mode(&path) {
assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode);
}
let loaded = load(&path, "vpn.example.com", "host-1").unwrap();
assert_eq!(loaded.username, "alice");
assert_eq!(loaded.host_id, "host-1");
assert_eq!(loaded.last_gateway, "gw1.example.com");
assert_eq!(loaded.auth_cookie.user_auth_cookie(), "user-auth");
assert!(
load(&path, "other.example.com", "host-1").is_none(),
"must reject mismatched server"
);
assert!(
load(&path, "vpn.example.com", "host-2").is_none(),
"must reject mismatched host id"
);
clear(&path);
assert!(!path.exists());
}
#[test]
fn rejects_version_mismatch() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("cookie.json");
let mut s = sample();
s.version = STORE_VERSION + 1;
save(&path, &s).unwrap();
assert!(load(&path, "vpn.example.com", "host-1").is_none());
}
}
+139 -38
View File
@@ -1,5 +1,3 @@
use std::collections::HashMap;
use anyhow::bail;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -41,14 +39,21 @@ impl From<&CachedCredential> for PasswordCredential {
pub struct PreloginCredential {
username: String,
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
}
impl PreloginCredential {
pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self {
pub fn new(
username: &str,
prelogin_cookie: Option<&str>,
portal_userauthcookie: Option<&str>,
token: Option<&str>,
) -> Self {
Self {
username: username.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()),
}
}
@@ -61,6 +66,10 @@ impl PreloginCredential {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
@@ -70,9 +79,10 @@ impl From<SamlAuthData> for PreloginCredential {
fn from(value: SamlAuthData) -> Self {
let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie();
let portal_userauthcookie = value.portal_userauthcookie();
let token = value.token();
Self::new(&username, prelogin_cookie, token)
Self::new(&username, prelogin_cookie, portal_userauthcookie, token)
}
}
@@ -82,6 +92,8 @@ pub struct AuthCookieCredential {
username: String,
user_auth_cookie: String,
prelogon_user_auth_cookie: String,
#[serde(skip)]
password: Option<String>,
}
impl AuthCookieCredential {
@@ -90,9 +102,16 @@ impl AuthCookieCredential {
username: username.to_string(),
user_auth_cookie: user_auth_cookie.to_string(),
prelogon_user_auth_cookie: prelogon_user_auth_cookie.to_string(),
password: None,
}
}
pub fn with_password(mut self, password: impl Into<String>) -> Self {
let password = password.into();
self.password = (!password.trim().is_empty()).then_some(password);
self
}
pub fn username(&self) -> &str {
&self.username
}
@@ -104,6 +123,19 @@ impl AuthCookieCredential {
pub fn prelogon_user_auth_cookie(&self) -> &str {
&self.prelogon_user_auth_cookie
}
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
pub fn can_authenticate_gateway(&self) -> bool {
is_gateway_auth_cookie(&self.user_auth_cookie) || is_gateway_auth_cookie(&self.prelogon_user_auth_cookie)
}
}
fn is_gateway_auth_cookie(value: &str) -> bool {
let value = value.trim();
!value.is_empty() && value != "empty"
}
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
@@ -135,6 +167,13 @@ impl CachedCredential {
self.auth_cookie.as_ref()
}
pub fn can_authenticate_gateway(&self) -> bool {
self
.auth_cookie
.as_ref()
.is_some_and(AuthCookieCredential::can_authenticate_gateway)
}
pub fn set_auth_cookie(&mut self, auth_cookie: AuthCookieCredential) {
self.auth_cookie = Some(auth_cookie);
}
@@ -180,42 +219,20 @@ impl Credential {
}
}
pub fn to_params(&self) -> HashMap<&str, &str> {
let mut params = HashMap::new();
params.insert("user", self.username());
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()),
Credential::AuthCookie(cred) => (
None,
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::Cached(cred) => (
cred.password(),
None,
cred.auth_cookie.as_ref().map(|c| c.user_auth_cookie()),
cred.auth_cookie.as_ref().map(|c| c.prelogon_user_auth_cookie()),
None,
),
};
params.insert("passwd", passwd.unwrap_or_default());
params.insert("prelogin-cookie", prelogin_cookie.unwrap_or_default());
params.insert("portal-userauthcookie", portal_userauthcookie.unwrap_or_default());
params.insert(
"portal-prelogonuserauthcookie",
portal_prelogonuserauthcookie.unwrap_or_default(),
);
if let Some(token) = token {
params.insert("token", token);
pub fn password(&self) -> Option<&str> {
match self {
Credential::Password(cred) => Some(cred.password()),
Credential::Cached(cred) => cred.password(),
Credential::Prelogin(_) | Credential::AuthCookie(_) => None,
}
}
params
pub fn can_authenticate_gateway(&self) -> bool {
match self {
Credential::AuthCookie(cred) => cred.can_authenticate_gateway(),
Credential::Cached(cred) => cred.can_authenticate_gateway(),
Credential::Password(_) | Credential::Prelogin(_) => true,
}
}
}
@@ -255,3 +272,87 @@ impl From<&CachedCredential> for Credential {
Self::Cached(value.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prelogin_credential_keeps_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 Credential::Prelogin(prelogin) = cred else {
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]");
assert_eq!(prelogin.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(prelogin.portal_userauthcookie(), Some("portal-userauthcookie"));
assert_eq!(prelogin.token(), None);
}
#[test]
fn prelogin_credential_keeps_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 Credential::Prelogin(prelogin) = cred else {
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]");
assert_eq!(prelogin.prelogin_cookie(), None);
assert_eq!(prelogin.portal_userauthcookie(), None);
assert_eq!(prelogin.token(), Some("cas-token"));
}
#[test]
fn auth_cookie_runtime_password_is_not_serialized() {
let value = serde_json::to_value(
AuthCookieCredential::new("alice", "user-cookie", "prelogon-cookie").with_password("secret"),
)
.unwrap();
assert_eq!(value.get("password"), None);
}
#[test]
fn auth_cookie_with_empty_sentinels_cannot_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "empty", "empty");
assert!(!cred.can_authenticate_gateway());
}
#[test]
fn auth_cookie_with_blank_values_cannot_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "", " ");
assert!(!cred.can_authenticate_gateway());
}
#[test]
fn auth_cookie_with_real_cookie_can_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "empty", "portal-prelogon-cookie");
assert!(cred.can_authenticate_gateway());
}
#[test]
fn cached_credential_without_real_auth_cookie_cannot_authenticate_gateway() {
let cred = CachedCredential::new(
"alice".to_string(),
None,
Some(AuthCookieCredential::new("alice", "empty", "empty")),
);
assert!(!cred.can_authenticate_gateway());
assert!(!Credential::from(&cred).can_authenticate_gateway());
}
}
-173
View File
@@ -1,173 +0,0 @@
use std::collections::HashMap;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
gp_params::GpParams,
process::hip_launcher::HipLauncher,
utils::{normalize_server, xml::ElementExt},
};
struct HipReporter<'a> {
server: String,
cookie: &'a str,
md5: &'a str,
csd_wrapper: &'a str,
gp_params: &'a GpParams,
client: Client,
}
impl HipReporter<'_> {
async fn report(&self) -> anyhow::Result<()> {
let client_ip = self.retrieve_client_ip().await?;
let hip_needed = match self.check_hip(&client_ip).await {
Ok(hip_needed) => hip_needed,
Err(err) => {
warn!("Failed to check HIP: {}", err);
return Ok(());
}
};
if !hip_needed {
info!("HIP report not needed");
return Ok(());
}
info!("HIP report needed, generating report...");
let report = self.generate_report(&client_ip).await?;
if let Err(err) = self.submit_hip(&client_ip, &report).await {
warn!("Failed to submit HIP report: {}", err);
}
Ok(())
}
async fn retrieve_client_ip(&self) -> anyhow::Result<String> {
let config_url = format!("{}/ssl-vpn/getconfig.esp", self.server);
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("client-type", "1");
params.insert("protocol-version", "p1");
params.insert("internal", "no");
params.insert("ipv6-support", "yes");
params.insert("clientos", self.gp_params.client_os());
params.insert("hmac-algo", "sha1,md5,sha256");
params.insert("enc-algo", "aes-128-cbc,aes-256-cbc");
if let Some(os_version) = self.gp_params.os_version() {
params.insert("os-version", os_version);
}
if let Some(client_version) = self.gp_params.client_version() {
params.insert("app-version", client_version);
}
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&config_url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
let root = Element::parse(res_xml.as_bytes())?;
// Get <ip-address>
let ip = root
.descendant_text("ip-address")
.ok_or_else(|| anyhow::anyhow!("ip-address not found"))?;
Ok(ip.to_string())
}
async fn check_hip(&self, client_ip: &str) -> anyhow::Result<bool> {
let url = format!("{}/ssl-vpn/hipreportcheck.esp", self.server);
let mut params = HashMap::new();
params.insert("client-role", "global-protect-full");
params.insert("client-ip", client_ip);
params.insert("md5", self.md5);
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
is_hip_needed(&res_xml)
}
async fn generate_report(&self, client_ip: &str) -> anyhow::Result<String> {
let launcher = HipLauncher::new(self.csd_wrapper)
.cookie(self.cookie)
.md5(self.md5)
.client_ip(client_ip)
.client_os(self.gp_params.client_os())
.client_version(self.gp_params.client_version());
launcher.launch().await
}
async fn submit_hip(&self, client_ip: &str, report: &str) -> anyhow::Result<()> {
let url = format!("{}/ssl-vpn/hipreport.esp", self.server);
let mut params = HashMap::new();
params.insert("client-role", "global-protect-full");
params.insert("client-ip", client_ip);
params.insert("report", report);
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
info!("HIP check response: {}", res_xml);
Ok(())
}
}
fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> {
let root = Element::parse(res_xml.as_bytes())?;
let hip_needed = root
.descendant_text("hip-report-needed")
.ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?;
Ok(hip_needed == "yes")
}
fn merge_cookie_params(cookie: &str, params: &HashMap<&str, &str>) -> anyhow::Result<HashMap<String, String>> {
let cookie_params = serde_urlencoded::from_str::<HashMap<String, String>>(cookie)?;
let params = params
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.chain(cookie_params)
.collect::<HashMap<String, String>>();
Ok(params)
}
// Compute md5 for fields except authcookie,preferred-ip,preferred-ipv6
fn build_csd_token(cookie: &str) -> anyhow::Result<String> {
let mut cookie_params = serde_urlencoded::from_str::<Vec<(String, String)>>(cookie)?;
cookie_params.retain(|(k, _)| k != "authcookie" && k != "preferred-ip" && k != "preferred-ipv6");
let token = serde_urlencoded::to_string(cookie_params)?;
let md5 = format!("{:x}", md5::compute(token));
Ok(md5)
}
pub async fn hip_report(gateway: &str, cookie: &str, csd_wrapper: &str, gp_params: &GpParams) -> anyhow::Result<()> {
let client = Client::try_from(gp_params)?;
let md5 = build_csd_token(cookie)?;
info!("Submit HIP report md5: {}", md5);
let reporter = HipReporter {
server: normalize_server(gateway)?,
cookie,
md5: &md5,
csd_wrapper,
gp_params,
client,
};
reporter.report().await
}
+60 -51
View File
@@ -1,4 +1,4 @@
use std::{borrow::Cow, collections::HashMap};
use std::{borrow::Cow, net::UdpSocket};
use anyhow::bail;
use log::{debug, info, warn};
@@ -9,7 +9,9 @@ use xmltree::Element;
use crate::{
credential::Credential,
error::PortalError,
gateway::GatewayLoginContext,
gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
@@ -19,7 +21,16 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
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(
@@ -27,13 +38,14 @@ pub async fn gateway_login_with_extend_lifetime(
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
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)?;
@@ -42,14 +54,33 @@ async fn gateway_login_with_options(
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime);
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host()))
});
let request_params = gateway_login::build(&GatewayLoginInput {
gp_params,
cred,
gateway_host: &gateway,
context,
client_ip: client_ip.as_deref(),
extend_lifetime,
});
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res = client
.post(&login_url)
.form(&request_params.body)
.send()
.await
.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}");
@@ -80,31 +111,29 @@ async fn gateway_login_with_options(
Ok(GatewayLogin::Cookie(cookie))
}
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
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();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
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(),
gp_params.client_version().is_some(),
client_ip.is_some()
);
params.insert("server".to_string(), gateway.to_string());
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
@@ -205,26 +234,6 @@ thisForm.inputStr.value = "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, false);
assert!(!params.contains_key("extend-lifetime"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
+134 -1
View File
@@ -1,4 +1,3 @@
pub mod hip;
mod login;
mod parse_gateways;
pub mod session;
@@ -23,10 +22,119 @@ pub(crate) struct PriorityRule {
pub struct Gateway {
pub(crate) name: String,
pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
pub(crate) priority: u32,
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_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_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_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_ip(&self) -> Option<&str> {
self.client_ip.as_deref()
}
}
impl Display for Gateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.name, self.address)
@@ -38,6 +146,7 @@ impl Gateway {
Self {
name,
address,
kind: GatewayKind::External,
priority: 0,
priority_rules: vec![],
}
@@ -50,4 +159,28 @@ impl Gateway {
pub fn server(&self) -> &str {
&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);
}
}
+63 -4
View File
@@ -3,21 +3,28 @@ use xmltree::Element;
use crate::utils::xml::ElementExt;
use super::{Gateway, PriorityRule};
use super::{Gateway, GatewayKind, PriorityRule};
pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?;
let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways...");
node_gateways.descendant("internal").and_then(|n| n.child("list"))
node_gateways
.descendant("internal")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::Internal))
} else {
None
};
let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways...");
node_gateways.descendant("external").and_then(|n| n.child("list"))
node_gateways
.descendant("external")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::External))
})?;
let (gateway_list, kind) = gateway_list;
let gateways = gateway_list
.children("entry")
@@ -28,12 +35,13 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option
let priority = parse_priority(gateway_item);
let priority_rules = gateway_item
.child("priority-rule")
.map(|n| parse_priority_rules(n))
.map(parse_priority_rules)
.unwrap_or_default();
Gateway {
name,
address,
kind,
priority,
priority_rules,
}
@@ -62,3 +70,54 @@ fn parse_priority(element: &Element) -> u32 {
.and_then(|s| s.parse().ok())
.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);
}
}
+27 -14
View File
@@ -13,7 +13,7 @@ use crate::{
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, xml::ElementExt},
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
@@ -120,16 +120,19 @@ fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
}
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());
let mut builder = Client::builder();
Client::try_from(&builder.build())
if let Some(user_agent) = args.user_agent() {
builder = builder.user_agent(user_agent);
}
if let Some(cert) = args.certificate() {
info!("Using client certificate authentication...");
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
builder = builder.identity(identity);
}
Ok(builder.build()?)
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
@@ -165,15 +168,25 @@ fn unix_timestamp() -> u64 {
#[cfg(test)]
mod tests {
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
session::SessionRequestArgs,
};
use super::*;
fn build_session_args() -> SessionRequestArgs {
let profile = OsProfile::builder(ClientOs::Mac)
.host_identity(HostIdentity::new(
"test-mac".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.client_version("6.3.1-12".to_string())
.build();
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_user_agent(profile.user_agent().to_string())
.with_disable_ipv6(true)
}
+410 -127
View File
@@ -1,71 +1,59 @@
use std::collections::HashMap;
use common::constants::GP_USER_AGENT;
use log::info;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::utils::request::create_identity;
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::create_identity,
};
#[derive(Debug, Serialize, Deserialize, Clone, Type, Default)]
pub enum ClientOs {
#[cfg_attr(not(target_os = "macos"), default)]
Linux,
Windows,
#[cfg_attr(target_os = "macos", default)]
Mac,
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
#[serde(rename_all = "lowercase")]
pub enum CscMode {
#[default]
Auto,
Yes,
No,
}
impl From<&str> for ClientOs {
fn from(os: &str) -> Self {
match os {
"Linux" => ClientOs::Linux,
"Windows" => ClientOs::Windows,
"Mac" => ClientOs::Mac,
_ => ClientOs::Linux,
}
}
}
impl ClientOs {
pub fn as_str(&self) -> &str {
impl CscMode {
pub fn effective(self, client_os: ClientOs) -> bool {
match self {
ClientOs::Linux => "Linux",
ClientOs::Windows => "Windows",
ClientOs::Mac => "Mac",
CscMode::Auto => client_os.default_csc_support(),
CscMode::Yes => true,
CscMode::No => false,
}
}
pub fn to_openconnect_os(&self) -> &str {
pub fn as_str(self) -> &'static str {
match self {
ClientOs::Linux => "linux",
ClientOs::Windows => "win",
ClientOs::Mac => "mac-intel",
CscMode::Auto => "auto",
CscMode::Yes => "yes",
CscMode::No => "no",
}
}
}
#[derive(Debug, Serialize, Deserialize, Type, Default, Clone)]
#[derive(Debug, Clone)]
pub struct GpParams {
is_gateway: bool,
user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
os_profile: OsProfile,
// Transport
ignore_tls_errors: bool,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
// Used for MFA
// Feature
csc_mode: CscMode,
// Per-request state
is_gateway: bool,
input_str: Option<String>,
otp: Option<String>,
}
impl GpParams {
pub fn builder() -> GpParamsBuilder {
GpParamsBuilder::new()
pub fn builder(os_profile: OsProfile) -> GpParamsBuilder {
GpParamsBuilder::new(os_profile)
}
pub(crate) fn is_gateway(&self) -> bool {
@@ -77,27 +65,63 @@ impl GpParams {
}
pub(crate) fn user_agent(&self) -> &str {
&self.user_agent
}
pub(crate) fn computer(&self) -> &str {
&self.computer
self.os_profile.user_agent()
}
pub fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
// ─── OsProfile accessor ─────────────────────────────────────────────────
pub fn os_profile(&self) -> &OsProfile {
&self.os_profile
}
// ─── Delegated identity accessors ────────────────────────────────────────
pub fn client_os(&self) -> &str {
self.client_os.as_str()
self.os_profile.client_os().as_str()
}
pub(crate) fn computer(&self) -> &str {
self.os_profile.computer()
}
pub fn os_version(&self) -> Option<&str> {
self.os_version.as_deref()
Some(self.os_profile.os_version())
}
pub fn client_version(&self) -> Option<&str> {
self.client_version.as_deref()
Some(self.os_profile.client_version())
}
pub(crate) fn host_id(&self) -> &str {
self.os_profile.host_id()
}
pub(crate) fn serialno(&self) -> &str {
self.os_profile.serialno()
}
pub fn host_identity(&self) -> &HostIdentity {
self.os_profile.host_identity()
}
// ─── Feature accessors ──────────────────────────────────────────────────
pub(crate) fn effective_csc_support(&self) -> bool {
self.csc_mode.effective(self.os_profile.client_os())
}
pub fn csc_mode(&self) -> CscMode {
self.csc_mode
}
// ─── Per-request state ──────────────────────────────────────────────────
pub(crate) fn input_str(&self) -> Option<&str> {
self.input_str.as_deref()
}
pub fn set_input_str(&mut self, input_str: &str) {
@@ -108,46 +132,15 @@ impl GpParams {
self.otp = Some(otp.to_string());
}
pub(crate) fn to_params(&self) -> HashMap<&str, &str> {
let mut params: HashMap<&str, &str> = HashMap::new();
let client_os = self.client_os.as_str();
// Common params
params.insert("prot", "https:");
params.insert("jnlpReady", "jnlpReady");
params.insert("ok", "Login");
params.insert("direct", "yes");
params.insert("ipv6-support", "yes");
params.insert("clientVer", "4100");
params.insert("clientos", client_os);
params.insert("computer", &self.computer);
// MFA
params.insert("inputStr", self.input_str.as_deref().unwrap_or_default());
if let Some(otp) = &self.otp {
params.insert("passwd", otp);
}
if let Some(os_version) = &self.os_version {
params.insert("os-version", os_version);
}
// NOTE: Do not include clientgpversion for now
// if let Some(client_version) = &self.client_version {
// params.insert("clientgpversion", client_version);
// }
params
pub(crate) fn otp(&self) -> Option<&str> {
self.otp.as_deref()
}
}
pub struct GpParamsBuilder {
is_gateway: bool,
user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
os_profile: OsProfile,
csc_mode: CscMode,
ignore_tls_errors: bool,
certificate: Option<String>,
sslkey: Option<String>,
@@ -155,16 +148,11 @@ pub struct GpParamsBuilder {
}
impl GpParamsBuilder {
pub fn new() -> Self {
let computer = whoami::fallible::hostname().unwrap_or_else(|_| String::from("localhost"));
pub fn new(os_profile: OsProfile) -> Self {
Self {
is_gateway: false,
user_agent: GP_USER_AGENT.to_string(),
client_os: ClientOs::Linux,
os_version: Default::default(),
client_version: Default::default(),
computer,
os_profile,
csc_mode: Default::default(),
ignore_tls_errors: false,
certificate: Default::default(),
sslkey: Default::default(),
@@ -177,28 +165,8 @@ impl GpParamsBuilder {
self
}
pub fn user_agent(&mut self, user_agent: &str) -> &mut Self {
self.user_agent = user_agent.to_string();
self
}
pub fn client_os(&mut self, client_os: ClientOs) -> &mut Self {
self.client_os = client_os;
self
}
pub fn os_version<T: Into<Option<String>>>(&mut self, os_version: T) -> &mut Self {
self.os_version = os_version.into();
self
}
pub fn client_version<T: Into<Option<String>>>(&mut self, client_version: T) -> &mut Self {
self.client_version = client_version.into();
self
}
pub fn computer(&mut self, computer: &str) -> &mut Self {
self.computer = computer.to_string();
pub fn csc_mode(&mut self, csc_mode: CscMode) -> &mut Self {
self.csc_mode = csc_mode;
self
}
@@ -224,35 +192,26 @@ impl GpParamsBuilder {
pub fn build(&self) -> GpParams {
GpParams {
is_gateway: self.is_gateway,
user_agent: self.user_agent.clone(),
client_os: self.client_os.clone(),
os_version: self.os_version.clone(),
client_version: self.client_version.clone(),
computer: self.computer.clone(),
os_profile: self.os_profile.clone(),
ignore_tls_errors: self.ignore_tls_errors,
certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(),
csc_mode: self.csc_mode,
is_gateway: self.is_gateway,
input_str: Default::default(),
otp: Default::default(),
}
}
}
impl Default for GpParamsBuilder {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<&GpParams> for Client {
type Error = anyhow::Error;
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(value.ignore_tls_errors)
.user_agent(&value.user_agent);
.user_agent(value.user_agent());
if let Some(cert) = value.certificate.as_deref() {
info!("Using client certificate authentication...");
@@ -264,3 +223,327 @@ impl TryFrom<&GpParams> for Client {
Ok(client)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::runtime_client_os;
fn profile(client_os: ClientOs) -> OsProfile {
OsProfile::builder(client_os).build()
}
#[test]
fn default_client_versions_match_observed_official_clients() {
assert_eq!(ClientOs::Linux.default_client_version(), "6.3.3-619");
assert_eq!(ClientOs::Windows.default_client_version(), "6.3.3-650");
assert_eq!(ClientOs::Mac.default_client_version(), "6.3.3-915");
}
#[test]
fn builder_uses_os_profile_client_version_when_unspecified() {
let params = GpParams::builder(profile(ClientOs::Mac)).build();
assert_eq!(params.client_version(), Some("6.3.3-915"));
}
#[test]
fn builder_keeps_explicit_client_version() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.2.9-1".to_string())
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.client_version(), Some("6.2.9-1"));
}
#[test]
fn builder_uses_os_profile_version_when_unspecified() {
let params = GpParams::builder(profile(ClientOs::Mac)).build();
let default_os_version = ClientOs::Mac.default_os_version();
assert_eq!(params.os_version(), Some(default_os_version.as_str()));
}
#[test]
fn os_profile_accessor_returns_profile() {
let params = GpParams::builder(profile(ClientOs::Linux)).build();
let profile = params.os_profile();
assert_eq!(profile.client_os(), ClientOs::Linux);
}
#[test]
fn delegates_identity_to_os_profile() {
let identity = HostIdentity::new(
"test-computer".to_string(),
"test-host-id".to_string(),
"test-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).host_identity(identity).build()).build();
assert!(!params.host_id().is_empty());
assert_eq!(params.host_identity().host_id(), "test-host-id");
assert_eq!(params.host_identity().serialno(), "test-serial");
assert_eq!(params.host_identity().mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn builder_accepts_pre_built_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyMac")
.build();
let expected_os_version = profile.os_version().to_string();
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyMac");
assert_eq!(params.os_version(), Some(expected_os_version.as_str()));
assert_eq!(params.client_os(), "Mac");
}
// ─── Delegation tests (Requirement 4.1) ──────────────────────────────────
#[test]
fn delegates_computer_to_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyComputer")
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyComputer");
assert_eq!(params.computer(), params.os_profile().computer());
}
#[test]
fn delegates_client_os_string_to_os_profile() {
let params = GpParams::builder(profile(ClientOs::Windows)).build();
assert_eq!(params.client_os(), "Windows");
assert_eq!(params.client_os(), params.os_profile().client_os().as_str());
}
#[test]
fn delegates_host_identity_to_os_profile() {
let identity = HostIdentity::new(
"delegated-computer".to_string(),
"delegated-host".to_string(),
"delegated-serial".to_string(),
"01:02:03:04:05:06".to_string(),
);
let params = GpParams::builder(
OsProfile::builder(ClientOs::Linux)
.host_identity(identity.clone())
.build(),
)
.build();
// The accessor returns the same HostIdentity stored on the inner OsProfile
assert_eq!(params.host_identity(), params.os_profile().host_identity());
assert_eq!(params.host_identity().host_id(), "delegated-host");
assert_eq!(params.host_identity().serialno(), "delegated-serial");
assert_eq!(params.host_identity().mac_addr(), "01:02:03:04:05:06");
}
// ─── Builder constructs OsProfile from individual fields (Req 4.1) ───────
#[test]
fn builder_uses_provided_os_profile() {
let identity = HostIdentity::new(
"identity-host".to_string(),
"host-7".to_string(),
"serial-7".to_string(),
"aa:bb:cc:11:22:33".to_string(),
);
let profile = OsProfile::builder(ClientOs::Linux)
.computer_name_override("linux-host")
.client_version("6.0.0-1".to_string())
.host_identity(identity)
.build();
let params = GpParams::builder(profile).build();
let profile = params.os_profile();
assert_eq!(profile.client_os(), ClientOs::Linux);
assert_eq!(profile.computer(), "linux-host");
assert_eq!(profile.os_version(), ClientOs::Linux.default_os_version());
assert_eq!(profile.client_version(), "6.0.0-1");
assert_eq!(profile.host_identity().host_id(), "host-7");
assert_eq!(profile.host_identity().serialno(), "serial-7");
assert_eq!(profile.host_identity().mac_addr(), "aa:bb:cc:11:22:33");
assert!(!profile.host_id().is_empty());
assert!(!profile.serialno().is_empty());
assert!(!profile.mac_addr().is_empty());
}
// ─── TryFrom<&GpParams> for Client (Requirement 4.7) ─────────────────────
#[test]
fn try_from_gp_params_constructs_reqwest_client() {
let params = GpParams::builder(profile(runtime_client_os())).build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client construction should succeed with default params");
}
#[test]
fn try_from_gp_params_with_ignore_tls_errors() {
let params = GpParams::builder(profile(runtime_client_os()))
.ignore_tls_errors(true)
.build();
let client = Client::try_from(&params);
assert!(
client.is_ok(),
"Client should construct successfully with ignore_tls_errors enabled"
);
}
#[test]
fn try_from_gp_params_with_custom_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
.user_agent("custom-agent/1.0")
.build(),
)
.build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client should construct with a custom user agent");
}
#[test]
fn try_from_gp_params_with_invalid_certificate_returns_error() {
// When a certificate path is provided but the file does not exist or is malformed,
// Client construction should fail rather than silently succeed.
let params = GpParams::builder(profile(runtime_client_os()))
.certificate("/nonexistent/path/to/cert.pem".to_string())
.build();
let client = Client::try_from(&params);
assert!(
client.is_err(),
"Client construction should fail when certificate path is invalid"
);
}
// ─── User Agent Delegation Tests (Requirements 3.2, 3.3, 3.4, 3.5, 3.6) ──
#[test]
fn user_agent_delegates_to_os_profile_for_default_build() {
let params = GpParams::builder(profile(runtime_client_os())).build();
assert_eq!(
params.user_agent(),
params.os_profile().user_agent(),
"GpParams::user_agent() should delegate to os_profile().user_agent()"
);
}
#[test]
fn builder_uses_profile_user_agent() {
let params = GpParams::builder(OsProfile::builder(runtime_client_os()).user_agent("custom").build()).build();
assert_eq!(params.user_agent(), "custom");
}
#[test]
fn builder_os_profile_without_user_agent_delegates_to_profile() {
let profile = OsProfile::builder(ClientOs::Mac).client_version("6.1.0").build();
let expected_ua = profile.user_agent().to_string();
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), expected_ua);
}
#[test]
fn profile_user_agent_override_wins_before_gp_params_construction() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.1.0")
.user_agent("override")
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), "override");
}
#[test]
fn try_from_gp_params_succeeds_with_delegated_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
.user_agent("delegated-agent/2.0")
.build(),
)
.build();
let client = Client::try_from(&params);
assert!(
client.is_ok(),
"TryFrom<&GpParams> for Client should succeed with delegated user_agent"
);
}
// ─── Property-Based Tests ─────────────────────────────────────────────────
mod prop_tests {
use super::*;
use proptest::prelude::*;
fn arb_client_os() -> impl Strategy<Value = ClientOs> {
prop_oneof![Just(ClientOs::Linux), Just(ClientOs::Windows), Just(ClientOs::Mac),]
}
// **Validates: Requirements 3.2, 3.4**
//
// Property 4: GpParams delegates user_agent to OsProfile
// For any GpParams instance (whether built from individual fields or from a
// pre-built OsProfile, with or without a user_agent override),
// gp_params.user_agent() == gp_params.os_profile().user_agent().
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn gp_params_delegates_user_agent_to_os_profile(
client_os in arb_client_os(),
user_agent_override in proptest::option::of("[a-zA-Z0-9/_.-]{1,30}"),
) {
let identity = HostIdentity::new(
"prop-computer".to_string(),
"prop-host".to_string(),
"prop-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let mut profile_builder = OsProfile::builder(client_os)
.client_version("6.1.0-1")
.computer_name_override("test-host")
.host_identity(identity);
if let Some(ref ua) = user_agent_override {
profile_builder = profile_builder.user_agent(ua);
}
let params = GpParams::builder(profile_builder.build()).build();
prop_assert_eq!(
params.user_agent(),
params.os_profile().user_agent(),
"GpParams::user_agent() must always equal GpParams::os_profile().user_agent()"
);
}
}
// **Validates: Requirements 3.3**
//
// Property 5: GpParams uses the user agent from OsProfile.
// For any non-empty string set via OsProfileBuilder::user_agent(), the resulting
// GpParams::user_agent() returns that override value.
proptest! {
#[test]
fn builder_uses_profile_user_agent(ua in "[^\\s]{1,50}") {
let profile = OsProfile::builder(runtime_client_os()).user_agent(&ua).build();
let params = GpParams::builder(profile).build();
prop_assert_eq!(params.user_agent(), ua.as_str());
}
}
}
}
+3
View File
@@ -1,8 +1,11 @@
pub mod auth;
pub mod cookie_store;
pub mod credential;
pub mod error;
pub mod gateway;
pub mod gp_params;
pub mod os_profile;
pub mod params;
pub mod portal;
pub mod process;
pub mod service;
@@ -0,0 +1,581 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use super::{ClientOs, serial_number};
use platform::RuntimeNativeHostIdentity;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostIdentity {
computer: String,
host_id: String,
#[serde(rename = "serialno")]
serial_number: String,
#[serde(rename = "macAddr")]
mac_address: String,
}
impl HostIdentity {
pub fn collect() -> Self {
Self::collect_with_host_id(None)
}
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
}
#[cfg(test)]
pub(crate) fn new(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
Self::from_parts(computer, host_id, serialno, mac_addr)
}
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id));
Self {
computer,
host_id,
serial_number,
mac_address,
}
}
pub fn computer(&self) -> &str {
&self.computer
}
pub fn host_id(&self) -> &str {
&self.host_id
}
pub fn serialno(&self) -> &str {
&self.serial_number
}
pub fn mac_addr(&self) -> &str {
&self.mac_address
}
pub fn with_computer(mut self, computer: String) -> Self {
if !computer.trim().is_empty() {
self.computer = computer;
}
self
}
pub(crate) fn runtime_os() -> ClientOs {
RuntimeNativeHostIdentity::runtime_os()
}
}
pub(super) fn fallback_hostname() -> String {
whoami::hostname().unwrap_or_else(|_| String::from("localhost"))
}
#[derive(Debug, Clone)]
struct NativeHostIdentitySnapshot {
host_id: String,
computer: String,
serial_number: Option<String>,
mac_address: Option<String>,
}
impl NativeHostIdentitySnapshot {
fn into_host_identity(self) -> HostIdentity {
let host_id = non_empty(self.host_id, fallback_host_id());
HostIdentity::from_parts(
self.computer,
host_id.clone(),
self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)),
self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)),
)
}
}
fn non_empty(value: String, fallback: String) -> String {
if value.trim().is_empty() { fallback } else { value }
}
fn fallback_host_id() -> String {
derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"])
}
fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String {
host_id_override
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(collect)
}
fn derive_serial_number(host_id: &str) -> String {
serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| {
let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]);
serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial")
})
}
fn derive_mac_address(host_id: &str) -> String {
let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
bytes.join(":")
}
fn normalize_mac_colon(value: &str) -> Option<String> {
let compact = value
.trim()
.replace('-', ":")
.split(':')
.map(|part| part.to_lowercase())
.collect::<Vec<_>>();
let valid = compact.len() == 6
&& compact
.iter()
.all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()));
valid.then(|| compact.join(":"))
}
fn primary_mac_colon() -> Option<String> {
netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.and_then(|mac| normalize_mac_colon(&mac))
}
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
#[cfg(target_os = "macos")]
mod platform {
use std::process::Command;
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
NativeHostIdentitySnapshot {
host_id,
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
serial_number: collect_macos_serial_number(),
mac_address: native_mac,
}
}
}
fn macos_computer_name() -> Option<String> {
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
let output = Command::new("scutil").args(["--get", name]).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 macos_builtin_mac() -> Option<String> {
macos_networksetup_mac("Wi-Fi")
.or_else(|| macos_networksetup_mac("AirPort"))
.or_else(macos_system_profiler_wifi_mac)
}
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
let output = Command::new("networksetup")
.arg("-listallhardwareports")
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == port_name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac() -> Option<String> {
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
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())
})
}
}
#[cfg(target_os = "windows")]
mod platform {
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Windows
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_windows_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
windows_machine_seed().unwrap_or_else(fallback_hostname)
}
}
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 windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "UUID")
.map(str::to_string)
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_linux_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
if let Some(host_id) = collect_linux_product_uuid() {
debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id);
return host_id;
}
let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| {
let hostname = fallback_hostname();
("hostname", hostname)
});
let host_id = derive_uuid_from_seed(&source, &[]);
debug!("Runtime host-id source: derived from {} ({})", source_name, host_id);
host_id
}
}
fn collect_linux_product_uuid() -> Option<String> {
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
}
fn normalize_uuid(value: &str) -> Option<String> {
uuid::Uuid::parse_str(value.trim())
.ok()
.map(|uuid| uuid.hyphenated().to_string())
}
fn collect_linux_fallback_seed() -> Option<(&'static str, String)> {
["/etc/machine-id", "/var/lib/dbus/machine-id"]
.iter()
.find_map(|path| read_linux_identity_file(path).map(|value| (*path, value)))
}
fn read_linux_identity_file(path: &str) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_usable_linux_identity_value(value))
}
fn is_usable_linux_identity_value(value: &str) -> bool {
!value.is_empty() && value != "None" && value != "To Be Filled By O.E.M."
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.iter()
.find_map(|path| read_linux_identity_file(path))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_uuid_preserves_real_uuid_identity() {
assert_eq!(
normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"),
Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string())
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collect_produces_non_empty_identity() {
let identity = HostIdentity::collect();
assert!(!identity.computer().is_empty());
assert!(!identity.host_id().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn collect_with_host_id_uses_provided_host_id() {
let identity = HostIdentity::collect_with_host_id(Some("provided-host-id"));
assert_eq!(identity.host_id(), "provided-host-id");
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
#[test]
fn collect_with_blank_host_id_falls_back_to_runtime_host_id() {
let identity = HostIdentity::collect_with_host_id(Some(" "));
assert!(!identity.host_id().is_empty());
assert_ne!(identity.host_id(), " ");
}
#[test]
fn resolve_host_id_does_not_collect_when_override_is_provided() {
let host_id = resolve_host_id(Some("provided-host-id"), || {
panic!("runtime host id should not be collected")
});
assert_eq!(host_id, "provided-host-id");
}
#[test]
fn host_identity_normalizes_mac_to_lowercase_colon_format() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"AA-BB-CC-DD-EE-FF".to_string(),
);
assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native = RuntimeNativeHostIdentity::collect(None);
assert!(!native.host_id.is_empty());
}
#[test]
fn serialization_keeps_globalprotect_field_names() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let value = serde_json::to_value(identity).unwrap();
assert_eq!(value["hostId"], "host-id");
assert_eq!(value["computer"], "computer");
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert_eq!(value["serialno"], "serial-number");
assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_identity_falls_back_to_derived_values_when_missing() {
let native = NativeHostIdentitySnapshot {
host_id: "native-host-id".to_string(),
computer: "native-computer".to_string(),
serial_number: None,
mac_address: None,
};
let identity = native.into_host_identity();
assert_eq!(identity.computer(), "native-computer");
assert_eq!(identity.host_id(), "native-host-id");
assert!(identity.serialno().starts_with("VMware-"));
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() {
let identity = HostIdentity::new(
"computer".to_string(),
"5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(),
String::new(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
assert_eq!(
identity.serialno(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn empty_host_id_falls_back_to_non_empty_value() {
let identity = HostIdentity::new(String::new(), String::new(), String::new(), String::new());
assert!(!identity.host_id().is_empty());
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
fn assert_mac(value: &str, separator: char) {
let parts: Vec<&str> = value.split(separator).collect();
assert_eq!(parts.len(), 6, "MAC should have 6 octets");
for part in &parts {
assert_eq!(part.len(), 2);
assert!(part.chars().all(|c| c.is_ascii_hexdigit()));
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,78 @@
pub(super) fn vmware_from_uuid(uuid: &str) -> Option<String> {
let parts: Vec<&str> = uuid.split('-').collect();
if parts.len() != 5
|| parts[0].len() != 8
|| parts[1].len() != 4
|| parts[2].len() != 4
|| parts[3].len() != 4
|| parts[4].len() != 12
|| !parts.iter().all(|part| part.chars().all(|ch| ch.is_ascii_hexdigit()))
{
return None;
}
let compact = [
reverse_hex_bytes(parts[0]),
reverse_hex_bytes(parts[1]),
reverse_hex_bytes(parts[2]),
parts[3].to_lowercase(),
parts[4].to_lowercase(),
]
.concat();
vmware_from_compact_hex(&compact)
}
pub(super) fn vmware_from_compact_hex(compact: &str) -> Option<String> {
let compact = compact.trim().to_lowercase();
if compact.len() != 32 || !compact.chars().all(|ch| ch.is_ascii_hexdigit()) {
return None;
}
Some(format!(
"VMware-{} {} {} {} {} {} {} {}-{} {} {} {} {} {} {} {}",
&compact[0..2],
&compact[2..4],
&compact[4..6],
&compact[6..8],
&compact[8..10],
&compact[10..12],
&compact[12..14],
&compact[14..16],
&compact[16..18],
&compact[18..20],
&compact[20..22],
&compact[22..24],
&compact[24..26],
&compact[26..28],
&compact[28..30],
&compact[30..32]
))
}
fn reverse_hex_bytes(value: &str) -> String {
value
.as_bytes()
.chunks(2)
.rev()
.map(|chunk| std::str::from_utf8(chunk).unwrap_or_default().to_lowercase())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vmware_serial_from_uuid_uses_smbios_byte_order() {
assert_eq!(
vmware_from_uuid("5a784d56-6461-19ac-9ea9-d36a3b9c6cef").unwrap(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn invalid_uuid_is_rejected() {
assert_eq!(vmware_from_uuid("not-a-uuid"), None);
}
}
+62
View File
@@ -0,0 +1,62 @@
use crate::{credential::Credential, gp_params::GpParams};
const EMPTY_PORTAL_COOKIE: &str = "empty";
fn portal_cookie_param(value: Option<&str>) -> String {
match value {
Some(value) if !value.is_empty() => value.to_string(),
_ => EMPTY_PORTAL_COOKIE.to_string(),
}
}
pub(crate) fn build(cred: &Credential, gp_params: &GpParams) -> Vec<(String, String)> {
let mut params = Vec::new();
params.push(("user".to_string(), cred.username().to_string()));
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match cred {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (
Some(gp_params.os_profile().saml_password()),
cred.prelogin_cookie(),
cred.portal_userauthcookie(),
None,
cred.token(),
),
Credential::AuthCookie(cred) => (
Some(
cred
.password()
.unwrap_or_else(|| gp_params.os_profile().saml_password()),
),
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::Cached(cred) => (
cred.password(),
None,
cred.auth_cookie().map(|cred| cred.user_auth_cookie()),
cred.auth_cookie().map(|cred| cred.prelogon_user_auth_cookie()),
None,
),
};
params.push(("passwd".to_string(), passwd.unwrap_or_default().to_string()));
params.push((
"prelogin-cookie".to_string(),
prelogin_cookie.unwrap_or_default().to_string(),
));
params.push((
"portal-userauthcookie".to_string(),
portal_cookie_param(portal_userauthcookie),
));
params.push((
"portal-prelogonuserauthcookie".to_string(),
portal_cookie_param(portal_prelogonuserauthcookie),
));
params.push(("token".to_string(), token.unwrap_or_default().to_string()));
params
}
+487
View File
@@ -0,0 +1,487 @@
use std::net::ToSocketAddrs;
use super::{RequestParams, credential as credential_params};
use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams};
/// Inputs required to build gateway login request parameters.
pub(crate) struct GatewayLoginInput<'a> {
pub gp_params: &'a GpParams,
pub cred: &'a Credential,
pub gateway_host: &'a str,
pub context: Option<&'a GatewayLoginContext>,
pub client_ip: Option<&'a str>,
pub extend_lifetime: bool,
}
/// Build request parameters for the gateway login endpoint.
///
/// Resolves the `server` parameter to an IPv4 address when
/// `profile.gateway_server_uses_resolved_ipv4()` is true.
/// Sets `gw` and `gateway-name` to the gateway FQDN.
pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams {
let profile = input.gp_params.os_profile();
let mut body: Vec<(String, String)> = Vec::new();
// Credential params (user, passwd, prelogin-cookie, portal-userauthcookie, etc.)
body.extend(credential_params::build(input.cred, input.gp_params));
// Common login params
body.push(("prot".into(), "https:".into()));
body.push(("jnlpReady".into(), "jnlpReady".into()));
body.push(("ok".into(), "Login".into()));
body.push(("direct".into(), "yes".into()));
body.push(("ipv6-support".into(), "yes".into()));
body.push(("clientVer".into(), "4100".into()));
body.push(("clientos".into(), profile.client_os().as_str().into()));
body.push(("computer".into(), profile.computer().into()));
body.push((
"inputStr".into(),
input.gp_params.input_str().unwrap_or_default().into(),
));
if let Some(otp) = input.gp_params.otp() {
body.push(("passwd".into(), otp.into()));
}
if let Some(os_version) = input.gp_params.os_version() {
body.push(("os-version".into(), os_version.into()));
}
// Server — resolve to IPv4 when profile requires it
let server = resolve_server(input);
body.push(("server".into(), server));
// Identity fields
body.push(("host-id".into(), profile.host_id().into()));
body.push(("serialno".into(), profile.serialno().into()));
body.push(("preferred-ip".into(), String::new()));
body.push(("preferred-ipv6".into(), String::new()));
// Client version
if let Some(client_version) = input.gp_params.client_version() {
body.push(("clientgpversion".into(), client_version.to_string()));
}
// Context-dependent fields
if let Some(context) = input.context {
let gateway_host = context.host().to_string();
body.push(("host".into(), gateway_host.clone()));
body.push(("gw".into(), gateway_host.clone()));
body.push(("gateway-name".into(), gateway_host));
body.push(("internal".into(), context.kind().as_login_param().to_string()));
body.push((
"selection-type".into(),
context.selection().as_login_param().to_string(),
));
body.push(("client-ipv6".into(), String::new()));
if let Some(connect_method) = context.connect_method() {
body.push(("connect-method".into(), connect_method.to_string()));
}
if let Some(client_version) = input.gp_params.client_version() {
// Ensure clientgpversion is set in the context block (override earlier value if present)
if let Some(pos) = body.iter().position(|(k, _)| k == "clientgpversion") {
body[pos].1 = client_version.to_string();
} else {
body.push(("clientgpversion".into(), client_version.to_string()));
}
}
if let Some(client_ip) = input.client_ip {
body.push(("client-ip".into(), client_ip.to_string()));
}
}
// Extend lifetime
if input.extend_lifetime {
body.push(("extend-lifetime".into(), "true".into()));
}
RequestParams { body, query: vec![] }
}
/// Resolve the gateway server to an IPv4 address if the profile requires it.
///
/// Falls back to the original gateway host if resolution fails.
fn resolve_server(input: &GatewayLoginInput) -> String {
if !input.gp_params.os_profile().gateway_server_uses_resolved_ipv4() {
return input.gateway_host.to_string();
}
if let Some(context) = input.context {
resolve_to_ipv4(context.host()).unwrap_or_else(|| input.gateway_host.to_string())
} else {
input.gateway_host.to_string()
}
}
/// Attempt DNS resolution of a hostname to its first IPv4 address.
fn resolve_to_ipv4(host: &str) -> Option<String> {
(host, 443)
.to_socket_addrs()
.ok()?
.find(|addr| addr.ip().is_ipv4())
.map(|addr| addr.ip().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
credential::{AuthCookieCredential, PasswordCredential},
gateway::{Gateway, GatewayKind, GatewaySelection},
os_profile::{ClientOs, HostIdentity, OsProfile},
};
fn test_identity() -> HostIdentity {
HostIdentity::new(
"test-computer".to_string(),
"host-id-123".to_string(),
"serial-456".to_string(),
"aa-bb-cc-dd-ee-ff".to_string(),
)
}
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os).host_identity(test_identity()).build()
}
fn make_gp_params() -> GpParams {
GpParams::builder(test_profile(ClientOs::Linux)).build()
}
fn make_credential() -> Credential {
Credential::Password(PasswordCredential::new("alice", "secret"))
}
#[test]
fn build_without_context_includes_identity_fields() {
let profile = test_profile(ClientOs::Linux);
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("host-id"), Some(profile.host_id()));
assert_eq!(find("serialno"), Some(profile.serialno()));
assert_eq!(find("preferred-ip"), Some(""));
assert_eq!(find("preferred-ipv6"), Some(""));
assert_eq!(find("token"), Some(""));
assert_eq!(find("server"), Some("vpn.example.com"));
}
#[test]
fn build_without_context_excludes_context_fields() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let has_key = |key: &str| result.body.iter().any(|(k, _)| k == key);
assert!(!has_key("host"));
assert!(!has_key("gw"));
assert!(!has_key("gateway-name"));
assert!(!has_key("internal"));
assert!(!has_key("selection-type"));
assert!(!has_key("connect-method"));
assert!(!has_key("client-ip"));
assert!(!has_key("client-ipv6"));
}
#[test]
fn build_with_context_includes_gateway_fqdn() {
let gp_params = make_gp_params();
let cred = make_credential();
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);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "us1.vpn.example.com",
context: Some(&context),
client_ip: Some("192.168.0.10"),
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("gw"), Some("us1.vpn.example.com"));
assert_eq!(find("gateway-name"), Some("us1.vpn.example.com"));
assert_eq!(find("host"), Some("us1.vpn.example.com"));
assert_eq!(find("internal"), Some("no"));
assert_eq!(find("selection-type"), Some("auto"));
assert_eq!(find("client-ip"), Some("192.168.0.10"));
assert_eq!(find("client-ipv6"), Some(""));
}
#[test]
fn mac_profile_uses_fqdn_for_gateway_display() {
let gp_params = GpParams::builder(test_profile(ClientOs::Mac)).build();
let cred = make_credential();
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);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "us1.vpn.example.com",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("gw"), Some("us1.vpn.example.com"));
assert_eq!(find("gateway-name"), Some("us1.vpn.example.com"));
}
#[test]
fn linux_prelogin_credential_uses_profile_saml_password() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::Prelogin(crate::credential::PreloginCredential::new(
"alice",
Some("prelogin-cookie"),
None,
None,
));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("SAMLPASS"));
}
#[test]
fn portal_auth_cookie_login_leaves_gateway_prelogin_cookie_empty() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::AuthCookie(AuthCookieCredential::new("alice", "empty", "empty"));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("passwd"), Some("SAMLPASS"));
assert_eq!(find("prelogin-cookie"), Some(""));
assert_eq!(find("portal-userauthcookie"), Some("empty"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("empty"));
}
#[test]
fn portal_auth_cookie_login_reuses_portal_password_when_available() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::AuthCookie(
AuthCookieCredential::new("alice", "portal-user-cookie", "portal-prelogon-cookie").with_password("secret"),
);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("passwd"), Some("secret"));
assert_eq!(find("prelogin-cookie"), Some(""));
assert_eq!(find("portal-userauthcookie"), Some("portal-user-cookie"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("portal-prelogon-cookie"));
}
#[test]
fn extend_lifetime_adds_param() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: true,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("extend-lifetime"), Some("true"));
}
#[test]
fn no_extend_lifetime_omits_param() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let has_key = |key: &str| result.body.iter().any(|(k, _)| k == key);
assert!(!has_key("extend-lifetime"));
}
#[test]
fn context_connect_method_included_when_present() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("GW".to_string(), "vpn.example.com".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual).with_connect_method(Some("on-demand"));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("connect-method"), Some("on-demand"));
assert_eq!(find("selection-type"), Some("manual"));
}
#[test]
fn all_params_in_body_not_query() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
assert!(result.query.is_empty());
assert!(!result.body.is_empty());
}
#[test]
fn server_resolves_to_ipv4_with_context_using_localhost() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("Local".to_string(), "localhost".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "localhost",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let server = result
.body
.iter()
.find(|(k, _)| k == "server")
.map(|(_, v)| v.as_str())
.expect("server param should exist");
// localhost resolves to 127.0.0.1 (IPv4)
assert_eq!(server, "127.0.0.1");
}
#[test]
fn server_falls_back_to_host_when_resolution_fails() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("GW".to_string(), "nonexistent.invalid.test".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "nonexistent.invalid.test",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let server = result
.body
.iter()
.find(|(k, _)| k == "server")
.map(|(_, v)| v.as_str())
.expect("server param should exist");
// Falls back to the original gateway host when DNS resolution fails
assert_eq!(server, "nonexistent.invalid.test");
}
}
+125
View File
@@ -0,0 +1,125 @@
use super::RequestParams;
use crate::os_profile::{OsProfile, PreloginBrowserMode, PreloginParamLocation};
/// Build request parameters for the gateway prelogin endpoint.
///
/// Same as portal prelogin but uses the gateway-specific embedded browser value.
pub(crate) fn build(profile: &OsProfile, browser_mode: PreloginBrowserMode) -> RequestParams {
let default_browser = profile.gateway_default_browser(browser_mode);
let params: Vec<(String, String)> = vec![
("tmp".into(), "tmp".into()),
("clientVer".into(), "4100".into()),
("clientos".into(), profile.client_os().as_str().into()),
("os-version".into(), profile.os_version().into()),
("host-id".into(), profile.host_id().into()),
("ipv6-support".into(), "yes".into()),
("default-browser".into(), default_browser.into()),
("cas-support".into(), "yes".into()),
("data".into(), "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9".into()),
];
let mut query: Vec<(String, String)> = vec![];
if profile.kerberos_support_in_query() {
query.push(("kerberos-support".into(), "yes".into()));
}
match profile.prelogin_param_location() {
PreloginParamLocation::Body => RequestParams { body: params, query },
PreloginParamLocation::Query => RequestParams {
body: vec![],
query: params.into_iter().chain(query).collect(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::ClientOs;
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert_eq!(result.query.len(), 1);
assert_eq!(result.query[0], ("kerberos-support".into(), "yes".into()));
}
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
// 9 base params + 1 kerberos-support
assert_eq!(result.query.len(), 10);
}
#[test]
fn uses_embedded_gateway_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "0");
}
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "4");
}
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"tmp"));
assert!(keys.contains(&"clientVer"));
assert!(keys.contains(&"clientos"));
assert!(keys.contains(&"os-version"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"ipv6-support"));
assert!(keys.contains(&"default-browser"));
assert!(keys.contains(&"cas-support"));
assert!(keys.contains(&"data"));
}
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
.body
.iter()
.find(|(k, _)| k == "data")
.expect("data param should exist");
assert_eq!(data_param.1, "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9");
}
}
+15
View File
@@ -0,0 +1,15 @@
pub(crate) mod credential;
pub mod gateway_login;
pub mod gateway_prelogin;
pub mod portal_getconfig;
pub mod portal_prelogin;
/// Ordered request parameters split into body (form data) and query string.
///
/// Uses `Vec<(String, String)>` instead of `HashMap` to preserve parameter
/// ordering, as some servers may be sensitive to order.
#[derive(Debug, Clone, Default)]
pub struct RequestParams {
pub body: Vec<(String, String)>,
pub query: Vec<(String, String)>,
}
+304
View File
@@ -0,0 +1,304 @@
use super::{RequestParams, credential as credential_params};
use crate::{credential::Credential, gp_params::GpParams, os_profile::ClientOs, portal::csc::swg_nonce};
/// Build request parameters for the portal getconfig endpoint.
///
/// This builder produces the form body for `getconfig.esp`. It deliberately
/// excludes `server`, `prot`, `direct`, and `jnlpReady` which are not sent
/// by the official client for this endpoint.
///
/// For SAML (prelogin) credentials the password is set to `SAMLPASS` on Linux
/// and left empty on macOS/Windows, matching official client behavior.
pub(crate) fn build(cred: &Credential, gp_params: &GpParams, server: &str) -> RequestParams {
let profile = gp_params.os_profile();
let nonce = if profile.client_os() == ClientOs::Linux {
"0".to_string()
} else {
swg_nonce()
};
let mut body = credential_params::build(cred, gp_params);
body.push(("inputStr".into(), gp_params.input_str().unwrap_or_default().into()));
// Fixed params
body.push(("ok".into(), "Login".into()));
body.push(("clientVer".into(), "4100".into()));
// OS params
body.push(("clientos".into(), profile.client_os().as_str().into()));
body.push(("clientgpversion".into(), profile.client_version().into()));
body.push(("computer".into(), profile.computer().into()));
body.push(("os-version".into(), profile.os_version().into()));
body.push(("host-id".into(), profile.host_id().into()));
body.push(("ipv6-support".into(), "yes".into()));
body.push(("serialno".into(), profile.serialno().into()));
// CSC fields
body.push(("csc-digest".into(), String::new()));
body.push(("config-digest".into(), String::new()));
body.push((
"csc-support".into(),
if gp_params.effective_csc_support() { "yes" } else { "no" }.into(),
));
// Host and SWG
body.push(("host".into(), server.into()));
body.push(("swg-auth-token".into(), "0".into()));
body.push(("swg-nonce".into(), nonce));
RequestParams { body, query: vec![] }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
credential::{PasswordCredential, PreloginCredential},
gp_params::CscMode,
os_profile::{ClientOs, HostIdentity, OsProfile},
};
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os)
.computer_name_override("test-computer")
.client_version("6.3.3-100")
.host_identity(HostIdentity::new(
"test-computer".into(),
"test-host-id".into(),
"test-serial".into(),
"aa:bb:cc:dd:ee:ff".into(),
))
.build()
}
fn password_cred() -> Credential {
Credential::from(PasswordCredential::new("alice", "secret"))
}
fn prelogin_cred() -> Credential {
Credential::Prelogin(PreloginCredential::new(
"alice",
Some("my-prelogin-cookie"),
Some("my-userauthcookie"),
None,
))
}
#[test]
fn excludes_forbidden_params() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(!keys.contains(&"server"));
assert!(!keys.contains(&"prot"));
assert!(!keys.contains(&"direct"));
assert!(!keys.contains(&"jnlpReady"));
}
#[test]
fn includes_required_params() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"clientgpversion"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"serialno"));
assert!(keys.contains(&"token"));
}
#[test]
fn includes_identity_from_profile() {
let profile = test_profile(ClientOs::Mac);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("host-id"), Some(profile.host_id()));
assert_eq!(find("serialno"), Some(profile.serialno()));
assert_eq!(find("clientgpversion"), Some("6.3.3-100"));
assert_eq!(find("computer"), Some("test-computer"));
assert_eq!(find("os-version"), Some(profile.os_version()));
assert_eq!(find("clientos"), Some("Mac"));
}
#[test]
fn linux_saml_sets_passwd_to_samlpass() {
let profile = test_profile(ClientOs::Linux);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("SAMLPASS"));
}
#[test]
fn mac_saml_sets_passwd_to_empty() {
let profile = test_profile(ClientOs::Mac);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some(""));
}
#[test]
fn saml_without_portal_auth_cookies_uses_empty_sentinel() {
let profile = test_profile(ClientOs::Mac);
let cred = Credential::Prelogin(PreloginCredential::new("alice", Some("my-prelogin-cookie"), None, None));
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("portal-userauthcookie"), Some("empty"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("empty"));
}
#[test]
fn saml_blank_portal_auth_cookie_uses_empty_sentinel() {
let profile = test_profile(ClientOs::Mac);
let cred = Credential::Prelogin(PreloginCredential::new(
"alice",
Some("my-prelogin-cookie"),
Some(""),
None,
));
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let portal_cookie = result
.body
.iter()
.find(|(k, _)| k == "portal-userauthcookie")
.map(|(_, v)| v.as_str());
assert_eq!(portal_cookie, Some("empty"));
}
#[test]
fn windows_saml_sets_passwd_to_empty() {
let profile = test_profile(ClientOs::Windows);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some(""));
}
#[test]
fn password_cred_sends_actual_password() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("secret"));
}
#[test]
fn includes_csc_support_fields() {
let profile = test_profile(ClientOs::Mac);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("csc-support"), Some("yes"));
assert_eq!(find("csc-digest"), Some(""));
assert_eq!(find("config-digest"), Some(""));
assert_eq!(find("swg-auth-token"), Some("0"));
assert!(find("swg-nonce").is_some());
}
#[test]
fn linux_uses_zero_swg_nonce() {
let profile = test_profile(ClientOs::Linux);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let nonce = result
.body
.iter()
.find(|(k, _)| k == "swg-nonce")
.map(|(_, v)| v.as_str());
assert_eq!(nonce, Some("0"));
}
#[test]
fn linux_defaults_csc_support_to_no() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let csc = result
.body
.iter()
.find(|(k, _)| k == "csc-support")
.map(|(_, v)| v.as_str());
assert_eq!(csc, Some("no"));
}
#[test]
fn csc_mode_override_works() {
let cred = password_cred();
let gp_params = GpParams::builder(test_profile(ClientOs::Linux))
.csc_mode(CscMode::Yes)
.build();
let result = build(&cred, &gp_params, "vpn.example.com");
let csc = result
.body
.iter()
.find(|(k, _)| k == "csc-support")
.map(|(_, v)| v.as_str());
assert_eq!(csc, Some("yes"));
}
#[test]
fn host_param_is_server_value() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let host = result.body.iter().find(|(k, _)| k == "host").map(|(_, v)| v.as_str());
assert_eq!(host, Some("vpn.example.com"));
}
#[test]
fn token_is_empty_for_password_cred() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let token = result.body.iter().find(|(k, _)| k == "token").map(|(_, v)| v.as_str());
assert_eq!(token, Some(""));
}
#[test]
fn all_params_in_body_not_query() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
}
+147
View File
@@ -0,0 +1,147 @@
use super::RequestParams;
use crate::os_profile::{OsProfile, PreloginBrowserMode, PreloginParamLocation};
/// Build request parameters for the portal prelogin endpoint.
///
/// Parameters are placed in the request body for Linux/macOS and in the query
/// string for Windows, based on `profile.prelogin_param_location()`.
///
/// When `profile.kerberos_support_in_query()` is true (macOS/Windows),
/// `kerberos-support=yes` is added as a query parameter.
pub(crate) fn build(profile: &OsProfile, browser_mode: PreloginBrowserMode) -> RequestParams {
let default_browser = profile.portal_default_browser(browser_mode);
let params: Vec<(String, String)> = vec![
("tmp".into(), "tmp".into()),
("clientVer".into(), "4100".into()),
("clientos".into(), profile.client_os().as_str().into()),
("os-version".into(), profile.os_version().into()),
("host-id".into(), profile.host_id().into()),
("ipv6-support".into(), "yes".into()),
("default-browser".into(), default_browser.into()),
("cas-support".into(), "yes".into()),
("data".into(), "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9".into()),
];
let mut query: Vec<(String, String)> = vec![];
if profile.kerberos_support_in_query() {
query.push(("kerberos-support".into(), "yes".into()));
}
match profile.prelogin_param_location() {
PreloginParamLocation::Body => RequestParams { body: params, query },
PreloginParamLocation::Query => RequestParams {
body: vec![],
query: params.into_iter().chain(query).collect(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::ClientOs;
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert_eq!(result.query.len(), 1);
assert_eq!(result.query[0], ("kerberos-support".into(), "yes".into()));
}
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
// 9 base params + 1 kerberos-support
assert_eq!(result.query.len(), 10);
}
#[test]
fn uses_embedded_portal_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "-10");
}
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "4");
}
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"tmp"));
assert!(keys.contains(&"clientVer"));
assert!(keys.contains(&"clientos"));
assert!(keys.contains(&"os-version"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"ipv6-support"));
assert!(keys.contains(&"default-browser"));
assert!(keys.contains(&"cas-support"));
assert!(keys.contains(&"data"));
}
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
.body
.iter()
.find(|(k, _)| k == "data")
.expect("data param should exist");
assert_eq!(data_param.1, "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9");
}
#[test]
fn kerberos_not_in_query_for_linux() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support");
assert!(!has_kerberos);
}
#[test]
fn kerberos_in_query_for_windows() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support");
assert!(has_kerberos);
}
}
+196 -26
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
@@ -11,9 +13,12 @@ use crate::{
error::PortalError,
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
params,
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
};
use super::csc;
#[derive(Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PortalConfig {
@@ -21,6 +26,7 @@ pub struct PortalConfig {
auth_cookie: AuthCookieCredential,
config_cred: Credential,
gateways: Vec<Gateway>,
connect_method: Option<String>,
config_digest: Option<String>,
/**
* Variants:
@@ -37,6 +43,10 @@ pub struct PortalConfig {
* Whether the portal policy allows extending the gateway session.
*/
allow_extend_session: Option<bool>,
/**
* Whether the portal policy enables default-browser authentication.
*/
default_browser: Option<bool>,
}
impl PortalConfig {
@@ -60,6 +70,10 @@ impl PortalConfig {
self.internal_host_detection
}
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub fn version(&self) -> Option<&str> {
self.version.as_deref()
}
@@ -68,6 +82,10 @@ impl PortalConfig {
self.allow_extend_session
}
pub fn default_browser(&self) -> Option<bool> {
self.default_browser
}
/// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region);
@@ -118,16 +136,17 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let url = format!("{}/global-protect/getconfig.esp", portal);
let client = Client::try_from(gp_params)?;
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);
let request_params = params::portal_getconfig::build(cred, gp_params, &server);
let body_pairs: Vec<(&str, &str)> = request_params
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_form_params(&body_pairs));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
@@ -152,11 +171,86 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
debug!("Portal config response: {}", res_xml);
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));
if !gp_params.effective_csc_support() {
bail!(PortalError::ConfigError(
"Portal returned CSC criteria but CSC support is disabled".to_string()
));
}
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)
}
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 prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true;
prefer_internal = internal_host_detect(&ihd_node)
prefer_internal = internal_host_detect(ihd_node)
}
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -169,27 +263,41 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
.descendant_text("portal-prelogonuserauthcookie")
.unwrap_or_default();
let config_digest = root.descendant_text("config-digest");
let connect_method = parse_connect_method(&root);
if gateways.is_empty() {
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());
info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
let default_browser = parse_default_browser(&root);
Ok(PortalConfig {
portal: server.to_string(),
auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie),
config_cred: cred.clone(),
gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version,
allow_extend_session,
default_browser,
})
}
fn parse_default_browser(root: &Element) -> Option<bool> {
match root.descendant_text("default-browser")?.trim() {
"yes" => Some(true),
"no" => Some(false),
_ => None,
}
}
fn parse_allow_extend_session(root: &Element) -> Option<bool> {
match root.descendant_text("allow-extend-session")?.trim() {
"yes" => Some(true),
@@ -198,6 +306,13 @@ fn parse_allow_extend_session(root: &Element) -> Option<bool> {
}
}
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
fn internal_host_detect(element: &Element) -> bool {
let ip_info = [
@@ -208,23 +323,24 @@ fn internal_host_detect(element: &Element) -> bool {
info!("Found internal-host-detection, performing DNS lookup");
for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref()) {
if !ip_address.is_empty() && !host.is_empty() {
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
&& !ip_address.is_empty()
&& !host.is_empty()
{
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
}
}
@@ -267,4 +383,58 @@ mod tests {
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn parses_default_browser_yes() {
let root = parse_xml("<response><default-browser>yes</default-browser></response>");
assert_eq!(parse_default_browser(&root), Some(true));
}
#[test]
fn parses_default_browser_no() {
let root = parse_xml("<response><default-browser>no</default-browser></response>");
assert_eq!(parse_default_browser(&root), Some(false));
}
#[test]
fn leaves_absent_default_browser_unknown() {
let root = parse_xml("<response></response>");
assert_eq!(parse_default_browser(&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);
}
}
+735
View File
@@ -0,0 +1,735 @@
use std::{
collections::HashMap,
fmt::Write,
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use xmltree::{Element, EmitterConfig, XMLNode};
use crate::{gp_params::GpParams, 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(crate) 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 = gp_params.host_id().to_string();
let serial_number = gp_params.serialno().to_string();
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")));
let custom_checks = build_custom_checks(input.criteria, input.gp_params, reader, summary);
if !custom_checks.children.is_empty() {
root.children.push(XMLNode::Element(custom_checks));
}
let mut bytes = Vec::new();
root.write_with_config(
&mut bytes,
EmitterConfig::new()
.perform_indent(true)
.indent_string("\t")
.write_document_declaration(true),
)?;
String::from_utf8(bytes)
.map(|xml| {
let mut xml = xml.replace("<categories />", "<categories>\n\t</categories>");
xml.push('\n');
xml
})
.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.os_profile().supports_macos_plist_csc()
&& 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, reader, summary)));
}
if gp_params.os_profile().supports_linux_process_csc()
&& 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,
)));
}
if gp_params.os_profile().supports_windows_registry_csc()
&& let Some(registry_key) = requested_checks
.child("windows")
.and_then(|windows| windows.child("registry-key"))
.or_else(|| requested_checks.child("registry-key"))
{
custom_checks
.children
.push(XMLNode::Element(build_registry_key_checks(registry_key)));
}
custom_checks
}
fn build_plist_checks(plist: &Element, 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 = 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 build_registry_key_checks(registry_key: &Element) -> Element {
let mut out = Element::new("registry-key");
for name in registry_key_names(registry_key) {
let mut entry = Element::new("entry");
entry.attributes.insert("name".to_string(), name);
push_text(&mut entry, "exist", "no");
push_text(&mut entry, "value", "");
out.children.push(XMLNode::Element(entry));
}
out
}
fn registry_key_names(registry_key: &Element) -> Vec<String> {
let mut names: Vec<String> = registry_key
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.collect();
names.extend(
registry_key
.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 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::GpParams,
os_profile::{ClientOs, HostIdentity, OsProfile},
};
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 {
let profile = OsProfile::builder(client_os)
.host_identity(HostIdentity::new(
"test-computer".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
GpParams::builder(profile).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+"));
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 empty_csc_report_uses_official_format_for_digest() {
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 req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
let digest_input = req.csc_data.replace(&req.csc_digest, DIGEST_PLACEHOLDER);
assert_eq!(req.csc_digest, pan_md5_hex(digest_input.as_bytes()));
assert!(
req
.csc_data
.contains("\n\t<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>")
);
assert!(req.csc_data.contains("\n\t<categories>\n\t</categories>\n"));
assert!(req.csc_data.ends_with("</hip-report>\n"));
}
#[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 builds_windows_registry_key_report() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<windows>
<registry-key>
<entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\TenantInfo\00000000-0000-4000-8000-000000000000" />
</registry-key>
</windows>
</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::Windows), &reader).unwrap();
assert!(req.csc_data.contains("<custom-checks>"));
assert!(req.csc_data.contains("<registry-key>"));
assert!(
req
.csc_data
.contains(r#"<entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\TenantInfo\00000000-0000-4000-8000-000000000000">"#)
);
assert!(req.csc_data.contains("<exist>no</exist>"));
assert!(req.csc_data.contains("<value />") || req.csc_data.contains("<value></value>"));
}
#[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,4 +1,5 @@
mod config;
pub(crate) mod csc;
mod prelogin;
pub use config::*;
+135 -21
View File
@@ -8,20 +8,11 @@ use xmltree::Element;
use crate::{
error::PortalError,
gp_params::GpParams,
os_profile::PreloginBrowserMode,
params::{gateway_prelogin, portal_prelogin},
utils::{base64, normalize_server, parse_gp_response, xml::ElementExt},
};
const REQUIRED_PARAMS: [&str; 8] = [
"tmp",
"clientVer",
"clientos",
"os-version",
"host-id",
"ipv6-support",
"default-browser",
"cas-support",
];
#[derive(Debug, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SamlPrelogin {
@@ -96,27 +87,64 @@ impl Prelogin {
}
}
pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> {
#[derive(Debug, Clone, Copy, Default)]
pub struct PreloginOptions {
external_browser_requested: bool,
gateway_external_browser_allowed: bool,
}
impl PreloginOptions {
pub fn external_browser_requested(mut self, external_browser_requested: bool) -> Self {
self.external_browser_requested = external_browser_requested;
self
}
pub fn gateway_external_browser_allowed(mut self, gateway_external_browser_allowed: bool) -> Self {
self.gateway_external_browser_allowed = gateway_external_browser_allowed;
self
}
fn browser_mode(self, is_gateway: bool) -> PreloginBrowserMode {
if self.external_browser_requested && (!is_gateway || self.gateway_external_browser_allowed) {
PreloginBrowserMode::External
} else {
PreloginBrowserMode::Embedded
}
}
}
pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptions) -> anyhow::Result<Prelogin> {
let user_agent = gp_params.user_agent();
let is_gateway = gp_params.is_gateway();
let prelogin_type = if is_gateway { "Gateway" } else { "Portal" };
info!("{} prelogin with user_agent: {}", prelogin_type, user_agent);
let portal = normalize_server(portal)?;
let path = if is_gateway { "ssl-vpn" } else { "global-protect" };
let prelogin_url = format!("{portal}/{}/prelogin.esp", path);
let mut params = gp_params.to_params();
let browser_mode = options.browser_mode(is_gateway);
let request_params = if is_gateway {
gateway_prelogin::build(gp_params.os_profile(), browser_mode)
} else {
portal_prelogin::build(gp_params.os_profile(), browser_mode)
};
let default_browser = request_param(&request_params, "default-browser").unwrap_or("");
params.insert("tmp", "tmp");
params.insert("default-browser", "1");
params.insert("cas-support", "yes");
params.retain(|k, _| REQUIRED_PARAMS.iter().any(|required_param| required_param == k));
info!(
"{} prelogin with user_agent: {}, default_browser: {}",
prelogin_type, user_agent, default_browser
);
let client = Client::try_from(gp_params)?;
let res = client.post(&prelogin_url).form(&params).send().await.map_err(|e| {
let mut request = client.post(&prelogin_url);
if !request_params.query.is_empty() {
request = request.query(&request_params.query);
}
if !request_params.body.is_empty() {
request = request.form(&request_params.body);
}
let res = request.send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
@@ -144,6 +172,14 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
Ok(prelogin)
}
fn request_param<'a>(params: &'a crate::params::RequestParams, name: &str) -> Option<&'a str> {
params
.body
.iter()
.chain(params.query.iter())
.find_map(|(key, value)| (key == name).then_some(value.as_str()))
}
fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let root = Element::parse(res_xml.as_bytes())?;
@@ -203,3 +239,81 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
Ok(Prelogin::Standard(standard_prelogin))
}
#[cfg(test)]
mod tests {
use super::PreloginOptions;
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, HostIdentity, OsProfile, PreloginBrowserMode},
params::{gateway_prelogin, portal_prelogin},
};
fn gp_params(client_os: ClientOs) -> GpParams {
let profile = OsProfile::builder(client_os)
.host_identity(HostIdentity::new(
"test-computer".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
GpParams::builder(profile).build()
}
#[test]
fn portal_prelogin_params_include_official_profile_fields() {
let gp_params = gp_params(ClientOs::Linux);
let request_params = portal_prelogin::build(gp_params.os_profile(), PreloginBrowserMode::Embedded);
let body: std::collections::HashMap<&str, &str> = request_params
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let query: std::collections::HashMap<&str, &str> = request_params
.query
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
assert_eq!(body.get("host-id"), Some(&gp_params.os_profile().host_id()));
assert_eq!(body.get("default-browser"), Some(&"-10"));
assert_eq!(body.get("cas-support"), Some(&"yes"));
assert_eq!(body.get("data"), Some(&r#"eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9"#));
// Linux does not place kerberos-support in the query string.
assert_eq!(query.get("kerberos-support"), None);
}
#[test]
fn gateway_prelogin_uses_gateway_default_browser() {
let gp_params = gp_params(ClientOs::Mac);
let request_params = gateway_prelogin::build(gp_params.os_profile(), PreloginBrowserMode::Embedded);
let body: std::collections::HashMap<&str, &str> = request_params
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
assert_eq!(body.get("default-browser"), Some(&"0"));
}
#[test]
fn browser_mode_uses_external_for_portal_when_requested() {
let options = PreloginOptions::default().external_browser_requested(true);
assert_eq!(options.browser_mode(false), PreloginBrowserMode::External);
}
#[test]
fn browser_mode_requires_gateway_external_browser_allowed_for_gateway_external() {
let options = PreloginOptions::default().external_browser_requested(true);
assert_eq!(options.browser_mode(true), PreloginBrowserMode::Embedded);
let options = options.gateway_external_browser_allowed(true);
assert_eq!(options.browser_mode(true), PreloginBrowserMode::External);
}
}
+101 -28
View File
@@ -1,10 +1,10 @@
use std::process::Stdio;
use std::{path::PathBuf, process::Stdio};
use anyhow::bail;
use common::constants::GP_AUTH_BINARY;
use common::binary_paths;
use tokio::process::Command;
use crate::{auth::SamlAuthResult, credential::Credential};
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
use super::command_traits::CommandExt;
@@ -13,9 +13,12 @@ pub struct SamlAuthLauncher<'a> {
auth_executable: Option<&'a str>,
gateway: bool,
saml_request: Option<&'a str>,
user_agent: Option<&'a str>,
os: Option<&'a str>,
os_version: Option<&'a str>,
host_id: Option<&'a str>,
client_version: Option<&'a str>,
certificate: Option<&'a str>,
sslkey: Option<&'a str>,
key_password: Option<&'a str>,
fix_openssl: bool,
ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")]
@@ -35,9 +38,12 @@ impl<'a> SamlAuthLauncher<'a> {
auth_executable: None,
gateway: false,
saml_request: None,
user_agent: None,
os: None,
os_version: None,
host_id: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
fix_openssl: false,
ignore_tls_errors: false,
#[cfg(feature = "webview-auth")]
@@ -66,18 +72,10 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
pub fn user_agent(mut self, user_agent: &'a str) -> Self {
self.user_agent = Some(user_agent);
self
}
pub fn os(mut self, os: &'a str) -> Self {
self.os = Some(os);
self
}
pub fn os_version(mut self, os_version: Option<&'a str>) -> Self {
self.os_version = os_version;
pub fn os_profile(mut self, profile: &'a OsProfile) -> Self {
self.os = Some(profile.client_os().as_str());
self.host_id = Some(profile.host_identity().host_id());
self.client_version = Some(profile.client_version());
self
}
@@ -91,6 +89,21 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
pub fn certificate(mut self, certificate: Option<&'a str>) -> Self {
self.certificate = certificate;
self
}
pub fn sslkey(mut self, sslkey: Option<&'a str>) -> Self {
self.sslkey = sslkey;
self
}
pub fn key_password(mut self, key_password: Option<&'a str>) -> Self {
self.key_password = key_password;
self
}
#[cfg(feature = "webview-auth")]
pub fn hidpi(mut self, hidpi: bool) -> Self {
self.hidpi = hidpi;
@@ -121,8 +134,11 @@ impl<'a> SamlAuthLauncher<'a> {
/// Launch the authenticator binary as the current user or SUDO_USER if available.
pub async fn launch(self) -> anyhow::Result<Credential> {
let program = self.auth_executable.unwrap_or(GP_AUTH_BINARY);
let mut auth_cmd = Command::new(program);
let program = self
.auth_executable
.map(PathBuf::from)
.unwrap_or_else(binary_paths::gpauth);
let mut auth_cmd = Command::new(&program);
auth_cmd.arg(self.server);
if self.gateway {
@@ -133,16 +149,16 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--saml-request").arg(saml_request);
}
if let Some(user_agent) = self.user_agent {
auth_cmd.arg("--user-agent").arg(user_agent);
}
if let Some(os) = self.os {
auth_cmd.arg("--os").arg(os);
}
if let Some(os_version) = self.os_version {
auth_cmd.arg("--os-version").arg(os_version);
if let Some(host_id) = self.host_id {
auth_cmd.arg("--host-id").arg(host_id);
}
if let Some(client_version) = self.client_version {
auth_cmd.arg("--client-version").arg(client_version);
}
if self.fix_openssl {
@@ -153,6 +169,18 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--ignore-tls-errors");
}
if let Some(certificate) = self.certificate {
auth_cmd.arg("--certificate").arg(certificate);
}
if let Some(sslkey) = self.sslkey {
auth_cmd.arg("--sslkey").arg(sslkey);
}
if let Some(key_password) = self.key_password {
auth_cmd.arg("--key-password").arg(key_password);
}
#[cfg(feature = "webview-auth")]
{
if self.hidpi {
@@ -182,7 +210,7 @@ impl<'a> SamlAuthLauncher<'a> {
let child = match child {
Ok(child) => child,
Err(err) => {
bail!("Failed to spawn {}: {}", program, err);
bail!("Failed to spawn {}: {}", program.display(), err);
}
};
@@ -195,3 +223,48 @@ impl<'a> SamlAuthLauncher<'a> {
Credential::try_from(auth_result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::{ClientOs, OsProfileBuilder};
#[test]
fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
assert_eq!(launcher.os, Some("Linux"));
}
#[test]
fn os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
assert_eq!(launcher.host_id, Some(profile.host_identity().host_id()));
}
#[test]
fn os_profile_sets_client_version_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
assert_eq!(launcher.client_version, Some("6.0.0"));
}
#[test]
fn client_certificate_options_are_stored() {
let launcher = SamlAuthLauncher::new("portal.example.com")
.certificate(Some("/tmp/client.pem"))
.sslkey(Some("/tmp/client.key"))
.key_password(Some("secret"));
assert_eq!(launcher.certificate, Some("/tmp/client.pem"));
assert_eq!(launcher.sslkey, Some("/tmp/client.key"));
assert_eq!(launcher.key_password, Some("secret"));
}
}
+3 -1
View File
@@ -2,7 +2,7 @@ use std::ffi::OsStr;
use tokio::process::Command;
use uzers::os::unix::UserExt;
use super::users::get_non_root_user;
use super::{desktop_session_env, users::get_non_root_user};
pub trait CommandExt {
fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command;
@@ -28,6 +28,8 @@ impl CommandExt for Command {
fn into_non_root(mut self) -> anyhow::Result<Command> {
let user = get_non_root_user().map_err(|_| anyhow::anyhow!("{:?} cannot be run as root", self))?;
desktop_session_env::apply(&mut self, user.uid(), user.home_dir());
self
.env("HOME", user.home_dir())
.env("USER", user.name())
@@ -0,0 +1,217 @@
use std::path::Path;
use tokio::process::Command;
pub(super) fn apply(command: &mut Command, user_id: u32, home_dir: &Path) {
platform::apply(command, user_id, home_dir);
}
#[cfg(target_os = "linux")]
mod platform {
use std::{collections::HashMap, env, fs, os::unix::fs::MetadataExt, path::Path};
use tokio::process::Command;
const DESKTOP_SESSION_ENV: &[&str] = &[
"BROWSER",
"DBUS_SESSION_BUS_ADDRESS",
"DESKTOP_SESSION",
"DISPLAY",
"MOZ_ENABLE_WAYLAND",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_CONFIG_HOME",
"XDG_CURRENT_DESKTOP",
"XDG_DATA_DIRS",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
];
pub(super) fn apply(command: &mut Command, user_id: u32, home_dir: &Path) {
let session_env = collect(user_id);
for key in DESKTOP_SESSION_ENV {
if let Some(value) = desktop_env_value(&session_env, key) {
command.env(key, value);
}
}
let runtime_dir =
desktop_env_value(&session_env, "XDG_RUNTIME_DIR").unwrap_or_else(|| format!("/run/user/{user_id}"));
command.env("XDG_RUNTIME_DIR", &runtime_dir);
if desktop_env_value(&session_env, "DBUS_SESSION_BUS_ADDRESS").is_none() {
command.env("DBUS_SESSION_BUS_ADDRESS", format!("unix:path={runtime_dir}/bus"));
}
if desktop_env_value(&session_env, "XDG_DATA_HOME").is_none() {
command.env("XDG_DATA_HOME", home_dir.join(".local/share"));
}
if desktop_env_value(&session_env, "XDG_CONFIG_HOME").is_none() {
command.env("XDG_CONFIG_HOME", home_dir.join(".config"));
}
if desktop_env_value(&session_env, "XDG_DATA_DIRS").is_none() {
command.env("XDG_DATA_DIRS", default_xdg_data_dirs());
}
}
fn collect(user_id: u32) -> HashMap<String, String> {
let mut best = HashMap::new();
let mut best_score = 0;
let Ok(entries) = fs::read_dir("/proc") else {
return best;
};
for entry in entries.flatten() {
let path = entry.path();
if !is_process_dir(&path) || !owned_by_user(&path, user_id) {
continue;
}
let env = read_environ(&path);
let score = score_env(&env);
if score > best_score {
best_score = score;
best = env;
}
}
best
}
fn is_process_dir(path: &Path) -> bool {
path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.bytes().all(|byte| byte.is_ascii_digit()))
}
fn owned_by_user(path: &Path, user_id: u32) -> bool {
path.metadata().is_ok_and(|metadata| metadata.uid() == user_id)
}
fn read_environ(process_dir: &Path) -> HashMap<String, String> {
let path = process_dir.join("environ");
let Ok(bytes) = fs::read(path) else {
return HashMap::new();
};
parse_environ(&bytes)
}
fn parse_environ(bytes: &[u8]) -> HashMap<String, String> {
bytes
.split(|byte| *byte == b'\0')
.filter_map(|entry| {
let index = entry.iter().position(|byte| *byte == b'=')?;
let (key, value) = (&entry[..index], &entry[index + 1..]);
let key = std::str::from_utf8(key).ok()?;
if !DESKTOP_SESSION_ENV.contains(&key) {
return None;
}
let value = String::from_utf8_lossy(value).to_string();
Some((key.to_string(), value))
})
.filter_map(|(key, value)| non_empty(Some(value)).map(|value| (key, value)))
.collect()
}
fn score_env(env: &HashMap<String, String>) -> usize {
let mut score = 0;
if env.contains_key("DBUS_SESSION_BUS_ADDRESS") {
score += 4;
}
if env.contains_key("XDG_RUNTIME_DIR") {
score += 3;
}
if env.contains_key("WAYLAND_DISPLAY") || env.contains_key("DISPLAY") {
score += 3;
}
if env.contains_key("XDG_CURRENT_DESKTOP") {
score += 2;
}
if env.contains_key("XDG_DATA_DIRS") {
score += 1;
}
score
}
fn env_value(key: &str) -> Option<String> {
non_empty(env::var(key).ok())
}
fn desktop_env_value(session_env: &HashMap<String, String>, key: &str) -> Option<String> {
session_env.get(key).cloned().or_else(|| env_value(key))
}
fn non_empty(value: Option<String>) -> Option<String> {
value.filter(|value| !value.trim().is_empty())
}
fn default_xdg_data_dirs() -> &'static str {
"/usr/local/share:/usr/share:/var/lib/snapd/desktop"
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_environ_keeps_only_desktop_session_values() {
let env = parse_environ(b"DISPLAY=:0\0PASSWORD=secret\0XDG_DATA_DIRS=/usr/share\0EMPTY= \0");
assert_eq!(env.get("DISPLAY").map(String::as_str), Some(":0"));
assert_eq!(env.get("XDG_DATA_DIRS").map(String::as_str), Some("/usr/share"));
assert!(!env.contains_key("PASSWORD"));
assert!(!env.contains_key("EMPTY"));
}
#[test]
fn score_prefers_graphical_session_env() {
let plain = HashMap::from([("XDG_DATA_DIRS".to_string(), "/usr/share".to_string())]);
let graphical = HashMap::from([
(
"DBUS_SESSION_BUS_ADDRESS".to_string(),
"unix:path=/run/user/1000/bus".to_string(),
),
("XDG_RUNTIME_DIR".to_string(), "/run/user/1000".to_string()),
("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string()),
]);
assert!(score_env(&graphical) > score_env(&plain));
}
#[test]
fn non_empty_ignores_missing_or_blank_values() {
assert_eq!(non_empty(None), None);
assert_eq!(non_empty(Some(" ".to_string())), None);
assert_eq!(non_empty(Some("value".to_string())), Some("value".to_string()));
}
#[test]
fn desktop_env_value_prefers_collected_user_session() {
let env = HashMap::from([("XDG_DATA_DIRS".to_string(), "/run/current-system/sw/share".to_string())]);
assert_eq!(
desktop_env_value(&env, "XDG_DATA_DIRS"),
Some("/run/current-system/sw/share".to_string())
);
}
}
}
#[cfg(not(target_os = "linux"))]
mod platform {
use std::path::Path;
use tokio::process::Command;
pub(super) fn apply(_command: &mut Command, _user_id: u32, _home_dir: &Path) {}
}
@@ -1,7 +1,7 @@
use std::{collections::HashMap, path::PathBuf, process::Stdio};
use anyhow::bail;
use common::constants::GP_GUI_HELPER_BINARY;
use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
@@ -17,7 +17,7 @@ pub struct GuiHelperLauncher<'a> {
impl<'a> GuiHelperLauncher<'a> {
pub fn new(api_key: &'a [u8]) -> Self {
Self {
program: GP_GUI_HELPER_BINARY.into(),
program: binary_paths::gpgui_helper(),
envs: None,
api_key,
gui_version: None,
+2 -2
View File
@@ -5,7 +5,7 @@ use std::{
};
use anyhow::bail;
use common::constants::GP_GUI_BINARY;
use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
@@ -25,7 +25,7 @@ impl<'a> GuiLauncher<'a> {
pub fn new(version: &'a str, api_key: &'a [u8]) -> Self {
Self {
version,
program: GP_GUI_BINARY.into(),
program: binary_paths::gpgui(),
api_key,
minimized: false,
envs: None,
+1
View File
@@ -1,4 +1,5 @@
pub(crate) mod command_traits;
mod desktop_session_env;
pub(crate) mod gui_helper_launcher;
pub mod auth_launcher;
+2 -2
View File
@@ -4,7 +4,7 @@ use std::{
process::{ExitStatus, Stdio},
};
use common::constants::GP_SERVICE_BINARY;
use common::binary_paths;
use tokio::process::Command;
use super::command_traits::CommandExt;
@@ -26,7 +26,7 @@ impl Default for ServiceLauncher<'_> {
impl<'a> ServiceLauncher<'a> {
pub fn new() -> Self {
Self {
program: GP_SERVICE_BINARY.into(),
program: binary_paths::gpservice(),
minimized: false,
env_file: None,
log_file: None,
+85 -8
View File
@@ -3,12 +3,18 @@ use std::env;
use anyhow::bail;
use uzers::User;
#[derive(Debug, PartialEq, Eq)]
enum RealUserLookup {
Uid(u32),
Name(String),
}
pub fn get_user_by_name(username: &str) -> anyhow::Result<User> {
uzers::get_user_by_name(username).ok_or_else(|| anyhow::anyhow!("User ({}) not found", username))
}
pub fn get_non_root_user() -> anyhow::Result<User> {
let current_user = whoami::username();
let current_user = current_username()?;
let user = if current_user == "root" {
get_real_user()?
@@ -24,16 +30,87 @@ pub fn get_non_root_user() -> anyhow::Result<User> {
}
pub fn get_current_user() -> anyhow::Result<User> {
let current_user = whoami::username();
let current_user = current_username()?;
get_user_by_name(&current_user)
}
fn current_username() -> anyhow::Result<String> {
whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))
}
fn get_real_user() -> anyhow::Result<User> {
// Read the UID from SUDO_UID or PKEXEC_UID environment variable if available.
let uid = match env::var("SUDO_UID") {
Ok(uid) => uid.parse::<u32>()?,
_ => env::var("PKEXEC_UID")?.parse::<u32>()?,
};
match real_user_lookup(|key| env::var(key).ok())? {
RealUserLookup::Uid(uid) => uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found")),
RealUserLookup::Name(name) => get_user_by_name(&name),
}
}
fn real_user_lookup(env_var: impl Fn(&str) -> Option<String>) -> anyhow::Result<RealUserLookup> {
if let Some(uid) = env_var("SUDO_UID") {
return Ok(RealUserLookup::Uid(uid.parse::<u32>()?));
}
if let Some(uid) = env_var("PKEXEC_UID") {
return Ok(RealUserLookup::Uid(uid.parse::<u32>()?));
}
if let Some(user) = env_var("DOAS_USER").filter(|user| !user.trim().is_empty()) {
return Ok(RealUserLookup::Name(user));
}
bail!("User not found")
}
#[cfg(test)]
mod tests {
use super::*;
fn lookup(vars: &[(&str, &str)]) -> anyhow::Result<RealUserLookup> {
real_user_lookup(|key| {
vars
.iter()
.find(|(name, _)| *name == key)
.map(|(_, value)| value.to_string())
})
}
#[test]
fn real_user_lookup_uses_sudo_uid() {
assert_eq!(lookup(&[("SUDO_UID", "1000")]).unwrap(), RealUserLookup::Uid(1000));
}
#[test]
fn real_user_lookup_uses_pkexec_uid() {
assert_eq!(lookup(&[("PKEXEC_UID", "1001")]).unwrap(), RealUserLookup::Uid(1001));
}
#[test]
fn real_user_lookup_uses_doas_user() {
assert_eq!(
lookup(&[("DOAS_USER", "alice")]).unwrap(),
RealUserLookup::Name("alice".to_string())
);
}
#[test]
fn real_user_lookup_prefers_uid_over_doas_user() {
assert_eq!(
lookup(&[("SUDO_UID", "1000"), ("PKEXEC_UID", "1001"), ("DOAS_USER", "alice")]).unwrap(),
RealUserLookup::Uid(1000)
);
assert_eq!(
lookup(&[("PKEXEC_UID", "1001"), ("DOAS_USER", "alice")]).unwrap(),
RealUserLookup::Uid(1001)
);
}
#[test]
fn real_user_lookup_ignores_blank_doas_user() {
assert!(lookup(&[("DOAS_USER", " ")]).is_err());
}
uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found"))
#[test]
fn real_user_lookup_errors_without_root_origin_env() {
assert!(lookup(&[]).is_err());
}
}
+43 -18
View File
@@ -3,7 +3,10 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::{gateway::Gateway, gp_params::ClientOs};
use crate::{
gateway::Gateway,
os_profile::{ClientOs, OsProfile},
};
use super::vpn_state::ConnectInfo;
@@ -36,6 +39,7 @@ pub struct ConnectArgs {
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
host_id: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
@@ -65,6 +69,7 @@ impl ConnectArgs {
os: None,
os_version: None,
client_version: None,
host_id: None,
certificate: None,
sslkey: None,
key_password: None,
@@ -110,6 +115,10 @@ impl ConnectArgs {
self.client_version.clone()
}
pub fn host_id(&self) -> Option<String> {
self.host_id.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
@@ -201,23 +210,12 @@ impl ConnectRequest {
self
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.args.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.args.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.args.os_version = os_version.into();
self
}
pub fn with_client_version(mut self, client_version: &str) -> Self {
self.args.client_version = Some(client_version.to_string());
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
self.args.os = Some(profile.client_os());
self.args.os_version = Some(profile.os_version().to_string());
self.args.client_version = Some(profile.client_version().to_string());
self.args.host_id = Some(profile.host_identity().host_id().to_string());
self.args.user_agent = Some(profile.user_agent().to_string());
self
}
@@ -314,6 +312,12 @@ mod tests {
use serde_json::json;
use super::*;
use crate::os_profile::OsProfileBuilder;
fn test_connect_info() -> ConnectInfo {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
}
#[test]
fn connect_request_serializes_allow_extend_session() {
@@ -324,4 +328,25 @@ mod tests {
assert_eq!(value["args"]["allowExtendSession"], json!(true));
}
#[test]
fn with_os_profile_sets_user_agent_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
}
#[test]
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
assert_eq!(
req.args().host_id(),
Some(profile.host_identity().host_id().to_string())
);
}
}
+15 -1
View File
@@ -1,6 +1,17 @@
use serde::{Deserialize, Serialize};
use crate::service::vpn_state::VpnState;
use crate::{os_profile::HostIdentity, service::vpn_state::VpnState};
/// The single DTO carrying all host facts gpservice ships to gpgui.
///
/// Populated by gpservice at WS connection time and sent inside `VpnEnv`.
/// gpgui stores it in a process-wide `OnceLock` and routes `AppSettings`,
/// `Constants`, and `OsProfile` construction through it.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HostInfo {
/// Host identity collected by gpservice for the runtime OS.
pub host_identity: HostIdentity,
}
/// Represents the VPN environment configuration.
/// When a client connects, the gpservice sends the current VPN environment
@@ -19,4 +30,7 @@ pub struct VpnEnv {
/// The gpauth executable path
/// Used by the client to launch gpauth for authentication
pub auth_executable: String,
/// Host identity collected by gpservice.
pub host_info: HostInfo,
}
+7 -35
View File
@@ -4,8 +4,6 @@ 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,
@@ -16,9 +14,6 @@ pub struct SessionWarning {
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>,
@@ -30,9 +25,6 @@ impl SessionRequestArgs {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
@@ -45,21 +37,6 @@ impl SessionRequestArgs {
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
@@ -88,18 +65,6 @@ impl SessionRequestArgs {
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()
}
@@ -299,4 +264,11 @@ mod tests {
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
#[test]
fn with_user_agent_sets_session_user_agent() {
let args = SessionRequestArgs::new("cookie".to_string()).with_user_agent("agent/1.0".to_string());
assert_eq!(args.user_agent(), Some("agent/1.0".to_string()));
}
}
-108
View File
@@ -1,108 +0,0 @@
use std::sync::OnceLock;
const DEFAULT_MACOS_VERSION: &str = "13.4.0";
#[cfg(not(target_os = "linux"))]
const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS";
#[cfg(not(target_os = "windows"))]
const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro";
const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0";
const DEFAULT_MACHINE_ID: &str = "DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF";
static MACHINE_ID: OnceLock<&'static str> = OnceLock::new();
static MACOS_VERSION: OnceLock<&'static str> = OnceLock::new();
static MACOS_OS_STRING: OnceLock<String> = OnceLock::new();
static LINUX_OS_STRING: OnceLock<String> = OnceLock::new();
static WINDOWS_VERSION: OnceLock<&'static str> = OnceLock::new();
static WINDOWS_OS_STRING: OnceLock<String> = OnceLock::new();
/// On macOS, get the OS version, or fallback to default
/// On other OSes, always return default
pub fn get_macos_version() -> &'static str {
MACOS_VERSION.get_or_init(|| {
#[cfg(target_os = "macos")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_MACOS_VERSION,
v => v.to_string().leak(),
}
}
#[cfg(not(target_os = "macos"))]
DEFAULT_MACOS_VERSION
})
}
pub fn get_macos_os_string() -> &'static str {
MACOS_OS_STRING.get_or_init(|| format!("Apple Mac OS X {}", get_macos_version()))
}
/// On Linux, use the real distro name if possible
/// On other OSes, fallback to default
pub fn get_linux_os_string() -> &'static str {
LINUX_OS_STRING.get_or_init(|| {
#[cfg(target_os = "linux")]
{
format!("Linux {}", whoami::distro())
}
#[cfg(not(target_os = "linux"))]
{
format!("Linux {}", DEFAULT_LINUX_DISTRO)
}
})
}
/// On Windows, get the OS version, or fallback to default
/// On other OSes, always return default
pub fn get_windows_version() -> &'static str {
WINDOWS_VERSION.get_or_init(|| {
#[cfg(target_os = "windows")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION,
v => format!("{}.0", v).leak(),
}
}
#[cfg(not(target_os = "windows"))]
DEFAULT_WINDOWS_VERSION
})
}
/// On Windows, use the real edition if possible
/// On other OSes, fallback to default
/// The trailing space is intentional
pub fn get_windows_os_string() -> &'static str {
WINDOWS_OS_STRING.get_or_init(|| {
#[cfg(target_os = "windows")]
{
let edition = os_info::get()
.edition()
.map(|e| e.to_string())
.unwrap_or_else(|| whoami::distro());
format!("Microsoft {} , 64-bit", edition)
}
#[cfg(not(target_os = "windows"))]
{
format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO)
}
})
}
/// Get machine ID or fallback to default
pub fn get_machine_id() -> &'static str {
MACHINE_ID.get_or_init(|| {
machine_uid::get()
.map(|id| id.to_string().leak() as &'static str)
.unwrap_or(DEFAULT_MACHINE_ID)
})
}
/// Generate a UUID v5 based on machine ID and provided seeds
pub fn derive_uuid(seeds: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", get_machine_id(), seeds.join("-"));
let uuid = Uuid::new_v5(&namespace, name.as_bytes());
uuid.hyphenated().to_string()
}
-1
View File
@@ -5,7 +5,6 @@ pub mod checksum;
pub mod crypto;
pub mod endpoint;
pub mod env_utils;
pub mod host_utils;
pub mod lock_file;
pub mod openssl;
pub mod redact;
+54
View File
@@ -123,6 +123,46 @@ pub fn redact_uri(uri: &str) -> 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> {
let query = query?;
@@ -190,6 +230,20 @@ mod tests {
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]
fn it_should_redact_data_uri() {
let uri = "data:text/plain;a";
+31 -8
View File
@@ -24,26 +24,49 @@ mod unix {
use anyhow::bail;
use gtk::{
EventBox,
glib::Cast,
glib::{self, Cast},
traits::{EventBoxExt, GtkWindowExt, WidgetExt},
};
use log::info;
use tauri::WebviewWindow;
use tokio::process::Command;
/// Wrapper to mark a non-Send closure as Send for dispatch to the GTK main thread.
///
/// SAFETY: The caller must ensure the closure is only executed on the GTK main
/// thread. This is guaranteed by `glib::MainContext::default().invoke()`.
struct SendFn(Box<dyn FnOnce()>);
unsafe impl Send for SendFn {}
impl SendFn {
fn invoke(self) {
(self.0)();
}
}
pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland {
let gtk_win = win.gtk_window()?;
if let Some(header) = gtk_win.titlebar() {
let _ = header.downcast::<EventBox>().map(|event_box| {
event_box.set_above_child(false);
});
}
gtk_win.hide();
gtk_win.show_all();
// GTK operations must run on the main thread. When this function is called
// from a background thread (e.g., rspc handler on a tokio worker), calling
// GTK widget methods directly causes crashes in GTK's CSS subsystem
// (gtk_css_value_inherit_free assertion failure). Dispatch to the main
// thread via glib::MainContext to ensure thread safety.
let send_fn = SendFn(Box::new(move || {
if let Some(header) = gtk_win.titlebar() {
let _ = header.downcast::<EventBox>().map(|event_box| {
event_box.set_above_child(false);
});
}
gtk_win.hide();
gtk_win.show_all();
}));
glib::MainContext::default().invoke(move || send_fn.invoke());
} else {
if !win.is_visible()? {
win.show()?;
+4 -4
View File
@@ -46,10 +46,10 @@ impl ElementExt for Element {
}
for child in &self.children {
if let Some(element) = child.as_element() {
if let Some(found) = element.descendant(name) {
return Some(found);
}
if let Some(element) = child.as_element()
&& let Some(found) = element.descendant(name)
{
return Some(found);
}
}
+13
View File
@@ -143,6 +143,13 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
config.env("LIBS", "-liconv");
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
{
config.ldflag("-L/usr/local/lib");
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
let dst = config.build();
let lib_dir = dst.join("lib");
@@ -190,6 +197,12 @@ fn main() {
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
{
println!("cargo:rustc-link-search=native=/usr/local/lib");
println!("cargo:rustc-link-lib=iconv");
}
// Prevent silent fallback to dynamic libraries
#[cfg(target_os = "linux")]
{
@@ -0,0 +1,101 @@
From 78078b21f53801b31fef352ec0de40d319edcae9 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sat, 13 Jun 2026 12:00:00 +0800
Subject: [PATCH 6/6] Add host ID to GlobalProtect HIP script arguments
---
gpst.c | 4 ++++
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 3 +++
4 files changed, 26 insertions(+)
diff --git a/gpst.c b/gpst.c
index 78c16d1c..f1e1f6bb 100644
--- a/gpst.c
+++ b/gpst.c
@@ -1019,6 +1019,10 @@ static int run_hip_script(struct openconnect_info *vpninfo)
hip_argv[i++] = "--client-os";
hip_argv[i++] = gpst_os_name(vpninfo);
hip_argv[i++] = "--os-version";
hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
+ if (openconnect_get_gp_host_id(vpninfo)) {
+ hip_argv[i++] = "--host-id";
+ hip_argv[i++] = openconnect_get_gp_host_id(vpninfo);
+ }
hip_argv[i++] = "--cookie";
hip_argv[i++] = vpninfo->cookie;
if (vpninfo->ip_info.addr) {
diff --git a/library.c b/library.c
index 03f47004..9e585119 100644
--- a/library.c
+++ b/library.c
@@ -900,6 +900,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->useragent);
free(vpninfo->gp_app_version);
free(vpninfo->gp_os_version);
+ free(vpninfo->gp_host_id);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1049,6 +1050,20 @@ const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
return vpninfo->gp_os_version ?: vpninfo->platname;
}
+int openconnect_set_gp_host_id(struct openconnect_info *vpninfo,
+ const char *gp_host_id)
+{
+ UTF8CHECK(gp_host_id);
+
+ STRDUP(vpninfo->gp_host_id, gp_host_id);
+ return 0;
+}
+
+const char *openconnect_get_gp_host_id(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_host_id;
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index a7e80659..76034fbd 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -788,6 +788,7 @@ struct openconnect_info {
char *version_string;
char *gp_app_version;
char *gp_os_version;
+ char *gp_host_id;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1684,6 +1685,9 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
/* Get the OS version string for GP */
const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
+/* Get the host ID string for GP */
+const char *openconnect_get_gp_host_id(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 40de2811..3c65c090 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -472,8 +472,11 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
const char *gp_app_version);
int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
const char *gp_os_version);
+int openconnect_set_gp_host_id(struct openconnect_info *vpninfo,
+ const char *gp_host_id);
+
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
+1
View File
@@ -15,6 +15,7 @@ pub(crate) struct ConnectOptions {
pub os: *const c_char,
pub os_version: *const c_char,
pub client_version: *const c_char,
pub host_id: *const c_char,
pub local_hostname: *const c_char,
pub script: *const c_char,
+5
View File
@@ -80,6 +80,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("USER_AGENT: %s", options->user_agent);
INFO("OS: %s", options->os);
INFO("CLIENT_VERSION: %s", options->client_version);
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
INFO("VPNC_SCRIPT: %s", options->script);
INFO("SCRIPT_TUN: %d", g_script_tun);
INFO("CSD_USER: %d", options->csd_uid);
@@ -120,6 +121,10 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
options->client_version);
}
if (options->host_id) {
openconnect_set_gp_host_id(vpninfo, options->host_id);
}
effective_local_hostname = options->local_hostname;
if (!effective_local_hostname && !uname(&utsbuf)) {
effective_local_hostname = utsbuf.nodename;
+1
View File
@@ -25,6 +25,7 @@ typedef struct vpn_options {
const char *os;
const char *os_version;
const char *client_version;
const char *host_id;
const char *local_hostname;
const char *script;
+45
View File
@@ -64,6 +64,7 @@ pub struct Vpn {
os: CString,
os_version: Option<CString>,
client_version: Option<CString>,
host_id: Option<CString>,
local_hostname: Option<CString>,
script: CString,
@@ -124,6 +125,7 @@ impl Vpn {
os: self.os.as_ptr(),
os_version: Self::option_to_ptr(&self.os_version),
client_version: Self::option_to_ptr(&self.client_version),
host_id: Self::option_to_ptr(&self.host_id),
local_hostname: Self::option_to_ptr(&self.local_hostname),
script: self.script.as_ptr(),
@@ -185,6 +187,7 @@ pub struct VpnBuilder {
os: Option<String>,
os_version: Option<String>,
client_version: Option<String>,
host_id: Option<String>,
local_hostname: Option<String>,
certificate: Option<String>,
@@ -217,6 +220,7 @@ impl VpnBuilder {
os: None,
os_version: None,
client_version: None,
host_id: None,
local_hostname: None,
certificate: None,
@@ -271,6 +275,11 @@ impl VpnBuilder {
self
}
pub fn host_id<T: Into<Option<String>>>(mut self, host_id: T) -> Self {
self.host_id = host_id.into();
self
}
pub fn local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self {
self.local_hostname = local_hostname.into();
self
@@ -378,6 +387,7 @@ impl VpnBuilder {
os: Self::to_cstring(&os),
os_version: self.os_version.as_deref().map(Self::to_cstring),
client_version: self.client_version.as_deref().map(Self::to_cstring),
host_id: self.host_id.as_deref().map(Self::to_cstring),
local_hostname: self.local_hostname.as_deref().map(Self::to_cstring),
script: Self::to_cstring(&script),
@@ -453,4 +463,39 @@ mod tests {
assert_eq!(info.lifetime_secs, None);
assert_eq!(info.lifetime_warning, None);
}
#[test]
fn connect_options_include_host_id() {
let vpn = Vpn {
server: CString::new("gateway.example.com").unwrap(),
cookie: CString::new("cookie").unwrap(),
user_agent: CString::new("agent").unwrap(),
os: CString::new("linux").unwrap(),
os_version: None,
client_version: None,
host_id: Some(CString::new("profile-host-id").unwrap()),
local_hostname: None,
script: CString::new("/bin/true").unwrap(),
interface: None,
script_tun: false,
certificate: None,
sslkey: None,
key_password: None,
servercert: None,
csd_uid: 0,
csd_wrapper: None,
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
no_dtls: false,
dpd_interval: 0,
no_xmlpost: false,
callback: Default::default(),
};
let options = vpn.build_connect_options();
let host_id = unsafe { CStr::from_ptr(options.host_id) }.to_str().unwrap();
assert_eq!(host_id, "profile-host-id");
}
}
+4 -2
View File
@@ -3,6 +3,7 @@ use std::{io, path::Path};
use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/vpnc-script",
"/usr/libexec/gpclient/vpnc-script",
"/usr/lib/gpclient/vpnc-script",
"/usr/local/share/vpnc-scripts/vpnc-script",
@@ -19,6 +20,7 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
@@ -44,11 +46,11 @@ fn find_executable(locations: &[&'static str]) -> 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> {
find_executable(&CSD_WRAPPER_LOCATIONS)
find_executable(CSD_WRAPPER_LOCATIONS)
}
/// If file exists, check if it is executable
+254 -49
View File
@@ -21,6 +21,7 @@
inherit system;
overlays = [ (import rust-overlay) ];
};
inherit (pkgs) lib;
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
pname = "globalprotect-openconnect";
@@ -35,46 +36,94 @@
src = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/globalprotect-openconnect-${version}.tar.gz";
hash = "sha256-MUkZSXaIFJJK8wD1jI8wk79TkB6tGa1bwBKdGhjQ/p4=";
hash = "sha256-Ejvb//r6tE6yMwNwUJq5Z0r57K0IHKFN1YVaXnvpGIs=";
};
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
gpguiHashes = {
x86_64 = "sha256-jLMErGlfbzhRk8onqqiRXOMeNhdFWBZGOqPPEh9vLyM=";
aarch64 = "sha256-YSjn2oxDaKTtdfK7rsmuMZfD9n1bitVbScIW0fyedXI=";
};
gpgui = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/gpgui_${cpu}.bin.tar.xz";
hash = {
x86_64 = "sha256-t21j1bPq8QrQh7tN6epCk9VASGKrdHBB7vMXsHK2Pqk=";
aarch64 = "sha256-jA8Zpev56iNJrbxYM1t1zRor+lX4kHxuSrzuwntWlwA=";
}.${cpu};
hash = gpguiHashes.${cpu};
};
in
{
# For `nix build`
packages.default = naersk'.buildPackage {
binaryHashes = {
x86_64 = "sha256-atZRM7v5areQTDkrJrOczSz0tc3P6aGU+BE4VblNE08=";
aarch64 = "sha256-ENE0fHlLSt493QIlotaIMf11MszJszl4ZZAsYWuFJeE=";
};
binaryPackage = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/globalprotect-openconnect_${version}_${cpu}.bin.tar.xz";
hash = binaryHashes.${cpu};
};
linuxRuntimeDependencies = with pkgs; [
glib-networking
libayatana-appindicator
];
linuxBuildInputs =
with pkgs;
[
libxml2
zlib
lz4
gnutls
p11-kit
nettle
gmp
]
++ lib.optionals stdenv.isLinux [
glib
gtk3
libsoup_3
webkitgtk_4_1
glib-networking
openssl
libsecret
libayatana-appindicator
];
rewriteSourceInstallPaths = ''
substituteInPlace $out/share/applications/gpgui.desktop \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
substituteInPlace $out/libexec/gpclient/hipreport.sh \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice
if [ -f $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down ]; then
substituteInPlace $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
fi
'';
rewriteHostInstallPaths = ''
substituteInPlace $out/share/applications/gpgui.desktop \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice
if [ -f $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down ]; then
substituteInPlace $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
fi
'';
fromSource = naersk'.buildPackage {
inherit pname version src;
# Must be set to true to avoid issues with the Tauri build process
singleStep = true;
buildInputs =
with pkgs;
[
libxml2
zlib
lz4
gnutls
p11-kit
nettle
gmp
]
++ lib.optionals stdenv.isLinux [
glib
gtk3
libsoup_3
webkitgtk_4_1
glib-networking
openssl
];
buildInputs = linuxBuildInputs;
nativeBuildInputs =
with pkgs;
@@ -89,13 +138,7 @@
wrapGAppsHook4
];
runtimeDependencies =
with pkgs;
[ ]
++ lib.optionals stdenv.isLinux [
libappindicator-gtk3
glib-networking
];
runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies;
overrideMain =
{ ... }:
@@ -124,23 +167,185 @@
cp -r packaging/files/usr/lib $out/lib
cp -r packaging/files/usr/libexec $out/libexec
# Change the `/usr/bin/gpclient` path in the desktop file
substituteInPlace $out/share/applications/gpgui.desktop \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
substituteInPlace $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
substituteInPlace $out/libexec/gpclient/hipreport.sh \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
# Change the `/usr/bin/gpservice` path in the polkit policy file
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice
${rewriteSourceInstallPaths}
'';
};
prebuiltFiles = pkgs.stdenv.mkDerivation {
inherit pname version;
src = binaryPackage;
dontBuild = true;
nativeBuildInputs = with pkgs; [
autoPatchelfHook
wrapGAppsHook4
];
buildInputs = linuxBuildInputs;
runtimeDependencies = linuxRuntimeDependencies;
installPhase = ''
runHook preInstall
mkdir -p $out
cp -r artifacts/usr/bin $out/bin
cp -r artifacts/usr/libexec $out/libexec
cp -r artifacts/usr/share $out/share
if [ -d artifacts/usr/lib ]; then
cp -r artifacts/usr/lib $out/lib
fi
runHook postInstall
'';
};
prebuiltCommand =
binaryName:
pkgs.buildFHSEnv {
name = binaryName;
targetPkgs =
pkgs:
[ prebuiltFiles ]
++ linuxBuildInputs
++ linuxRuntimeDependencies;
runScript = "/usr/bin/${binaryName}";
profile = ''
export PATH=/run/wrappers/bin:$PATH
'';
extraBwrapArgs = [
"--bind-try"
"/run/wrappers"
"/run/wrappers"
];
};
prebuiltCommands = {
gpclient = prebuiltCommand "gpclient";
gpservice = prebuiltCommand "gpservice";
gpauth = prebuiltCommand "gpauth";
gpgui = prebuiltCommand "gpgui";
gpgui-helper = prebuiltCommand "gpgui-helper";
};
prebuilt = pkgs.stdenv.mkDerivation {
inherit pname version;
dontUnpack = true;
installPhase = ''
runHook preInstall
mkdir -p $out/bin
cat > $out/bin/gpclient <<'EOF'
#!${pkgs.runtimeShell}
set -eu
gpclient_fhs='${prebuiltCommands.gpclient}/bin/gpclient'
gpservice_public='@gpservice_public@'
if [ "''${1:-}" = "launch-gui" ]; then
shift
auth_data=
minimized=
for arg in "$@"; do
case "$arg" in
--minimized)
minimized=--minimized
;;
--*)
;;
*)
auth_data=$arg
;;
esac
done
if [ -z "$auth_data" ]; then
if [ -n "''${XDG_DATA_HOME:-}" ]; then
data_home=$XDG_DATA_HOME
elif [ -n "''${HOME:-}" ]; then
data_home=$HOME/.local/share
else
data_home=/tmp
fi
log_dir="$data_home/gpclient"
mkdir -p "$log_dir"
log_file="$log_dir/gpclient.log"
env_file=$(mktemp)
env > "$env_file"
printf 'GP_LOG_FILE=%s\n' "$log_file" >> "$env_file"
pkexec_bin=/run/wrappers/bin/pkexec
if [ ! -x "$pkexec_bin" ]; then
pkexec_bin=pkexec
fi
set +e
if [ -n "$minimized" ]; then
"$pkexec_bin" --user root "$gpservice_public" --minimized --env-file "$env_file" 2>"$log_file"
else
"$pkexec_bin" --user root "$gpservice_public" --env-file "$env_file" 2>"$log_file"
fi
status=$?
set -e
rm -f "$env_file"
exit "$status"
fi
set -- launch-gui "$@"
fi
exec "$gpclient_fhs" "$@"
EOF
substituteInPlace $out/bin/gpclient \
--replace-fail '@gpservice_public@' "$out/bin/gpservice"
chmod +x $out/bin/gpclient
cat > $out/bin/gpservice <<'EOF'
#!${pkgs.runtimeShell}
set -eu
exec '@gpservice_fhs@' "$@"
EOF
substituteInPlace $out/bin/gpservice \
--replace-fail '@gpservice_fhs@' '${prebuiltCommands.gpservice}/bin/gpservice'
chmod +x $out/bin/gpservice
ln -s ${prebuiltCommands.gpauth}/bin/gpauth $out/bin/gpauth
ln -s ${prebuiltCommands.gpgui}/bin/gpgui $out/bin/gpgui
ln -s ${prebuiltCommands."gpgui-helper"}/bin/gpgui-helper $out/bin/gpgui-helper
cp -r ${prebuiltFiles}/libexec $out/libexec
cp -r ${prebuiltFiles}/share $out/share
if [ -d ${prebuiltFiles}/lib ]; then
cp -r ${prebuiltFiles}/lib $out/lib
fi
${rewriteHostInstallPaths}
runHook postInstall
'';
};
in
{
# For `nix build`
packages =
{
fromSource = fromSource;
}
// lib.optionalAttrs pkgs.stdenv.isLinux {
default = prebuilt;
prebuilt = prebuilt;
}
// lib.optionalAttrs (!pkgs.stdenv.isLinux) {
default = fromSource;
};
apps.default = {
type = "app";
program = "${self.packages.${system}.default}/bin/gpclient";
+75
View File
@@ -0,0 +1,75 @@
# 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}" \
BUILD_WEBVIEW_AUTH="${BUILD_WEBVIEW_AUTH:-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
"
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN" "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
<vendor>The GlobalProtect-openconnect Project</vendor>
<vendor_url>https://github.com/yuezk/GlobalProtect-openconnect</vendor_url>
<icon_name>gpgui</icon_name>
<action id="com.yuezk.gpgui.service">
<description>Run GPService as root</description>
<message>Authentication is required to run the GPService as root</message>
<defaults>
<allow_any>auth_admin</allow_any>
<allow_inactive>auth_admin</allow_inactive>
<allow_active>yes</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.exec.path">/usr/local/bin/gpservice</annotate>
<annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>
</action>
</policyconfig>
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more