Compare commits

..
99 changed files with 3329 additions and 9780 deletions

No files matched your search

+9 -299
View File
@@ -10,16 +10,6 @@ on:
description: 'gpgui branch to use for the snapshot release' description: 'gpgui branch to use for the snapshot release'
required: true required: true
default: dev 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: push:
paths-ignore: paths-ignore:
- LICENSE - LICENSE
@@ -130,7 +120,6 @@ jobs:
if-no-files-found: error if-no-files-found: error
build-gp: build-gp:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
needs: needs:
- tarball - tarball
strategy: strategy:
@@ -154,17 +143,19 @@ jobs:
with: with:
name: artifact-source name: artifact-source
path: build-gp-${{ matrix.package }} 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 - name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros # LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: | run: |
docker run --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \ -e LIBXML2_STATIC=1 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \ -v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 yuezk/gpdev:${{ matrix.package }}-builder-tauri2
- name: Install ${{ matrix.package }} package in Docker - name: Install ${{ matrix.package }} package in Docker
run: | run: |
docker run --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_INSTALLED=0 \ -e GPGUI_INSTALLED=0 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \ -v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
@@ -181,7 +172,6 @@ jobs:
build-gp-${{ matrix.package }}/artifacts/* build-gp-${{ matrix.package }}/artifacts/*
build-docker-image: build-docker-image:
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -282,16 +272,18 @@ jobs:
run: | run: |
cd gpgui-source cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp 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 - name: Build gpgui in Docker
run: | run: |
docker run --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }} -v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
- name: Install gpgui in Docker - name: Install gpgui in Docker
run: | run: |
cd gpgui-source cd gpgui-source
tar -xJf *.bin.tar.xz tar -xJf *.bin.tar.xz
docker run --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \ -v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version" bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
@@ -304,278 +296,17 @@ jobs:
gpgui-source/*.bin.tar.xz gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256 gpgui-source/*.bin.tar.xz.sha256
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: gh-release:
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }} if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
needs: needs:
- tarball - tarball
- tarball-offline - tarball-offline
- build-gp - build-gp
- build-docker-image - build-docker-image
- build-gpgui - build-gpgui
- setup-bsd-matrix
- build-gpgui-frontend
- build-bsd
steps: 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 - name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release run: rm -rf gh-release && mkdir gh-release
@@ -604,27 +335,6 @@ jobs:
mv "$file" "${file%.apk}-aarch64.apk" mv "$file" "${file%.apk}-aarch64.apk"
done 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 - name: Create GH release
env: env:
GH_TOKEN: ${{ secrets.GH_PAT }} GH_TOKEN: ${{ secrets.GH_PAT }}
+1 -2
View File
@@ -129,7 +129,6 @@ jobs:
cp -v packaging/deb/postrm .build/debian/postrm cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules 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 # Update the control file with the correct Rust version
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control
@@ -137,7 +136,7 @@ jobs:
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
- name: Publish to PPA - name: Publish to PPA
uses: yuezk/publish-ppa-package@main uses: yuezk/publish-ppa-package@gp
with: with:
repository: "yuezk/globalprotect-openconnect" repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }} gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
+6 -48
View File
@@ -116,10 +116,12 @@ jobs:
--pattern '*[^offline].tar.gz' \ --pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }} --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 - name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros # LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: | run: |
docker run --rm \ docker run --pull=always --rm \
-v $(pwd)/build-${{ matrix.package }}:/workspace \ -v $(pwd)/build-${{ matrix.package }}:/workspace \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \ -e LIBXML2_STATIC=1 \
@@ -128,7 +130,7 @@ jobs:
- name: Install ${{ matrix.package }} package in Docker - name: Install ${{ matrix.package }} package in Docker
run: | run: |
docker run --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/build-${{ matrix.package }}:/workspace \ -v $(pwd)/build-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \ yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
@@ -251,34 +253,13 @@ jobs:
- build - build
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ inputs.gh-release }} if: ${{ inputs.gh-release }}
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
steps: steps:
- name: Prepare workspace - name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release 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 - name: Download artifact
uses: actions/download-artifact@v8 uses: actions/download-artifact@v8
with: with:
path: gh-release 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 - name: Rename APK artifacts
run: | run: |
shopt -s nullglob shopt -s nullglob
@@ -289,29 +270,6 @@ jobs:
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk" mv "$file" "${file%.apk}-aarch64.apk"
done 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 - name: Update release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
with: with:
@@ -319,5 +277,5 @@ jobs:
prerelease: ${{ contains(github.ref, 'snapshot') }} prerelease: ${{ contains(github.ref, 'snapshot') }}
fail_on_unmatched_files: true fail_on_unmatched_files: true
tag_name: ${{ inputs.tag }} tag_name: ${{ inputs.tag }}
body_path: ${{ steps.release-notes.outputs.path }} files: |
files: ${{ steps.release-assets.outputs.files }} gh-release/artifact-*/*
+36 -87
View File
@@ -6,9 +6,9 @@ on:
version: version:
description: "Release version. Defaults to Cargo.toml workspace version." description: "Release version. Defaults to Cargo.toml workspace version."
required: false required: false
release_tag: release:
description: "GitHub release tag to fetch assets from. Defaults to v<version>; use snapshot for snapshot assets." types:
required: false - published
permissions: permissions:
contents: write contents: write
@@ -26,95 +26,44 @@ jobs:
- name: Update flake hashes - name: Update flake hashes
env: env:
RELEASE_VERSION: ${{ inputs.version }} RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: | run: |
if [[ -n "$RELEASE_VERSION" ]]; then if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION" "$RELEASE_TAG" scripts/update-flake-hashes.sh "$RELEASE_VERSION"
else else
scripts/update-flake-hashes.sh "" "$RELEASE_TAG" scripts/update-flake-hashes.sh
fi 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 - name: Open pull request
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ inputs.version }} RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }} run: |
run: scripts/open-flake-hashes-pr.sh "$RELEASE_VERSION" "$RELEASE_TAG" 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
Generated
+526 -555
View File
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package] [workspace.package]
rust-version = "1.89" rust-version = "1.89"
version = "2.6.3" version = "2.5.4"
authors = ["Kevin Yue <[email protected]>"] authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect" homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024" edition = "2024"
@@ -19,7 +19,7 @@ license = "GPL-3.0"
[workspace.dependencies] [workspace.dependencies]
anyhow = "1.0" anyhow = "1.0"
askama = "0.16" askama = "0.14"
base64 = "0.22" base64 = "0.22"
chrono = "0.4" chrono = "0.4"
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
@@ -31,10 +31,10 @@ env_logger = "0.11"
is_executable = "1.0" is_executable = "1.0"
log = "0.4" log = "0.4"
regex = "1" regex = "1"
reqwest = { version = "0.13", features = ["native-tls", "json", "form", "query"] } reqwest = { version = "0.12", features = ["native-tls", "json"] }
openssl = "0.10" openssl = "0.10"
pem = "3" pem = "3"
xmltree = { version = "0.12", features = ["attribute-order"] } xmltree = "0.12"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
# Use 0.36 as newer versions requires Rust 1.88+ # Use 0.36 as newer versions requires Rust 1.88+
@@ -48,7 +48,7 @@ axum = "0.8"
futures = "0.3" futures = "0.3"
futures-util = "0.3" futures-util = "0.3"
uzers = "0.12" uzers = "0.12"
whoami = "2" whoami = "1"
thiserror = "2" thiserror = "2"
redact-engine = "0.1" redact-engine = "0.1"
compile-time = "0.2" compile-time = "0.2"
@@ -58,12 +58,12 @@ sha256 = "1"
which = "8" which = "8"
uuid = "1" uuid = "1"
netdev = "0.40" netdev = "0.40"
machine-uid = "0.5"
humantime = "2" humantime = "2"
# Tauri dependencies # Tauri dependencies
tauri = { version = "2" } tauri = { version = "2" }
specta = "=2.0.0-rc.20" specta = "=2.0.0-rc.20"
proptest = "1"
[profile.release] [profile.release]
opt-level = 'z' # Optimize for size opt-level = 'z' # Optimize for size
+4 -115
View File
@@ -1,5 +1,4 @@
SHELL := /bin/sh .SHELLFLAGS += -e
.SHELLFLAGS := -ec
INCLUDE_GUI ?= 0 INCLUDE_GUI ?= 0
CARGO ?= cargo CARGO ?= cargo
@@ -31,12 +30,6 @@ PUBLISH ?= 0
# Indicates whether to build the GUI components # Indicates whether to build the GUI components
BUILD_GUI_HELPER ?= 1 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 DEBEMAIL = [email protected]
export DEBFULLNAME = Kevin Yue export DEBFULLNAME = Kevin Yue
export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false") export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false")
@@ -116,18 +109,11 @@ build-rs:
rm -vf rust-toolchain.toml; \ rm -vf rust-toolchain.toml; \
fi 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 # Only build the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \ if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper; \ $(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; \
fi fi
clean: clean:
@@ -166,98 +152,6 @@ 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/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 -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: uninstall:
@echo "Uninstalling $(PKG_NAME)..." @echo "Uninstalling $(PKG_NAME)..."
@@ -303,15 +197,10 @@ init-debian: clean-debian tarball
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \ sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libayatana-appindicator3-1/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; \ 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; \ sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
fi fi
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules 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 sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
rm -f .build/deb/$(PKG)/debian/changelog rm -f .build/deb/$(PKG)/debian/changelog
+42 -41
View File
@@ -81,8 +81,6 @@ gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-
``` ```
**Browser Options:** **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 <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 - Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
@@ -214,53 +212,56 @@ sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
This repository includes a flake for NixOS integration. This repository includes a flake for NixOS integration.
If you want a quick user-level install, you can install it directly from the flake:
```bash
nix profile add github:yuezk/GlobalProtect-openconnect
```
If you want it managed as part of your NixOS system configuration, use the steps below.
#### Installation Steps #### Installation Steps
Add the flake input and package to your `flake.nix`: 1. Add the flake to your `flake.nix`:
```nix ```nix
{ {
inputs = { inputs = {
# ... other inputs # ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect"; 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
];
}
];
}; };
};
}
```
Apply: outputs = { nixpkgs, ... }@inputs: {
nixosConfigurations.<your-host> = nixpkgs.lib.nixosSystem {
specialArgs = { inherit inputs; };
modules = [
./configuration.nix
];
};
};
}
```
```bash 2. Add the package to your `configuration.nix`:
sudo nixos-rebuild switch
loginctl terminate-user "$USER"
```
After logging back in to GNOME, enable AppIndicator support if needed: ```nix
{ config, pkgs, inputs, ... }:
```bash {
gnome-extensions enable [email protected] # ... other configurations
``` environment.systemPackages = with pkgs; [
# ... other packages
] ++ [
inputs.globalprotect-openconnect.packages.${pkgs.stdenv.hostPlatform.system}.default
];
}
```
3. Apply the changes:
```bash
sudo nixos-rebuild switch
```
### Official Docker Image ### Official Docker Image
+20 -140
View File
@@ -1,10 +1,10 @@
use auth::{BrowserAuthenticator, auth_prelogin}; use auth::{BrowserAuthenticator, auth_prelogin};
use clap::Parser; use clap::Parser;
use common::constants::GP_USER_AGENT;
use gpapi::{ use gpapi::{
auth::{SamlAuthData, SamlAuthResult}, auth::{SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error}, clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
gp_params::GpParams, gp_params::{ClientOs, GpParams},
os_profile::{ClientOs, OsProfile},
utils::{normalize_server, openssl}, utils::{normalize_server, openssl},
}; };
use log::info; use log::info;
@@ -48,27 +48,14 @@ struct Cli {
#[arg(long, help = "The SAML authentication request")] #[arg(long, help = "The SAML authentication request")]
saml_request: Option<String>, saml_request: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())] #[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
os: Os, os: Os,
#[arg(long, help = "Use this runtime host ID when building the OS profile")] #[arg(long)]
host_id: Option<String>, os_version: 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")] #[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
fix_openssl: bool, fix_openssl: bool,
@@ -82,8 +69,8 @@ struct Cli {
#[arg( #[arg(
long, long,
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser.", help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable",
default_missing_value = "auto", default_missing_value = "default",
num_args=0..=1 num_args=0..=1
)] )]
browser: Option<String>, browser: Option<String>,
@@ -134,14 +121,10 @@ impl Cli {
let server = normalize_server(&self.server)?; let server = normalize_server(&self.server)?;
let gp_params = self.build_gp_params(); 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() { let auth_request = match self.saml_request.as_deref() {
Some(auth_request) => auth_request.to_string(), Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await?, None => auth_prelogin(&server, &gp_params).await?,
}; };
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
@@ -154,11 +137,10 @@ impl Cli {
let browser = self.browser.as_deref().or(Some("default")); let browser = self.browser.as_deref().or(Some("default"));
if let Some(browser) = browser { 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 authenticator = BrowserAuthenticator::new(&auth_request, browser);
let auth_result = authenticator.authenticate().await; let auth_result = authenticator.authenticate().await;
print_auth_result(auth_result, Some(&auth_host_id)); print_auth_result(auth_result);
// explicitly drop openssl_conf to avoid the unused variable warning // explicitly drop openssl_conf to avoid the unused variable warning
drop(openssl_conf); drop(openssl_conf);
@@ -172,36 +154,15 @@ impl Cli {
} }
fn build_gp_params(&self) -> GpParams { fn build_gp_params(&self) -> GpParams {
GpParams::builder(self.build_os_profile()) let gp_params = GpParams::builder()
.user_agent(&self.user_agent)
.client_os(ClientOs::from(&self.os))
.os_version(self.os_version.clone())
.ignore_tls_errors(self.ignore_tls_errors) .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) .is_gateway(self.gateway)
.build() .build();
}
fn build_os_profile(&self) -> OsProfile { gp_params
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
}
} }
} }
@@ -223,92 +184,11 @@ pub async fn run() {
} }
} }
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) { pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>) {
let auth_result = match auth_result { let auth_result = match auth_result {
Ok(auth_data) => { Ok(auth_data) => SamlAuthResult::Success(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)), Err(err) => SamlAuthResult::Failure(format!("{}", err)),
}; };
println!("{}", json!(auth_result)); 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"));
}
}
+1 -4
View File
@@ -13,8 +13,6 @@ pub async fn authenticate(
clean: bool, clean: bool,
mut openssl_conf: Option<NamedTempFile>, mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
tauri::Builder::default() tauri::Builder::default()
.setup(move |app| { .setup(move |app| {
let app_handle = app.handle().clone(); let app_handle = app.handle().clone();
@@ -22,11 +20,10 @@ pub async fn authenticate(
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let authenticator = WebviewAuthenticator::new(&server, &gp_params) let authenticator = WebviewAuthenticator::new(&server, &gp_params)
.with_auth_request(&auth_request) .with_auth_request(&auth_request)
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
.with_clean(clean); .with_clean(clean);
let auth_result = authenticator.authenticate(&app_handle).await; let auth_result = authenticator.authenticate(&app_handle).await;
print_auth_result(auth_result, Some(&auth_host_id)); print_auth_result(auth_result);
// Ensure the app exits after the authentication process // Ensure the app exits after the authentication process
app_handle.exit(0); app_handle.exit(0);
-2
View File
@@ -20,7 +20,6 @@ inquire = "0.9"
log.workspace = true log.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] } tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true sysinfo.workspace = true
serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
serde_urlencoded.workspace = true serde_urlencoded.workspace = true
whoami.workspace = true whoami.workspace = true
@@ -30,7 +29,6 @@ directories.workspace = true
compile-time.workspace = true compile-time.workspace = true
netdev.workspace = true netdev.workspace = true
xmltree.workspace = true xmltree.workspace = true
uuid = { workspace = true, features = ["v5"] }
[features] [features]
default = ["webview-auth"] default = ["webview-auth"]
+847
View File
@@ -0,0 +1,847 @@
use std::{
borrow::Cow,
cell::RefCell,
fs,
str::FromStr,
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, GatewayLoginContext, GatewaySelection, SessionExtensionAuth, gateway_login,
gateway_login_with_context,
},
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(Default)]
struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
fn new(requested: bool) -> Self {
Self { requested }
}
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
if !webview_auth || !self.requested {
return false;
}
self.requested = false;
true
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CscPreferenceArg {
domain: String,
key: String,
value: String,
}
impl FromStr for CscPreferenceArg {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let (name, value) = input
.split_once('=')
.ok_or_else(|| "expected <domain>:<key>=<value>".to_string())?;
let (domain, key) = name
.split_once(':')
.ok_or_else(|| "expected <domain>:<key>=<value>".to_string())?;
if domain.is_empty() || key.is_empty() || value.is_empty() {
return Err("domain, key, and value must be non-empty".to_string());
}
Ok(Self {
domain: domain.to_string(),
key: key.to_string(),
value: value.to_string(),
})
}
}
#[derive(Args)]
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 = "csc-preference",
help = "Override a Mac CSC plist preference value, in the form <domain>:<key>=<value>",
value_name = "DOMAIN:KEY=VALUE"
)]
csc_preferences: Vec<CscPreferenceArg>,
#[arg(
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,
#[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>>,
clean_auth_state: RefCell<CleanAuthState>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self {
args,
shared_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 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);
}
for preference in &self.args.csc_preferences {
builder.csc_preference_override(&preference.domain, &preference.key, &preference.value);
}
builder.build()
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
#[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, None)
.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, 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).await?;
let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
let gateway_selection = if self.args.gateway.is_some() {
GatewaySelection::Manual
} else {
GatewaySelection::Auto
};
let selected_gateway = match &self.args.gateway {
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 client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let gateway_context = GatewayLoginContext::new(selected_gateway, gateway_selection)
.with_connect_method(portal_config.connect_method())
.with_client_version(client_version);
let login_session = match self
.login_gateway(gateway, &cred, &gp_params, Some(&gateway_context))
.await
{
Ok(login_session) => login_session,
Err(err) => {
info!("Gateway login failed: {}", err);
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,
Some(gateway_context),
)
.await;
}
};
// Use the client version from the command line argument if specified, otherwise
// use the version from the portal config if available
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,
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 prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let login_session = self
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.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,
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,
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 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 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()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_csc_preference_override() {
let preference = CscPreferenceArg::from_str("com.example.settings:ExampleKey=ExampleValue").unwrap();
assert_eq!(
preference,
CscPreferenceArg {
domain: "com.example.settings".to_string(),
key: "ExampleKey".to_string(),
value: "ExampleValue".to_string(),
}
);
}
#[test]
fn rejects_invalid_csc_preference_override() {
assert!(CscPreferenceArg::from_str("com.example.settings:ExampleKey").is_err());
assert!(CscPreferenceArg::from_str("com.example.settings=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str(":ExampleKey=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str("com.example.settings:=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str("com.example.settings:ExampleKey=").is_err());
}
#[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));
}
}
-401
View File
@@ -1,401 +0,0 @@
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
@@ -1,271 +0,0 @@
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));
}
}
-532
View File
@@ -1,532 +0,0 @@
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};
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
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);
let disconnect_requested = Arc::new(AtomicBool::new(false));
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
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()))?;
}
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
}
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,
disconnect_requested: bool,
) -> Result<(), GatewayConnectError> {
if exit_code == 0 {
return Ok(());
}
if disconnect_requested && exit_code == OPENCONNECT_INTERRUPTED_EXIT_CODE {
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, false).is_ok());
assert!(classify_openconnect_result(0, true, false).is_ok());
}
#[test]
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
let err = classify_openconnect_result(1, false, 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, false).expect_err("nonzero exit should fail");
assert!(!err.is_before_tunnel());
}
#[test]
fn interrupted_exit_after_requested_disconnect_is_success() {
assert!(classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, true).is_ok());
}
#[test]
fn interrupted_exit_without_requested_disconnect_is_failure() {
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
.expect_err("unexpected interrupt 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
@@ -1,314 +0,0 @@
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));
}
}
+136 -342
View File
@@ -1,13 +1,8 @@
use askama::Template; use askama::Template;
use clap::Args; use clap::Args;
use gpapi::{ use gpapi::{clap::args::Os, utils::host_utils};
clap::args::Os,
os_profile::{ClientOs, OsProfile, OsProfileBuilder},
};
use log::debug; use log::debug;
use serde::Deserialize;
use std::collections::HashMap; use std::collections::HashMap;
use std::process::Command;
use xmltree::Element; use xmltree::Element;
#[derive(Template)] #[derive(Template)]
@@ -19,45 +14,27 @@ struct HipReportTemplate<'a> {
month: String, month: String,
year: String, year: String,
user_name: &'a str, user_name: &'a str,
host_info: HostInfo, host_info: HostInfo<'a>,
md5: &'a str, 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 /// Host information for HIP reporting
struct HostInfo { struct HostInfo<'a> {
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux" /// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
os_vendor: String, os_vendor: &'a str,
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc. /// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
os_version: String, os_version: &'a str,
/// Per-OS machine identifier (UUID for Linux/Windows, MAC for macOS) /// Only for macOS and Windows
host_id: String, host_id: String,
/// Common for all OSes /// Common for all OSes
host_name: String, host_name: String,
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130" /// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
software_version: String, software_version: &'a str,
domain: String, domain: String,
network_interfaces: Vec<NetworkInterface>, network_interfaces: Vec<NetworkInterface>,
defender: Option<DefenderInfo>,
} }
impl HostInfo { impl<'a> HostInfo<'a> {
/// Get the first available IPv4 address from network interfaces /// Get the first available IPv4 address from network interfaces
pub fn default_ipv4(&self) -> &str { pub fn default_ipv4(&self) -> &str {
self self
@@ -126,11 +103,8 @@ pub(crate) struct HipArgs {
#[arg(long, value_enum, help = "The client OS")] #[arg(long, value_enum, help = "The client OS")]
client_os: Os, client_os: Os,
#[arg(long, hide = true)] #[arg(long, help = "The OS version string, e.g., Apple Mac OS X 10.15.7")]
os_version: Option<String>, os_version: String,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "The authentication cookie")] #[arg(long, help = "The authentication cookie")]
cookie: String, cookie: String,
@@ -147,13 +121,11 @@ pub(crate) struct HipArgs {
pub(crate) struct HipHandler<'a> { pub(crate) struct HipHandler<'a> {
args: &'a HipArgs, args: &'a HipArgs,
profile: OsProfile,
} }
impl<'a> HipHandler<'a> { impl<'a> HipHandler<'a> {
pub(crate) fn new(args: &'a HipArgs) -> Self { pub(crate) fn new(args: &'a HipArgs) -> Self {
let profile = build_os_profile(args); Self { args }
Self { args, profile }
} }
pub(crate) async fn handle(&self) -> anyhow::Result<()> { pub(crate) async fn handle(&self) -> anyhow::Result<()> {
@@ -192,57 +164,34 @@ impl<'a> HipHandler<'a> {
format_xml(&report) format_xml(&report)
} }
/// Collect host information using the configured OsProfile. /// Collect host information based on the client OS
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo { fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo<'a> {
HostInfoCollector::new(&self.profile, self.args, cookie_params).collect() let collector = HostInfoCollector::new(self.args, cookie_params);
}
}
/// Construct an `OsProfile` from CLI args, falling back to per-OS defaults match self.args.client_os {
/// for any value not supplied on the command line. Os::Linux => collector.collect_linux(),
fn build_os_profile(args: &HipArgs) -> OsProfile { Os::Mac => collector.collect_macos(),
let client_os = ClientOs::from(args.client_os); Os::Windows => collector.collect_windows(),
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 // Host Information Collector
// ============================================================================ // ============================================================================
/// Helper struct for collecting host information. /// Helper struct for collecting host information
/// struct HostInfoCollector<'a> {
/// 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, args: &'a HipArgs,
cookie_params: &'a HashMap<String, String>, cookie_params: &'a HashMap<String, String>,
} }
impl<'p, 'a> HostInfoCollector<'p, 'a> { impl<'a> HostInfoCollector<'a> {
fn new(profile: &'p OsProfile, args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self { fn new(args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
Self { Self { args, cookie_params }
profile,
args,
cookie_params,
}
} }
/// Domain belongs to the runtime user/session, not the simulated OS, so /// Get domain from cookie parameters
/// it is sourced from the auth cookie when available.
fn get_domain(&self) -> String { fn get_domain(&self) -> String {
self self
.cookie_params .cookie_params
@@ -268,128 +217,125 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
} }
} }
/// Single entry point for collecting host info — dispatches per-OS /// Collect Linux-specific host information
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`. fn collect_linux(&self) -> HostInfo<'a> {
fn collect(&self) -> HostInfo { let iface = self.collect_network_interface();
let runtime_iface = self.collect_network_interface();
let primary = self.adapt_primary_interface(&runtime_iface);
let mut interfaces = vec![primary.clone()]; // Use the fixed interface name enp1s0f0 for Linux if it is not on Linux
interfaces.extend(self.extra_interfaces(&primary)); let iface = NetworkInterface {
#[cfg(target_os = "linux")]
name: iface.name,
#[cfg(target_os = "linux")]
description: iface.description,
HostInfo { #[cfg(not(target_os = "linux"))]
os_vendor: self.profile.os_vendor().to_string(), name: "enp1s0f0".to_string(),
os_version: self.profile.os_version().to_string(), #[cfg(not(target_os = "linux"))]
host_id: self.profile.host_id().to_string(), description: "enp1s0f0".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(),
}
}
/// Build the primary network interface with OS-appropriate naming and mac_address: iface.mac_address,
/// MAC formatting. When emulating a different OS, the runtime interface ipv4: iface.ipv4,
/// name/description are replaced with the canonical placeholder for the ipv6: iface.ipv6,
/// 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)
}; };
NetworkInterface { HostInfo {
name, os_vendor: "Linux",
description, os_version: &self.args.os_version,
mac_address: format_mac_for(self.profile, runtime.mac_address.clone()), host_id: host_utils::derive_uuid(&[]),
ipv4: runtime.ipv4.clone(), host_name: whoami::devicename(),
ipv6: runtime.ipv6.clone(), software_version: "",
domain: String::new(),
network_interfaces: vec![iface],
} }
} }
/// Additional interfaces appended after the primary. Only Windows /// Collect macOS-specific host information
/// emits the software loopback interface in HIP reports. fn collect_macos(&self) -> HostInfo<'a> {
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> { let iface = self.collect_network_interface();
match self.profile.client_os() { // macOS use the mac address as host ID
ClientOs::Windows => vec![NetworkInterface { let host_id = iface
name: derive_windows_network_name(self.profile.host_id(), primary), .mac_address
description: "Software Loopback Interface 1".to_string(), .as_ref()
mac_address: Some(String::new()), .map(|s| s.to_string())
ipv4: Some("127.0.0.1".to_string()), .unwrap_or_else(|| "00:00:00:00:00:00".to_string());
ipv6: Some("::1".to_string()),
}], // Use the fixed interface name en0 for macOS if it is not on macOS
ClientOs::Linux | ClientOs::Mac => vec![], 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,
};
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],
} }
} }
/// Linux HIP reports omit the domain field; macOS/Windows include it /// Collect Windows-specific host information
/// from the auth cookie. fn collect_windows(&self) -> HostInfo<'a> {
fn domain_for_profile(&self) -> String { // Use the actual machine ID on Windows
match self.profile.client_os() { #[cfg(target_os = "windows")]
ClientOs::Linux => String::new(), let host_id = host_utils::get_machine_id().to_string();
ClientOs::Mac | ClientOs::Windows => self.get_domain(), #[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,
} }
} }
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,
}
} }
// ============================================================================ // ============================================================================
@@ -418,163 +364,11 @@ fn format_xml(xml_str: &str) -> anyhow::Result<String> {
Ok(String::from_utf8(xml_buf)?) Ok(String::from_utf8(xml_buf)?)
} }
fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> String { fn derive_windows_network_name(iface: &NetworkInterface) -> String {
let seed = format!( let seeds = [
"{}-{}-{}",
host_id,
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"), iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
iface.name iface.name.as_str(),
); ];
format!( format!("{{{}}}", host_utils::derive_uuid(&seeds).to_uppercase())
"{{{}}}",
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<()> { pub(crate) async fn handle(&self) -> anyhow::Result<()> {
// `launch-gui`cannot be run as root // `launch-gui`cannot be run as root
let user = whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))?; let user = whoami::username();
if user == "root" { if user == "root" {
anyhow::bail!("`launch-gui` cannot be run as root"); anyhow::bail!("`launch-gui` cannot be run as root");
} }
+21 -14
View File
@@ -1,8 +1,9 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{ use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session}, gateway::{SessionContext, SessionExtensionAuth, extend_session},
os_profile::OsProfile, gp_params::ClientOs,
session::{SessionInfo, SessionRequestArgs, SessionWarning}, session::{SessionInfo, SessionRequestArgs, SessionWarning},
}; };
use log::{info, warn}; use log::{info, warn};
@@ -20,7 +21,10 @@ pub(crate) struct SessionContextInput {
pub(crate) portal: String, pub(crate) portal: String,
pub(crate) gateway: String, pub(crate) gateway: String,
pub(crate) cookie: String, pub(crate) cookie: String,
pub(crate) os_profile: OsProfile, pub(crate) user_agent: String,
pub(crate) os: ClientOs,
pub(crate) os_version: String,
pub(crate) client_version: Option<String>,
pub(crate) certificate: Option<String>, pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>, pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>, pub(crate) key_password: Option<String>,
@@ -30,7 +34,12 @@ pub(crate) struct SessionContextInput {
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext { pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie) let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(input.os_profile.user_agent().to_string()) .with_user_agent(Some(input.user_agent))
.with_os(Some(input.os))
.with_os_version(Some(input.os_version))
.with_client_version(Some(
input.client_version.unwrap_or_else(|| GP_CLIENT_VERSION.to_string()),
))
.with_certificate(input.certificate) .with_certificate(input.certificate)
.with_sslkey(input.sslkey) .with_sslkey(input.sslkey)
.with_key_password(input.key_password) .with_key_password(input.key_password)
@@ -172,17 +181,15 @@ mod tests {
} }
#[test] #[test]
fn builds_session_context_from_os_profile() { fn builds_session_context_from_cli_runtime_values() {
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 { let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(), portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(), gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(), cookie: "authcookie=AUTH".to_string(),
os_profile: profile, user_agent: "UA".to_string(),
os: ClientOs::Mac,
os_version: "macOS 15.0".to_string(),
client_version: Some("6.3.1-12".to_string()),
certificate: Some("/tmp/client.pem".to_string()), certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()), sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()), key_password: Some("secret".to_string()),
@@ -193,10 +200,10 @@ mod tests {
assert_eq!(ctx.portal(), "portal.example.com"); assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com"); assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH"); assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!( assert_eq!(ctx.session_args().user_agent().as_deref(), Some("UA"));
ctx.session_args().user_agent().as_deref(), assert!(matches!(ctx.session_args().os(), Some(ClientOs::Mac)));
Some(expected_user_agent.as_str()) assert_eq!(ctx.session_args().os_version().as_deref(), Some("macOS 15.0"));
); assert_eq!(ctx.session_args().client_version().as_deref(), Some("6.3.1-12"));
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem")); assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key")); assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret")); assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
-13
View File
@@ -218,20 +218,7 @@
</entry> </entry>
{% elif host_info.os_vendor == "Linux" -%} {% elif host_info.os_vendor == "Linux" -%}
<entry name="anti-malware"> <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/> <list/>
{% endif -%}
</entry> </entry>
<entry name="disk-backup"> <entry name="disk-backup">
<list/> <list/>
+12 -12
View File
@@ -11,27 +11,27 @@
"dependencies": { "dependencies": {
"@emotion/react": "^11.14.0", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1", "@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.11", "@mui/icons-material": "^7.3.10",
"@mui/material": "^7.3.11", "@mui/material": "^7.3.10",
"@tauri-apps/api": "^2.11.1", "@tauri-apps/api": "^2.11.0",
"react": "^19.2.7", "react": "^19.2.5",
"react-dom": "^19.2.7" "react-dom": "^19.2.5"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.11.2", "@tauri-apps/cli": "^2.11.1",
"@types/node": "^25.9.4", "@types/node": "^25.6.0",
"@types/react": "^19.2.17", "@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.61.1", "@typescript-eslint/eslint-plugin": "^8.59.2",
"@typescript-eslint/parser": "^8.61.1", "@typescript-eslint/parser": "^8.59.2",
"@vitejs/plugin-react": "^6.0.2", "@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4", "eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.8.3", "prettier": "3.8.3",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"vite": "^8.0.16" "vite": "^8.0.10"
}, },
"packageManager": "[email protected]" "packageManager": "[email protected]"
} }
+548 -569
View File
File diff suppressed because it is too large. Load diff
+8 -7
View File
@@ -3,6 +3,7 @@ use std::{
io::BufReader, io::BufReader,
ops::ControlFlow, ops::ControlFlow,
os::unix::fs::PermissionsExt, os::unix::fs::PermissionsExt,
path::PathBuf,
sync::Arc, sync::Arc,
}; };
@@ -16,7 +17,7 @@ use axum::{
http::StatusCode, http::StatusCode,
response::IntoResponse, response::IntoResponse,
}; };
use common::binary_paths; use common::constants::GP_GUI_BINARY;
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};
use gpapi::{ use gpapi::{
service::{event::WsEvent, request::UpdateGuiRequest}, service::{event::WsEvent, request::UpdateGuiRequest},
@@ -66,8 +67,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 // Unpack GPGUI archive, gpgui_2.0.0_{arch}.bin.tar.xz and install it
async fn install_gui(src: &str) -> anyhow::Result<()> { async fn install_gui(src: &str) -> anyhow::Result<()> {
let target = binary_paths::gpgui(); let path = PathBuf::from(GP_GUI_BINARY);
let Some(dir) = target.parent() else { let Some(dir) = path.parent() else {
bail!("Failed to get parent directory of GUI binary"); bail!("Failed to get parent directory of GUI binary");
}; };
@@ -80,13 +81,13 @@ async fn install_gui(src: &str) -> anyhow::Result<()> {
for entry in ar.entries()? { for entry in ar.entries()? {
let mut entry = entry?; let mut entry = entry?;
let entry_path = entry.path()?; let path = entry.path()?;
if let Some(name) = entry_path.file_name() { if let Some(name) = path.file_name() {
let name = name.to_string_lossy(); let name = name.to_string_lossy();
if name == "gpgui" { if name == "gpgui" {
let mut file = File::create(&target)?; let mut file = File::create(GP_GUI_BINARY)?;
std::io::copy(&mut entry, &mut file)?; std::io::copy(&mut entry, &mut file)?;
break; break;
} }
@@ -94,7 +95,7 @@ async fn install_gui(src: &str) -> anyhow::Result<()> {
} }
// Make the binary executable // Make the binary executable
fs::set_permissions(target, Permissions::from_mode(0o755)).await?; fs::set_permissions(GP_GUI_BINARY, Permissions::from_mode(0o755)).await?;
Ok(()) Ok(())
} }
-1
View File
@@ -46,7 +46,6 @@ impl VpnTaskContext {
.os(args.openconnect_os()) .os(args.openconnect_os())
.os_version(args.os_version()) .os_version(args.os_version())
.client_version(args.client_version()) .client_version(args.client_version())
.host_id(args.host_id())
.certificate(args.certificate()) .certificate(args.certificate())
.sslkey(args.sslkey()) .sslkey(args.sslkey())
.key_password(args.key_password()) .key_password(args.key_password())
+3 -14
View File
@@ -1,15 +1,9 @@
use std::sync::Arc; use std::sync::Arc;
use axum::extract::ws::Message; use axum::extract::ws::Message;
use common::binary_paths; use common::constants::GP_AUTH_BINARY;
use gpapi::{ use gpapi::{
os_profile::HostIdentity, service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpn_state::VpnState},
service::{
event::WsEvent,
request::WsRequest,
vpn_env::{HostInfo, VpnEnv},
vpn_state::VpnState,
},
utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction}, utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction},
}; };
use log::{info, warn}; use log::{info, warn};
@@ -65,16 +59,11 @@ impl WsServerContext {
// Send current VPN state to new client // Send current VPN state to new client
info!("Sending current environment to new client"); info!("Sending current environment to new client");
let host_info = HostInfo {
host_identity: HostIdentity::collect(),
};
let vpn_env = VpnEnv { let vpn_env = VpnEnv {
vpn_state: self.vpn_state_rx.borrow().clone(), vpn_state: self.vpn_state_rx.borrow().clone(),
vpnc_script: find_vpnc_script().map(|s| s.to_owned()), vpnc_script: find_vpnc_script().map(|s| s.to_owned()),
csd_wrapper: find_csd_wrapper().map(|s| s.to_owned()), csd_wrapper: find_csd_wrapper().map(|s| s.to_owned()),
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(), auth_executable: GP_AUTH_BINARY.to_owned(),
host_info,
}; };
if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await { if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await {
-61
View File
@@ -1,66 +1,5 @@
# Changelog # Changelog
## 2.6.3
### Fixed
- Fixed NixOS GUI launch authorization after package updates.
- Fixed disconnect handling so a normal Ctrl+C logout no longer reports an error.
- Fixed snapshot flake hash update automation for prebuilt Nix packages.
## 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 ## 2.5.4 - 2026-05-08
- Add Alpine/musl gpgui release assets for x86_64 and aarch64. - Add Alpine/musl gpgui release assets for x86_64 and aarch64.
+1 -1
View File
@@ -29,7 +29,7 @@ regex = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true } tokio-util = { workspace = true, optional = true }
html-escape = { version = "0.2.13", optional = true } html-escape = { version = "0.2.13", optional = true }
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies] [target.'cfg(not(target_os = "macos"))'.dependencies]
webkit2gtk = { version = "2", optional = true } webkit2gtk = { version = "2", optional = true }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
+1 -5
View File
@@ -1,7 +1,7 @@
use std::io::Cursor; use std::io::Cursor;
use log::info; use log::info;
use tiny_http::{Header, Method, Response, Server}; use tiny_http::{Header, Response, Server};
use uuid::Uuid; use uuid::Uuid;
pub(super) struct AuthServer { pub(super) struct AuthServer {
@@ -30,10 +30,6 @@ impl AuthServer {
if req.url() != format!("/{}", self.auth_id) { if req.url() != format!("/{}", self.auth_id) {
let forbidden = Response::from_string("forbidden").with_status_code(403); let forbidden = Response::from_string("forbidden").with_status_code(403);
let _ = req.respond(forbidden); 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 { } else {
let auth_response = build_auth_response(auth_request); let auth_response = build_auth_response(auth_request);
if let Err(err) = req.respond(auth_response) { if let Err(err) = req.respond(auth_response) {
+9 -38
View File
@@ -11,7 +11,6 @@ use tokio::{
use crate::browser::auth_server::AuthServer; use crate::browser::auth_server::AuthServer;
pub enum Browser<'a> { pub enum Browser<'a> {
Auto,
Default, Default,
Chrome, Chrome,
Firefox, Firefox,
@@ -22,7 +21,6 @@ pub enum Browser<'a> {
impl<'a> Browser<'a> { impl<'a> Browser<'a> {
pub fn from_str(browser: &'a str) -> Self { pub fn from_str(browser: &'a str) -> Self {
match browser.to_lowercase().as_str() { match browser.to_lowercase().as_str() {
"auto" => Browser::Auto,
"default" => Browser::Default, "default" => Browser::Default,
"chrome" => Browser::Chrome, "chrome" => Browser::Chrome,
"firefox" => Browser::Firefox, "firefox" => Browser::Firefox,
@@ -33,7 +31,6 @@ impl<'a> Browser<'a> {
fn as_str(&self) -> &str { fn as_str(&self) -> &str {
match self { match self {
Browser::Auto => "auto",
Browser::Default => "default", Browser::Default => "default",
Browser::Chrome => "chrome", Browser::Chrome => "chrome",
Browser::Firefox => "firefox", Browser::Firefox => "firefox",
@@ -90,15 +87,6 @@ Note that the URL is only valid for a single use.
info!("Launching the default browser..."); info!("Launching the default browser...");
webbrowser::open(&auth_url)?; 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); let app = find_browser_path(&self.browser);
@@ -136,25 +124,19 @@ async fn detect_local_ip() -> anyhow::Result<String> {
fn find_browser_path(browser: &Browser) -> String { fn find_browser_path(browser: &Browser) -> String {
match browser { match browser {
Browser::Chrome => find_chrome_path().unwrap_or_else(|| browser.as_str().to_string()), 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.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> { async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// Start a local server to receive the browser authentication data // Start a local server to receive the browser authentication data
let listener = TcpListener::bind("127.0.0.1:0").await?; let listener = TcpListener::bind("127.0.0.1:0").await?;
@@ -194,14 +176,3 @@ fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
let auth_data = SamlAuthData::from_gpcallback(data.trim())?; let auth_data = SamlAuthData::from_gpcallback(data.trim())?;
Ok(auth_data) 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));
}
}
+3 -11
View File
@@ -1,7 +1,7 @@
use anyhow::bail; use anyhow::bail;
use gpapi::{ use gpapi::{
gp_params::GpParams, gp_params::GpParams,
portal::{Prelogin, PreloginOptions, prelogin}, portal::{Prelogin, prelogin},
}; };
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
@@ -15,16 +15,8 @@ mod webview;
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
pub use webview::*; pub use webview::*;
pub async fn auth_prelogin( pub async fn auth_prelogin(server: &str, gp_params: &GpParams) -> anyhow::Result<String> {
server: &str, match prelogin(server, gp_params).await? {
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::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"), Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
} }
+2 -14
View File
@@ -1,20 +1,8 @@
mod auth_messenger; mod auth_messenger;
mod webview_auth; mod webview_auth;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg_attr(not(target_os = "macos"), path = "webview/unix.rs")]
#[path = "webview/gtk.rs"] #[cfg_attr(target_os = "macos", path = "webview/macos.rs")]
mod platform_impl; 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; pub use webview_auth::WebviewAuthenticator;
+4 -4
View File
@@ -7,7 +7,7 @@ use tokio_util::sync::CancellationToken;
#[derive(Debug)] #[derive(Debug)]
pub(crate) enum AuthDataLocation { pub(crate) enum AuthDataLocation {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
Headers, Headers,
Body, Body,
} }
@@ -15,7 +15,7 @@ pub(crate) enum AuthDataLocation {
#[derive(Debug)] #[derive(Debug)]
pub(crate) enum AuthError { pub(crate) enum AuthError {
/// Failed to load page due to TLS error /// Failed to load page due to TLS error
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
TlsError, TlsError,
/// 1. Found auth data in headers/body but it's invalid /// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc. /// 2. Loaded an empty page, failed to load page. etc.
@@ -34,7 +34,7 @@ impl AuthError {
} }
} }
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
impl AuthError { impl AuthError {
pub fn not_found_in_headers() -> Self { pub fn not_found_in_headers() -> Self {
Self::NotFound(AuthDataLocation::Headers) Self::NotFound(AuthDataLocation::Headers)
@@ -155,7 +155,7 @@ impl AuthMessenger {
} }
} }
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) { pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
use log::warn; use log::warn;
+1 -25
View File
@@ -1,8 +1,7 @@
use anyhow::bail;
use block2::RcBlock; use block2::RcBlock;
use log::warn; use log::warn;
use objc2::runtime::AnyObject; use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest}; use objc2_foundation::{NSError, NSString, NSURL, NSURLRequest};
use objc2_web_kit::WKWebView; use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview; use tauri::webview::PlatformWebview;
@@ -14,29 +13,6 @@ impl PlatformWebviewExt for PlatformWebview {
Ok(()) 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<()> { fn load_url(&self, url: &str) -> anyhow::Result<()> {
unsafe { unsafe {
let wv: &WKWebView = &*self.inner().cast(); let wv: &WKWebView = &*self.inner().cast();
@@ -5,8 +5,8 @@ use gpapi::utils::redact::redact_uri;
use log::warn; use log::warn;
use tauri::webview::PlatformWebview; use tauri::webview::PlatformWebview;
use webkit2gtk::{ use webkit2gtk::{
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, WebsiteDataManagerExt,
WebsiteDataManagerExt, gio::Cancellable, glib::GString, gio::Cancellable, glib::GString,
}; };
use super::{ use super::{
@@ -33,26 +33,6 @@ impl PlatformWebviewExt for PlatformWebview {
bail!("Failed to get website data manager"); 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<()> { fn load_url(&self, url: &str) -> anyhow::Result<()> {
self.inner().load_uri(url); self.inner().load_uri(url);
Ok(()) Ok(())
+9 -203
View File
@@ -1,12 +1,7 @@
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use anyhow::bail; use anyhow::bail;
use gpapi::{ use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri};
auth::SamlAuthData,
gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::redact::redact_uri,
};
use log::{info, warn}; use log::{info, warn};
use tauri::{ use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent, AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
@@ -21,10 +16,6 @@ use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
pub trait PlatformWebviewExt { pub trait PlatformWebviewExt {
fn ignore_tls_errors(&self) -> anyhow::Result<()>; 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_url(&self, url: &str) -> anyhow::Result<()>;
fn load_html(&self, html: &str) -> anyhow::Result<()>; fn load_html(&self, html: &str) -> anyhow::Result<()>;
@@ -42,7 +33,7 @@ pub trait PlatformWebviewExt {
} }
} }
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
pub trait GetHeader { pub trait GetHeader {
fn get_header(&self, key: &str) -> Option<String>; fn get_header(&self, key: &str) -> Option<String>;
} }
@@ -51,7 +42,6 @@ pub struct WebviewAuthenticator<'a> {
server: &'a str, server: &'a str,
gp_params: &'a GpParams, gp_params: &'a GpParams,
auth_request: Option<&'a str>, auth_request: Option<&'a str>,
webview_user_agent: Option<WebviewUserAgent>,
clean: bool, clean: bool,
is_retrying: tokio::sync::RwLock<bool>, is_retrying: tokio::sync::RwLock<bool>,
@@ -63,7 +53,6 @@ impl<'a> WebviewAuthenticator<'a> {
server, server,
gp_params, gp_params,
auth_request: None, auth_request: None,
webview_user_agent: None,
clean: false, clean: false,
is_retrying: Default::default(), is_retrying: Default::default(),
} }
@@ -74,11 +63,6 @@ impl<'a> WebviewAuthenticator<'a> {
self 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 { pub fn with_clean(mut self, clean: bool) -> Self {
self.clean = clean; self.clean = clean;
self self
@@ -132,7 +116,7 @@ impl<'a> WebviewAuthenticator<'a> {
match auth_messenger.subscribe().await? { match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!("Authentication cancelled"), AuthEvent::Close => bail!("Authentication cancelled"),
AuthEvent::RaiseWindow => self.raise_window(&auth_window), AuthEvent::RaiseWindow => self.raise_window(&auth_window),
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError), AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
AuthEvent::Error(AuthError::NotFound(location)) => { AuthEvent::Error(AuthError::NotFound(location)) => {
info!( info!(
@@ -184,16 +168,15 @@ impl<'a> WebviewAuthenticator<'a> {
let auth_request = match self.auth_request { let auth_request = match self.auth_request {
Some(auth_request) => auth_request.to_string(), Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&self.server, &self.gp_params, false, false).await?, None => auth_prelogin(&self.server, &self.gp_params).await?,
}; };
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>(); let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let ignore_tls_errors = self.gp_params.ignore_tls_errors(); let ignore_tls_errors = self.gp_params.ignore_tls_errors();
let webview_user_agent = self.webview_user_agent.clone();
// Set up webview // Set up webview
auth_window.with_webview(move |wv| { auth_window.with_webview(move |wv| {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
{ {
use super::platform_impl::PlatformWebviewOnResponse; use super::platform_impl::PlatformWebviewOnResponse;
wv.on_response(Box::new(move |response| match response { wv.on_response(Box::new(move |response| match response {
@@ -207,7 +190,7 @@ impl<'a> WebviewAuthenticator<'a> {
wv.ignore_tls_errors()?; wv.ignore_tls_errors()?;
} }
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request) wv.load_auth_request(&auth_request)
}(); }();
if let Err(result) = tx.send(result) { if let Err(result) = tx.send(result) {
@@ -257,15 +240,10 @@ impl<'a> WebviewAuthenticator<'a> {
document.body.appendChild(loading); document.body.appendChild(loading);
"#)?; "#)?;
let auth_request = auth_prelogin(&self.server, &self.gp_params, false, false).await?; let auth_request = auth_prelogin(&self.server, &self.gp_params).await?;
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>(); let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let webview_user_agent = self.webview_user_agent.clone();
auth_window.with_webview(move |wv| { auth_window.with_webview(move |wv| {
let result = || -> anyhow::Result<()> { let result = 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) { if let Err(result) = tx.send(result) {
warn!("Failed to send retry auth result: {:?}", result); warn!("Failed to send retry auth result: {:?}", result);
} }
@@ -287,7 +265,7 @@ impl<'a> WebviewAuthenticator<'a> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
let result = auth_window.show(); let result = auth_window.show();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(not(target_os = "macos"))]
let result = { let result = {
use gpapi::utils::window::WindowExt; use gpapi::utils::window::WindowExt;
auth_window.raise() auth_window.raise()
@@ -298,175 +276,3 @@ 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
@@ -1,58 +0,0 @@
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"));
}
}
+6 -35
View File
@@ -1,7 +1,5 @@
pub const GP_USER_AGENT: &str = "PAN GlobalProtect"; pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619"; pub const GP_CLIENT_VERSION: &str = "6.3.0-33";
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_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port"; pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
@@ -29,43 +27,16 @@ pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))] #[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth"; 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 // Release binaries - Linux
#[cfg(all( #[cfg(all(not(debug_assertions), not(target_os = "macos")))]
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient"; pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
#[cfg(all( #[cfg(all(not(debug_assertions), not(target_os = "macos")))]
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice"; pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
#[cfg(all( #[cfg(all(not(debug_assertions), not(target_os = "macos")))]
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui"; pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(all( #[cfg(all(not(debug_assertions), not(target_os = "macos")))]
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"; pub const GP_GUI_HELPER_BINARY: &str = "/usr/bin/gpgui-helper";
#[cfg(all( #[cfg(all(not(debug_assertions), not(target_os = "macos")))]
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_AUTH_BINARY: &str = "/usr/bin/gpauth"; pub const GP_AUTH_BINARY: &str = "/usr/bin/gpauth";
// Debug binaries are set in build.rs via environment variables // Debug binaries are set in build.rs via environment variables
-1
View File
@@ -1,2 +1 @@
pub mod binary_paths;
pub mod constants; pub mod constants;
+5 -4
View File
@@ -32,11 +32,11 @@ uzers.workspace = true
serde_urlencoded.workspace = true serde_urlencoded.workspace = true
md5.workspace = true md5.workspace = true
sha256.workspace = true sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] } uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true chrono.workspace = true
humantime.workspace = true humantime.workspace = true
netdev.workspace = true netdev.workspace = true
os_info = { version = "3", default-features = false }
# Optional dependencies for features # Optional dependencies for features
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
@@ -46,13 +46,14 @@ clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true } env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", 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 # Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies] [target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = { version = "0.18", optional = true } gtk = { version = "0.18", optional = true }
[dev-dependencies]
proptest.workspace = true
[features] [features]
tauri = ["dep:tauri", "dep:gtk"] tauri = ["dep:tauri", "dep:gtk"]
clap = ["dep:clap", "dep:clap-verbosity-flag"] clap = ["dep:clap", "dep:clap-verbosity-flag"]
+2 -56
View File
@@ -9,7 +9,7 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>; pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SamlAuthData { pub struct SamlAuthData {
#[serde(alias = "un")] #[serde(alias = "un")]
@@ -17,11 +17,9 @@ pub struct SamlAuthData {
prelogin_cookie: Option<String>, prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>, portal_userauthcookie: Option<String>,
token: Option<String>, token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
host_id: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum SamlAuthResult { pub enum SamlAuthResult {
Success(SamlAuthData), Success(SamlAuthData),
@@ -35,13 +33,6 @@ impl SamlAuthResult {
SamlAuthResult::Failure(_) => false, 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 { impl SamlAuthData {
@@ -71,16 +62,9 @@ impl SamlAuthData {
prelogin_cookie: Some(prelogin_cookie), prelogin_cookie: Some(prelogin_cookie),
portal_userauthcookie: Some(portal_userauthcookie), portal_userauthcookie: Some(portal_userauthcookie),
token: None, 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 { pub fn from_html(html: &str) -> AuthDataParseResult {
match parse_xml_tag(html, "saml-auth-status") { match parse_xml_tag(html, "saml-auth-status") {
Some(status) if status == "1" => { Some(status) if status == "1" => {
@@ -151,10 +135,6 @@ impl SamlAuthData {
self.token.as_deref() self.token.as_deref()
} }
pub fn host_id(&self) -> Option<&str> {
self.host_id.as_deref()
}
fn log_summary(&self, source: &str) { fn log_summary(&self, source: &str) {
info!( info!(
"Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}", "Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}",
@@ -212,38 +192,4 @@ mod tests {
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie")); assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie")); 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());
}
} }
+37 -38
View File
@@ -1,22 +1,37 @@
use clap::{ValueEnum, builder::PossibleValue}; use clap::{ValueEnum, builder::PossibleValue};
use crate::{ use crate::gp_params::ClientOs;
gp_params::CscMode,
os_profile::{ClientOs, runtime_client_os},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] #[derive(Debug, Clone)]
pub enum Os { pub enum Os {
#[value(name = "Linux")]
Linux, Linux,
#[value(name = "Windows")]
Windows, Windows,
#[value(name = "Mac")]
Mac, Mac,
} }
impl From<Os> for ClientOs { impl Os {
fn from(value: Os) -> Self { 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 {
match value { match value {
Os::Linux => ClientOs::Linux, Os::Linux => ClientOs::Linux,
Os::Windows => ClientOs::Windows, Os::Windows => ClientOs::Windows,
@@ -25,41 +40,25 @@ impl From<Os> for ClientOs {
} }
} }
impl Default for Os { impl ValueEnum 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] { fn value_variants<'a>() -> &'a [Self] {
&[CscMode::Auto, CscMode::Yes, CscMode::No] &[Os::Linux, Os::Windows, Os::Mac]
} }
fn to_possible_value(&self) -> Option<PossibleValue> { fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
Some(PossibleValue::new(self.as_str())) match self {
Os::Linux => Some(PossibleValue::new("Linux")),
Os::Windows => Some(PossibleValue::new("Windows")),
Os::Mac => Some(PossibleValue::new("Mac")),
}
} }
fn from_str(input: &str, _: bool) -> Result<Self, String> { fn from_str(input: &str, _: bool) -> Result<Self, String> {
match input.to_lowercase().as_str() { match input.to_lowercase().as_str() {
"auto" => Ok(CscMode::Auto), "linux" => Ok(Os::Linux),
"yes" => Ok(CscMode::Yes), "windows" => Ok(Os::Windows),
"no" => Ok(CscMode::No), "mac" => Ok(Os::Mac),
_ => Err(format!("Invalid CSC mode: {}", input)), _ => Err(format!("Invalid OS: {}", input)),
} }
} }
} }
-190
View File
@@ -1,190 +0,0 @@
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());
}
}
+56 -100
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use anyhow::bail; use anyhow::bail;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
@@ -92,8 +94,6 @@ pub struct AuthCookieCredential {
username: String, username: String,
user_auth_cookie: String, user_auth_cookie: String,
prelogon_user_auth_cookie: String, prelogon_user_auth_cookie: String,
#[serde(skip)]
password: Option<String>,
} }
impl AuthCookieCredential { impl AuthCookieCredential {
@@ -102,16 +102,9 @@ impl AuthCookieCredential {
username: username.to_string(), username: username.to_string(),
user_auth_cookie: user_auth_cookie.to_string(), user_auth_cookie: user_auth_cookie.to_string(),
prelogon_user_auth_cookie: prelogon_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 { pub fn username(&self) -> &str {
&self.username &self.username
} }
@@ -123,19 +116,6 @@ impl AuthCookieCredential {
pub fn prelogon_user_auth_cookie(&self) -> &str { pub fn prelogon_user_auth_cookie(&self) -> &str {
&self.prelogon_user_auth_cookie &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)] #[derive(Debug, Serialize, Deserialize, Type, Clone)]
@@ -167,13 +147,6 @@ impl CachedCredential {
self.auth_cookie.as_ref() 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) { pub fn set_auth_cookie(&mut self, auth_cookie: AuthCookieCredential) {
self.auth_cookie = Some(auth_cookie); self.auth_cookie = Some(auth_cookie);
} }
@@ -219,20 +192,48 @@ impl Credential {
} }
} }
pub fn password(&self) -> Option<&str> { pub fn to_params(&self) -> HashMap<&str, &str> {
match self { let mut params = HashMap::new();
Credential::Password(cred) => Some(cred.password()), params.insert("user", self.username());
Credential::Cached(cred) => cred.password(),
Credential::Prelogin(_) | Credential::AuthCookie(_) => None,
}
}
pub fn can_authenticate_gateway(&self) -> bool { let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
match self { Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::AuthCookie(cred) => cred.can_authenticate_gateway(), Credential::Prelogin(cred) => (
Credential::Cached(cred) => cred.can_authenticate_gateway(), None,
Credential::Password(_) | Credential::Prelogin(_) => true, cred.prelogin_cookie(),
cred.portal_userauthcookie(),
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);
} }
params
} }
} }
@@ -278,7 +279,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn prelogin_credential_keeps_saml_cookies() { fn prelogin_credential_params_include_saml_cookies() {
let auth_data = SamlAuthData::new( let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()), Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()), Some("prelogin-cookie".to_string()),
@@ -287,72 +288,27 @@ mod tests {
.unwrap(); .unwrap();
let cred = Credential::from(auth_data); let cred = Credential::from(auth_data);
let Credential::Prelogin(prelogin) = cred else { let params = cred.to_params();
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]"); assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(prelogin.prelogin_cookie(), Some("prelogin-cookie")); assert_eq!(params.get("passwd"), Some(&""));
assert_eq!(prelogin.portal_userauthcookie(), Some("portal-userauthcookie")); assert_eq!(params.get("prelogin-cookie"), Some(&"prelogin-cookie"));
assert_eq!(prelogin.token(), None); assert_eq!(params.get("portal-userauthcookie"), Some(&"portal-userauthcookie"));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
} }
#[test] #[test]
fn prelogin_credential_keeps_cas_token_without_cookies() { fn prelogin_credential_params_keep_cas_token_without_cookies() {
let auth_data = let auth_data =
SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap(); SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap();
let cred = Credential::from(auth_data); let cred = Credential::from(auth_data);
let Credential::Prelogin(prelogin) = cred else { let params = cred.to_params();
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]"); assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(prelogin.prelogin_cookie(), None); assert_eq!(params.get("prelogin-cookie"), Some(&""));
assert_eq!(prelogin.portal_userauthcookie(), None); assert_eq!(params.get("portal-userauthcookie"), Some(&""));
assert_eq!(prelogin.token(), Some("cas-token")); assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
} assert_eq!(params.get("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
@@ -0,0 +1,173 @@
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
}
+142 -19
View File
@@ -1,4 +1,4 @@
use std::{borrow::Cow, net::UdpSocket}; use std::{borrow::Cow, collections::HashMap, net::UdpSocket};
use anyhow::bail; use anyhow::bail;
use log::{debug, info, warn}; use log::{debug, info, warn};
@@ -11,7 +11,6 @@ use crate::{
error::PortalError, error::PortalError,
gateway::GatewayLoginContext, gateway::GatewayLoginContext,
gp_params::GpParams, gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
}; };
@@ -60,27 +59,22 @@ async fn gateway_login_with_options(
.map(|ip| ip.to_string()) .map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host())) .or_else(|| detect_local_ipv4(context.host()))
}); });
let request_params = gateway_login::build(&GatewayLoginInput { let params = build_gateway_login_params(
gp_params, &gateway,
cred, cred,
gateway_host: &gateway, gp_params,
context, context,
client_ip: client_ip.as_deref(), client_ip.as_deref(),
extend_lifetime, extend_lifetime,
}); );
info!("Perform gateway login, user_agent: {}", gp_params.user_agent()); info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref(), gp_params); log_gateway_login_context(context, client_ip.as_deref());
let res = client let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
.post(&login_url) warn!("Network error: {:?}", e);
.form(&request_params.body) anyhow::anyhow!(PortalError::NetworkError(e))
.send() })?;
.await
.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res = parse_gp_response(res).await.map_err(|err| { let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}"); warn!("{err}");
@@ -111,6 +105,59 @@ async fn gateway_login_with_options(
Ok(GatewayLogin::Cookie(cookie)) Ok(GatewayLogin::Cookie(cookie))
} }
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
client_ip: Option<&str>,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
params.insert("server".to_string(), gateway.to_string());
if let Some(context) = context {
params.insert("host".to_string(), context.host().to_string());
params.insert("gw".to_string(), context.name().to_string());
params.insert("gateway-name".to_string(), context.name().to_string());
params.insert("internal".to_string(), context.kind().as_login_param().to_string());
params.insert(
"selection-type".to_string(),
context.selection().as_login_param().to_string(),
);
params.insert("client-ipv6".to_string(), String::new());
if let Some(connect_method) = context.connect_method() {
params.insert("connect-method".to_string(), connect_method.to_string());
}
if let Some(client_version) = context.client_version().or_else(|| gp_params.client_version()) {
params.insert("clientgpversion".to_string(), client_version.to_string());
}
if let Some(client_ip) = client_ip {
params.insert("client-ip".to_string(), client_ip.to_string());
}
}
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn detect_local_ipv4(host: &str) -> Option<String> { fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?; let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?; socket.connect((host, 443)).ok()?;
@@ -119,7 +166,7 @@ fn detect_local_ipv4(host: &str) -> Option<String> {
if ip.is_ipv4() { Some(ip.to_string()) } else { None } 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) { fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>) {
let Some(context) = context else { let Some(context) = context else {
return; return;
}; };
@@ -131,7 +178,7 @@ fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: O
context.connect_method().is_some(), context.connect_method().is_some(),
context.selection().as_login_param(), context.selection().as_login_param(),
context.kind().as_login_param(), context.kind().as_login_param(),
gp_params.client_version().is_some(), context.client_version().is_some(),
client_ip.is_some() client_ip.is_some()
); );
} }
@@ -222,6 +269,7 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::gateway::{Gateway, GatewayKind, GatewaySelection};
#[test] #[test]
fn mfa() { fn mfa() {
@@ -234,6 +282,81 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(input_str, "5ef64e83000119ed"); assert_eq!(input_str, "5ef64e83000119ed");
} }
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, false);
assert!(!params.contains_key("extend-lifetime"));
assert!(!params.contains_key("host"));
assert!(!params.contains_key("gw"));
assert!(!params.contains_key("gateway-name"));
assert!(!params.contains_key("connect-method"));
assert!(!params.contains_key("selection-type"));
assert!(!params.contains_key("internal"));
assert!(!params.contains_key("client-ip"));
assert!(!params.contains_key("client-ipv6"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_login_params_include_official_context_fields() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto)
.with_connect_method(Some("on-demand"))
.with_client_version(Some("6.3.3-915"));
let params = build_gateway_login_params(
"us1.vpn.example.com",
&cred,
&gp_params,
Some(&context),
Some("192.168.0.102"),
false,
);
assert_eq!(params.get("host").map(String::as_str), Some("us1.vpn.example.com"));
assert_eq!(params.get("gw").map(String::as_str), Some("US_East"));
assert_eq!(params.get("gateway-name").map(String::as_str), Some("US_East"));
assert_eq!(params.get("connect-method").map(String::as_str), Some("on-demand"));
assert_eq!(params.get("selection-type").map(String::as_str), Some("auto"));
assert_eq!(params.get("internal").map(String::as_str), Some("no"));
assert_eq!(params.get("clientgpversion").map(String::as_str), Some("6.3.3-915"));
assert_eq!(params.get("client-ip").map(String::as_str), Some("192.168.0.102"));
assert_eq!(params.get("client-ipv6").map(String::as_str), Some(""));
}
#[test]
fn manual_gateway_selection_maps_to_manual_param() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual);
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, Some(&context), None, false);
assert_eq!(params.get("selection-type").map(String::as_str), Some("manual"));
}
#[test] #[test]
fn gateway_token_keeps_upstream_cookie_fields() { fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#" let res = r#"
+12
View File
@@ -1,3 +1,4 @@
pub mod hip;
mod login; mod login;
mod parse_gateways; mod parse_gateways;
pub mod session; pub mod session;
@@ -79,6 +80,7 @@ pub struct GatewayLoginContext {
kind: GatewayKind, kind: GatewayKind,
selection: GatewaySelection, selection: GatewaySelection,
connect_method: Option<String>, connect_method: Option<String>,
client_version: Option<String>,
client_ip: Option<String>, client_ip: Option<String>,
} }
@@ -96,6 +98,7 @@ impl GatewayLoginContext {
kind: gateway.kind(), kind: gateway.kind(),
selection, selection,
connect_method: None, connect_method: None,
client_version: None,
client_ip: None, client_ip: None,
} }
} }
@@ -105,6 +108,11 @@ impl GatewayLoginContext {
self self
} }
pub fn with_client_version(mut self, client_version: Option<&str>) -> Self {
self.client_version = client_version.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_ip(mut self, client_ip: Option<String>) -> Self { pub fn with_client_ip(mut self, client_ip: Option<String>) -> Self {
self.client_ip = client_ip.filter(|s| !s.is_empty()); self.client_ip = client_ip.filter(|s| !s.is_empty());
self self
@@ -130,6 +138,10 @@ impl GatewayLoginContext {
self.connect_method.as_deref() self.connect_method.as_deref()
} }
pub(crate) fn client_version(&self) -> Option<&str> {
self.client_version.as_deref()
}
pub(crate) fn client_ip(&self) -> Option<&str> { pub(crate) fn client_ip(&self) -> Option<&str> {
self.client_ip.as_deref() self.client_ip.as_deref()
} }
+14 -27
View File
@@ -13,7 +13,7 @@ use crate::{
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime}, gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams, gp_params::GpParams,
session::SessionRequestArgs, session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt}, utils::{normalize_server, parse_gp_response, xml::ElementExt},
}; };
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension"; const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
@@ -120,19 +120,16 @@ fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
} }
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> { fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = Client::builder(); 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());
if let Some(user_agent) = args.user_agent() { Client::try_from(&builder.build())
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>> { fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
@@ -168,25 +165,15 @@ fn unix_timestamp() -> u64 {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::{gp_params::ClientOs, session::SessionRequestArgs};
os_profile::{ClientOs, HostIdentity, OsProfile},
session::SessionRequestArgs,
};
use super::*; use super::*;
fn build_session_args() -> SessionRequestArgs { 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()) SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_user_agent(profile.user_agent().to_string()) .with_os(Some(ClientOs::Mac))
.with_os_version(Some("macOS 15.0".to_string()))
.with_client_version(Some("6.3.1-12".to_string()))
.with_disable_ipv6(true) .with_disable_ipv6(true)
} }
+152 -413
View File
@@ -1,59 +1,72 @@
use std::collections::HashMap;
use common::constants::GP_USER_AGENT;
use log::info; use log::info;
use reqwest::Client; use reqwest::Client;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::{ use crate::utils::request::create_identity;
os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::create_identity,
};
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)] #[derive(Debug, Serialize, Deserialize, Clone, Type, Default)]
#[serde(rename_all = "lowercase")] pub enum ClientOs {
pub enum CscMode { #[cfg_attr(not(target_os = "macos"), default)]
#[default] Linux,
Auto, Windows,
Yes, #[cfg_attr(target_os = "macos", default)]
No, Mac,
} }
impl CscMode { impl From<&str> for ClientOs {
pub fn effective(self, client_os: ClientOs) -> bool { fn from(os: &str) -> Self {
match self { match os {
CscMode::Auto => client_os.default_csc_support(), "Linux" => ClientOs::Linux,
CscMode::Yes => true, "Windows" => ClientOs::Windows,
CscMode::No => false, "Mac" => ClientOs::Mac,
} _ => ClientOs::Linux,
}
pub fn as_str(self) -> &'static str {
match self {
CscMode::Auto => "auto",
CscMode::Yes => "yes",
CscMode::No => "no",
} }
} }
} }
#[derive(Debug, Clone)] impl ClientOs {
pub fn as_str(&self) -> &str {
match self {
ClientOs::Linux => "Linux",
ClientOs::Windows => "Windows",
ClientOs::Mac => "Mac",
}
}
pub fn to_openconnect_os(&self) -> &str {
match self {
ClientOs::Linux => "linux",
ClientOs::Windows => "win",
ClientOs::Mac => "mac-intel",
}
}
}
#[derive(Debug, Serialize, Deserialize, Type, Default, Clone)]
pub struct GpParams { pub struct GpParams {
os_profile: OsProfile, is_gateway: bool,
// Transport user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
ignore_tls_errors: bool, ignore_tls_errors: bool,
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
// Feature csc_preference_overrides: HashMap<String, String>,
csc_mode: CscMode, // Used for MFA
// Per-request state
is_gateway: bool,
input_str: Option<String>, input_str: Option<String>,
otp: Option<String>, otp: Option<String>,
} }
impl GpParams { impl GpParams {
pub fn builder(os_profile: OsProfile) -> GpParamsBuilder { pub fn builder() -> GpParamsBuilder {
GpParamsBuilder::new(os_profile) GpParamsBuilder::new()
} }
pub(crate) fn is_gateway(&self) -> bool { pub(crate) fn is_gateway(&self) -> bool {
@@ -65,63 +78,34 @@ impl GpParams {
} }
pub(crate) fn user_agent(&self) -> &str { pub(crate) fn user_agent(&self) -> &str {
self.os_profile.user_agent() &self.user_agent
}
pub(crate) fn computer(&self) -> &str {
&self.computer
} }
pub fn ignore_tls_errors(&self) -> bool { pub fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors self.ignore_tls_errors
} }
// ─── OsProfile accessor ─────────────────────────────────────────────────
pub fn os_profile(&self) -> &OsProfile {
&self.os_profile
}
// ─── Delegated identity accessors ────────────────────────────────────────
pub fn client_os(&self) -> &str { pub fn client_os(&self) -> &str {
self.os_profile.client_os().as_str() self.client_os.as_str()
}
pub(crate) fn computer(&self) -> &str {
self.os_profile.computer()
} }
pub fn os_version(&self) -> Option<&str> { pub fn os_version(&self) -> Option<&str> {
Some(self.os_profile.os_version()) self.os_version.as_deref()
} }
pub fn client_version(&self) -> Option<&str> { pub fn client_version(&self) -> Option<&str> {
Some(self.os_profile.client_version()) self.client_version.as_deref()
} }
pub(crate) fn host_id(&self) -> &str { pub fn csc_preference_override(&self, domain: &str, key: &str) -> Option<&str> {
self.os_profile.host_id() self
} .csc_preference_overrides
.get(&csc_preference_key(domain, key))
pub(crate) fn serialno(&self) -> &str { .map(String::as_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) { pub fn set_input_str(&mut self, input_str: &str) {
@@ -132,31 +116,69 @@ impl GpParams {
self.otp = Some(otp.to_string()); self.otp = Some(otp.to_string());
} }
pub(crate) fn otp(&self) -> Option<&str> { pub(crate) fn to_params(&self) -> HashMap<&str, &str> {
self.otp.as_deref() 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 struct GpParamsBuilder { pub struct GpParamsBuilder {
is_gateway: bool, is_gateway: bool,
os_profile: OsProfile, user_agent: String,
csc_mode: CscMode, client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
ignore_tls_errors: bool, ignore_tls_errors: bool,
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
} }
impl GpParamsBuilder { impl GpParamsBuilder {
pub fn new(os_profile: OsProfile) -> Self { pub fn new() -> Self {
let computer = whoami::fallible::hostname().unwrap_or_else(|_| String::from("localhost"));
Self { Self {
is_gateway: false, is_gateway: false,
os_profile, user_agent: GP_USER_AGENT.to_string(),
csc_mode: Default::default(), client_os: ClientOs::Linux,
os_version: Default::default(),
client_version: Default::default(),
computer,
ignore_tls_errors: false, ignore_tls_errors: false,
certificate: Default::default(), certificate: Default::default(),
sslkey: Default::default(), sslkey: Default::default(),
key_password: Default::default(), key_password: Default::default(),
csc_preference_overrides: Default::default(),
} }
} }
@@ -165,8 +187,28 @@ impl GpParamsBuilder {
self self
} }
pub fn csc_mode(&mut self, csc_mode: CscMode) -> &mut Self { pub fn user_agent(&mut self, user_agent: &str) -> &mut Self {
self.csc_mode = csc_mode; 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();
self self
} }
@@ -190,28 +232,49 @@ impl GpParamsBuilder {
self self
} }
pub fn csc_preference_override(&mut self, domain: &str, key: &str, value: &str) -> &mut Self {
self
.csc_preference_overrides
.insert(csc_preference_key(domain, key), value.to_string());
self
}
pub fn build(&self) -> GpParams { pub fn build(&self) -> GpParams {
GpParams { GpParams {
os_profile: self.os_profile.clone(), 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(),
ignore_tls_errors: self.ignore_tls_errors, ignore_tls_errors: self.ignore_tls_errors,
certificate: self.certificate.clone(), certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(), sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(), key_password: self.key_password.clone(),
csc_mode: self.csc_mode, csc_preference_overrides: self.csc_preference_overrides.clone(),
is_gateway: self.is_gateway,
input_str: Default::default(), input_str: Default::default(),
otp: Default::default(), otp: Default::default(),
} }
} }
} }
fn csc_preference_key(domain: &str, key: &str) -> String {
format!("{domain}:{key}")
}
impl Default for GpParamsBuilder {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<&GpParams> for Client { impl TryFrom<&GpParams> for Client {
type Error = anyhow::Error; type Error = anyhow::Error;
fn try_from(value: &GpParams) -> Result<Self, Self::Error> { fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
let mut builder = Client::builder() let mut builder = Client::builder()
.danger_accept_invalid_certs(value.ignore_tls_errors) .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() { if let Some(cert) = value.certificate.as_deref() {
info!("Using client certificate authentication..."); info!("Using client certificate authentication...");
@@ -223,327 +286,3 @@ impl TryFrom<&GpParams> for Client {
Ok(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,11 +1,8 @@
pub mod auth; pub mod auth;
pub mod cookie_store;
pub mod credential; pub mod credential;
pub mod error; pub mod error;
pub mod gateway; pub mod gateway;
pub mod gp_params; pub mod gp_params;
pub mod os_profile;
pub mod params;
pub mod portal; pub mod portal;
pub mod process; pub mod process;
pub mod service; pub mod service;
@@ -1,581 +0,0 @@
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
@@ -1,78 +0,0 @@
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
@@ -1,62 +0,0 @@
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
@@ -1,487 +0,0 @@
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
@@ -1,125 +0,0 @@
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
@@ -1,15 +0,0 @@
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
@@ -1,304 +0,0 @@
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
@@ -1,147 +0,0 @@
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);
}
}
+39 -53
View File
@@ -13,7 +13,6 @@ use crate::{
error::PortalError, error::PortalError,
gateway::{Gateway, parse_gateways}, gateway::{Gateway, parse_gateways},
gp_params::GpParams, gp_params::GpParams,
params,
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
}; };
@@ -43,10 +42,6 @@ pub struct PortalConfig {
* Whether the portal policy allows extending the gateway session. * Whether the portal policy allows extending the gateway session.
*/ */
allow_extend_session: Option<bool>, allow_extend_session: Option<bool>,
/**
* Whether the portal policy enables default-browser authentication.
*/
default_browser: Option<bool>,
} }
impl PortalConfig { impl PortalConfig {
@@ -82,10 +77,6 @@ impl PortalConfig {
self.allow_extend_session self.allow_extend_session
} }
pub fn default_browser(&self) -> Option<bool> {
self.default_browser
}
/// In-place sort the gateways by region /// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) { pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region); let preferred_gateway = self.find_preferred_gateway(region);
@@ -136,17 +127,13 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let url = format!("{}/global-protect/getconfig.esp", portal); let url = format!("{}/global-protect/getconfig.esp", portal);
let client = Client::try_from(gp_params)?; let client = Client::try_from(gp_params)?;
let request_params = params::portal_getconfig::build(cred, gp_params, &server); let swg_nonce = csc::swg_nonce();
let body_pairs: Vec<(&str, &str)> = request_params let params = build_config_params(cred, gp_params, &server, &swg_nonce);
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent()); info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_form_params(&body_pairs)); info!("Portal config request params: {}", redact_params(&params));
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| { let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e)) anyhow::anyhow!(PortalError::NetworkError(e))
})?; })?;
@@ -173,11 +160,6 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
if csc::is_config_criteria(&root) { if csc::is_config_criteria(&root) {
info!("Portal returned CSC criteria: {}", csc_criteria_summary(&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?; let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml); debug!("Portal CSC config response: {}", csc_xml);
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
@@ -188,6 +170,27 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
parse_portal_config(&server, cred, root) parse_portal_config(&server, cred, root)
} }
fn build_config_params<'a>(
cred: &'a Credential,
gp_params: &'a GpParams,
server: &'a str,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", server);
params.insert("host", server);
params.insert("csc-digest", "");
params.insert("config-digest", "");
params.insert("csc-support", "yes");
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
async fn retrieve_csc_config( async fn retrieve_csc_config(
client: &Client, client: &Client,
portal: &str, portal: &str,
@@ -274,7 +277,6 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
let version = root.descendant_text("version").map(|s| s.to_string()); let version = root.descendant_text("version").map(|s| s.to_string());
info!("Detected portal version: {:?}", version); info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root); let allow_extend_session = parse_allow_extend_session(&root);
let default_browser = parse_default_browser(&root);
Ok(PortalConfig { Ok(PortalConfig {
portal: server.to_string(), portal: server.to_string(),
@@ -286,18 +288,9 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version, version,
allow_extend_session, 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> { fn parse_allow_extend_session(root: &Element) -> Option<bool> {
match root.descendant_text("allow-extend-session")?.trim() { match root.descendant_text("allow-extend-session")?.trim() {
"yes" => Some(true), "yes" => Some(true),
@@ -356,6 +349,20 @@ mod tests {
Element::parse(xml.as_bytes()).unwrap() Element::parse(xml.as_bytes()).unwrap()
} }
#[test]
fn getconfig_params_include_csc_support_fields() {
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_config_params(&cred, &gp_params, "vpn.example.com", "123");
assert_eq!(params.get("csc-support"), Some(&"yes"));
assert_eq!(params.get("csc-digest"), Some(&""));
assert_eq!(params.get("config-digest"), Some(&""));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
assert_eq!(params.get("host"), Some(&"vpn.example.com"));
}
#[test] #[test]
fn parses_allow_extend_session_yes() { fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>"); let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
@@ -384,27 +391,6 @@ mod tests {
assert_eq!(parse_allow_extend_session(&root), None); 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] #[test]
fn parses_connect_method() { fn parses_connect_method() {
let root = parse_xml("<policy><connect-method>on-demand</connect-method></policy>"); let root = parse_xml("<policy><connect-method>on-demand</connect-method></policy>");
+106 -126
View File
@@ -8,7 +8,10 @@ use std::{
use xmltree::{Element, EmitterConfig, XMLNode}; use xmltree::{Element, EmitterConfig, XMLNode};
use crate::{gp_params::GpParams, utils::xml::ElementExt}; use crate::{
gp_params::GpParams,
utils::{host_utils, xml::ElementExt},
};
const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__"; const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__";
@@ -75,7 +78,7 @@ impl CscDataReader for SystemCscDataReader {
} }
} }
pub(crate) fn swg_nonce() -> String { pub(super) fn swg_nonce() -> String {
let millis = SystemTime::now() let millis = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis()) .map(|duration| duration.as_millis())
@@ -104,8 +107,8 @@ pub(super) fn build_csc_request_with_reader(
.filter(|value| !value.is_empty()) .filter(|value| !value.is_empty())
.ok_or_else(|| anyhow::anyhow!("CSC criteria response does not contain portal-csc-auth-cookie"))?; .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 config_digest = root.descendant_text("config-digest").unwrap_or_default();
let host_id = gp_params.host_id().to_string(); let host_id = collect_host_id(gp_params);
let serial_number = gp_params.serialno().to_string(); let serial_number = collect_serial_number();
let mut summary = CscBuildSummary::default(); let mut summary = CscBuildSummary::default();
let csc_data = build_csc_data( let csc_data = build_csc_data(
@@ -172,27 +175,22 @@ fn build_csc_data(
push_text(&mut root, "device-serial-number", input.serial_number); push_text(&mut root, "device-serial-number", input.serial_number);
push_text(&mut root, "csc-digest", input.csc_digest); push_text(&mut root, "csc-digest", input.csc_digest);
root.children.push(XMLNode::Element(Element::new("categories"))); root.children.push(XMLNode::Element(Element::new("categories")));
let custom_checks = build_custom_checks(input.criteria, input.gp_params, reader, summary); root.children.push(XMLNode::Element(build_custom_checks(
if !custom_checks.children.is_empty() { input.criteria,
root.children.push(XMLNode::Element(custom_checks)); input.gp_params,
} reader,
summary,
)));
let mut bytes = Vec::new(); let mut bytes = Vec::new();
root.write_with_config( root.write_with_config(
&mut bytes, &mut bytes,
EmitterConfig::new() EmitterConfig::new()
.perform_indent(true) .perform_indent(true)
.indent_string("\t")
.write_document_declaration(true), .write_document_declaration(true),
)?; )?;
String::from_utf8(bytes) String::from_utf8(bytes).map_err(Into::into)
.map(|xml| {
let mut xml = xml.replace("<categories />", "<categories>\n\t</categories>");
xml.push('\n');
xml
})
.map_err(Into::into)
} }
fn build_custom_checks( fn build_custom_checks(
@@ -206,17 +204,17 @@ fn build_custom_checks(
return custom_checks; return custom_checks;
}; };
if gp_params.os_profile().supports_macos_plist_csc() if gp_params.client_os() == "Mac"
&& let Some(plist) = requested_checks && let Some(plist) = requested_checks
.child("mac-os") .child("mac-os")
.and_then(|mac_os| mac_os.child("plist")) .and_then(|mac_os| mac_os.child("plist"))
{ {
custom_checks custom_checks
.children .children
.push(XMLNode::Element(build_plist_checks(plist, reader, summary))); .push(XMLNode::Element(build_plist_checks(plist, gp_params, reader, summary)));
} }
if gp_params.os_profile().supports_linux_process_csc() if gp_params.client_os() == "Linux"
&& let Some(process_list) = requested_checks && let Some(process_list) = requested_checks
.child("linux") .child("linux")
.and_then(|linux| linux.child("process-list")) .and_then(|linux| linux.child("process-list"))
@@ -229,21 +227,15 @@ fn build_custom_checks(
))); )));
} }
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 custom_checks
} }
fn build_plist_checks(plist: &Element, reader: &dyn CscDataReader, summary: &mut CscBuildSummary) -> Element { fn build_plist_checks(
plist: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("plist"); let mut out = Element::new("plist");
for entry in plist.children("entry") { for entry in plist.children("entry") {
@@ -255,7 +247,10 @@ fn build_plist_checks(plist: &Element, reader: &dyn CscDataReader, summary: &mut
let values: Vec<_> = keys let values: Vec<_> = keys
.iter() .iter()
.map(|key| { .map(|key| {
let value = reader.read_preference(domain, key); let value = gp_params
.csc_preference_override(domain, key)
.map(str::to_string)
.or_else(|| reader.read_preference(domain, key));
(key.as_str(), value) (key.as_str(), value)
}) })
.collect(); .collect();
@@ -349,42 +344,6 @@ fn process_list_names(process_list: &Element) -> Vec<String> {
names 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 { fn pan_md5_hex(value: &[u8]) -> String {
let digest = md5::compute(value); let digest = md5::compute(value);
let mut out = String::new(); let mut out = String::new();
@@ -394,6 +353,63 @@ fn pan_md5_hex(value: &[u8]) -> String {
out out
} }
fn collect_host_id(gp_params: &GpParams) -> String {
match gp_params.client_os() {
"Mac" => netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.unwrap_or_default(),
"Windows" => host_utils::get_machine_id().to_string(),
_ => host_utils::derive_uuid(&[]),
}
}
fn collect_serial_number() -> String {
collect_macos_serial_number()
.or_else(collect_linux_serial_number)
.or_else(collect_windows_serial_number)
.unwrap_or_default()
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.into_iter()
.filter_map(|path| fs::read_to_string(path).ok())
.map(|value| value.trim().to_string())
.find(|value| !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M.")
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn read_macos_preference(domain: &str, key: &str) -> Option<String> { fn read_macos_preference(domain: &str, key: &str) -> Option<String> {
if cfg!(not(target_os = "macos")) { if cfg!(not(target_os = "macos")) {
return None; return None;
@@ -454,10 +470,7 @@ fn yes_no(value: bool) -> &'static str {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::{ use crate::gp_params::{ClientOs, GpParams};
gp_params::GpParams,
os_profile::{ClientOs, HostIdentity, OsProfile},
};
struct TestCscDataReader { struct TestCscDataReader {
values: HashMap<String, String>, values: HashMap<String, String>,
@@ -479,15 +492,10 @@ mod tests {
} }
fn gp_params(client_os: ClientOs) -> GpParams { fn gp_params(client_os: ClientOs) -> GpParams {
let profile = OsProfile::builder(client_os) GpParams::builder()
.host_identity(HostIdentity::new( .client_os(client_os)
"test-computer".to_string(), .os_version(Some("Apple Mac OS X 26.4.1".to_string()))
"host-id".to_string(), .build()
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
GpParams::builder(profile).build()
} }
#[test] #[test]
@@ -524,7 +532,7 @@ mod tests {
assert_eq!(req.auth_cookie, "cookie"); assert_eq!(req.auth_cookie, "cookie");
assert!(req.csc_data.contains("<user-name>alice%40example.com</user-name>")); 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("<client-os>Apple+Mac+OS+X+26.4.1</client-os>"));
assert!(req.csc_data.contains("<exist>yes</exist>")); assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>")); assert!(req.csc_data.contains("<value>ExampleValue</value>"));
assert!( assert!(
@@ -561,10 +569,16 @@ mod tests {
} }
#[test] #[test]
fn empty_csc_report_uses_official_format_for_digest() { fn macos_plist_override_works_without_native_preference() {
let root = parse_xml( let root = parse_xml(
r#"<config-criteria> r#"<config-criteria>
<custom-checks /> <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> <portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#, </config-criteria>"#,
); );
@@ -572,18 +586,16 @@ mod tests {
values: HashMap::new(), values: HashMap::new(),
processes: Vec::new(), processes: Vec::new(),
}; };
let gp_params = GpParams::builder()
.client_os(ClientOs::Mac)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.csc_preference_override("com.example.settings", "ExampleKey", "ExampleValue")
.build();
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap(); let req = build_csc_request_with_reader(&root, "alice", &gp_params, &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("<exist>yes</exist>"));
assert!( assert!(req.csc_data.contains("<value>ExampleValue</value>"));
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] #[test]
@@ -642,38 +654,6 @@ mod tests {
assert!(req.summary().contains("process_missing=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] #[test]
fn uses_pan_non_padded_md5_digest() { fn uses_pan_non_padded_md5_digest() {
assert_eq!(pan_md5_hex(b""), "d41d8cd98f0b24e980998ecf8427e"); assert_eq!(pan_md5_hex(b""), "d41d8cd98f0b24e980998ecf8427e");
+1 -1
View File
@@ -1,5 +1,5 @@
mod config; mod config;
pub(crate) mod csc; mod csc;
mod prelogin; mod prelogin;
pub use config::*; pub use config::*;
+21 -135
View File
@@ -8,11 +8,20 @@ use xmltree::Element;
use crate::{ use crate::{
error::PortalError, error::PortalError,
gp_params::GpParams, gp_params::GpParams,
os_profile::PreloginBrowserMode,
params::{gateway_prelogin, portal_prelogin},
utils::{base64, normalize_server, parse_gp_response, xml::ElementExt}, 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)] #[derive(Debug, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SamlPrelogin { pub struct SamlPrelogin {
@@ -87,64 +96,27 @@ impl Prelogin {
} }
} }
#[derive(Debug, Clone, Copy, Default)] pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> {
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 user_agent = gp_params.user_agent();
let is_gateway = gp_params.is_gateway(); let is_gateway = gp_params.is_gateway();
let prelogin_type = if is_gateway { "Gateway" } else { "Portal" }; let prelogin_type = if is_gateway { "Gateway" } else { "Portal" };
info!("{} prelogin with user_agent: {}", prelogin_type, user_agent);
let portal = normalize_server(portal)?; let portal = normalize_server(portal)?;
let path = if is_gateway { "ssl-vpn" } else { "global-protect" }; let path = if is_gateway { "ssl-vpn" } else { "global-protect" };
let prelogin_url = format!("{portal}/{}/prelogin.esp", path); let prelogin_url = format!("{portal}/{}/prelogin.esp", path);
let browser_mode = options.browser_mode(is_gateway); let mut params = gp_params.to_params();
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("");
info!( params.insert("tmp", "tmp");
"{} prelogin with user_agent: {}, default_browser: {}", params.insert("default-browser", "1");
prelogin_type, user_agent, default_browser params.insert("cas-support", "yes");
);
params.retain(|k, _| REQUIRED_PARAMS.iter().any(|required_param| required_param == k));
let client = Client::try_from(gp_params)?; let client = Client::try_from(gp_params)?;
let mut request = client.post(&prelogin_url); let res = client.post(&prelogin_url).form(&params).send().await.map_err(|e| {
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); warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e)) anyhow::anyhow!(PortalError::NetworkError(e))
})?; })?;
@@ -172,14 +144,6 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
Ok(prelogin) 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> { fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let root = Element::parse(res_xml.as_bytes())?; let root = Element::parse(res_xml.as_bytes())?;
@@ -239,81 +203,3 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
Ok(Prelogin::Standard(standard_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);
}
}
+28 -101
View File
@@ -1,10 +1,10 @@
use std::{path::PathBuf, process::Stdio}; use std::process::Stdio;
use anyhow::bail; use anyhow::bail;
use common::binary_paths; use common::constants::GP_AUTH_BINARY;
use tokio::process::Command; use tokio::process::Command;
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile}; use crate::{auth::SamlAuthResult, credential::Credential};
use super::command_traits::CommandExt; use super::command_traits::CommandExt;
@@ -13,12 +13,9 @@ pub struct SamlAuthLauncher<'a> {
auth_executable: Option<&'a str>, auth_executable: Option<&'a str>,
gateway: bool, gateway: bool,
saml_request: Option<&'a str>, saml_request: Option<&'a str>,
user_agent: Option<&'a str>,
os: Option<&'a str>, os: Option<&'a str>,
host_id: Option<&'a str>, os_version: Option<&'a str>,
client_version: Option<&'a str>,
certificate: Option<&'a str>,
sslkey: Option<&'a str>,
key_password: Option<&'a str>,
fix_openssl: bool, fix_openssl: bool,
ignore_tls_errors: bool, ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
@@ -38,12 +35,9 @@ impl<'a> SamlAuthLauncher<'a> {
auth_executable: None, auth_executable: None,
gateway: false, gateway: false,
saml_request: None, saml_request: None,
user_agent: None,
os: None, os: None,
host_id: None, os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
fix_openssl: false, fix_openssl: false,
ignore_tls_errors: false, ignore_tls_errors: false,
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
@@ -72,10 +66,18 @@ impl<'a> SamlAuthLauncher<'a> {
self self
} }
pub fn os_profile(mut self, profile: &'a OsProfile) -> Self { pub fn user_agent(mut self, user_agent: &'a str) -> Self {
self.os = Some(profile.client_os().as_str()); self.user_agent = Some(user_agent);
self.host_id = Some(profile.host_identity().host_id()); self
self.client_version = Some(profile.client_version()); }
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;
self self
} }
@@ -89,21 +91,6 @@ impl<'a> SamlAuthLauncher<'a> {
self 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")] #[cfg(feature = "webview-auth")]
pub fn hidpi(mut self, hidpi: bool) -> Self { pub fn hidpi(mut self, hidpi: bool) -> Self {
self.hidpi = hidpi; self.hidpi = hidpi;
@@ -134,11 +121,8 @@ impl<'a> SamlAuthLauncher<'a> {
/// Launch the authenticator binary as the current user or SUDO_USER if available. /// Launch the authenticator binary as the current user or SUDO_USER if available.
pub async fn launch(self) -> anyhow::Result<Credential> { pub async fn launch(self) -> anyhow::Result<Credential> {
let program = self let program = self.auth_executable.unwrap_or(GP_AUTH_BINARY);
.auth_executable let mut auth_cmd = Command::new(program);
.map(PathBuf::from)
.unwrap_or_else(binary_paths::gpauth);
let mut auth_cmd = Command::new(&program);
auth_cmd.arg(self.server); auth_cmd.arg(self.server);
if self.gateway { if self.gateway {
@@ -149,16 +133,16 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--saml-request").arg(saml_request); 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 { if let Some(os) = self.os {
auth_cmd.arg("--os").arg(os); auth_cmd.arg("--os").arg(os);
} }
if let Some(host_id) = self.host_id { if let Some(os_version) = self.os_version {
auth_cmd.arg("--host-id").arg(host_id); auth_cmd.arg("--os-version").arg(os_version);
}
if let Some(client_version) = self.client_version {
auth_cmd.arg("--client-version").arg(client_version);
} }
if self.fix_openssl { if self.fix_openssl {
@@ -169,18 +153,6 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--ignore-tls-errors"); 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")] #[cfg(feature = "webview-auth")]
{ {
if self.hidpi { if self.hidpi {
@@ -210,7 +182,7 @@ impl<'a> SamlAuthLauncher<'a> {
let child = match child { let child = match child {
Ok(child) => child, Ok(child) => child,
Err(err) => { Err(err) => {
bail!("Failed to spawn {}: {}", program.display(), err); bail!("Failed to spawn {}: {}", program, err);
} }
}; };
@@ -223,48 +195,3 @@ impl<'a> SamlAuthLauncher<'a> {
Credential::try_from(auth_result) 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"));
}
}
+1 -3
View File
@@ -2,7 +2,7 @@ use std::ffi::OsStr;
use tokio::process::Command; use tokio::process::Command;
use uzers::os::unix::UserExt; use uzers::os::unix::UserExt;
use super::{desktop_session_env, users::get_non_root_user}; use super::users::get_non_root_user;
pub trait CommandExt { pub trait CommandExt {
fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command; fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command;
@@ -28,8 +28,6 @@ impl CommandExt for Command {
fn into_non_root(mut self) -> anyhow::Result<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))?; 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 self
.env("HOME", user.home_dir()) .env("HOME", user.home_dir())
.env("USER", user.name()) .env("USER", user.name())
@@ -1,217 +0,0 @@
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 std::{collections::HashMap, path::PathBuf, process::Stdio};
use anyhow::bail; use anyhow::bail;
use common::binary_paths; use common::constants::GP_GUI_HELPER_BINARY;
use log::info; use log::info;
use tokio::{io::AsyncWriteExt, process::Command}; use tokio::{io::AsyncWriteExt, process::Command};
@@ -17,7 +17,7 @@ pub struct GuiHelperLauncher<'a> {
impl<'a> GuiHelperLauncher<'a> { impl<'a> GuiHelperLauncher<'a> {
pub fn new(api_key: &'a [u8]) -> Self { pub fn new(api_key: &'a [u8]) -> Self {
Self { Self {
program: binary_paths::gpgui_helper(), program: GP_GUI_HELPER_BINARY.into(),
envs: None, envs: None,
api_key, api_key,
gui_version: None, gui_version: None,
+2 -2
View File
@@ -5,7 +5,7 @@ use std::{
}; };
use anyhow::bail; use anyhow::bail;
use common::binary_paths; use common::constants::GP_GUI_BINARY;
use log::info; use log::info;
use tokio::{io::AsyncWriteExt, process::Command}; 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 { pub fn new(version: &'a str, api_key: &'a [u8]) -> Self {
Self { Self {
version, version,
program: binary_paths::gpgui(), program: GP_GUI_BINARY.into(),
api_key, api_key,
minimized: false, minimized: false,
envs: None, envs: None,
-1
View File
@@ -1,5 +1,4 @@
pub(crate) mod command_traits; pub(crate) mod command_traits;
mod desktop_session_env;
pub(crate) mod gui_helper_launcher; pub(crate) mod gui_helper_launcher;
pub mod auth_launcher; pub mod auth_launcher;
+2 -2
View File
@@ -4,7 +4,7 @@ use std::{
process::{ExitStatus, Stdio}, process::{ExitStatus, Stdio},
}; };
use common::binary_paths; use common::constants::GP_SERVICE_BINARY;
use tokio::process::Command; use tokio::process::Command;
use super::command_traits::CommandExt; use super::command_traits::CommandExt;
@@ -26,7 +26,7 @@ impl Default for ServiceLauncher<'_> {
impl<'a> ServiceLauncher<'a> { impl<'a> ServiceLauncher<'a> {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
program: binary_paths::gpservice(), program: GP_SERVICE_BINARY.into(),
minimized: false, minimized: false,
env_file: None, env_file: None,
log_file: None, log_file: None,
+8 -85
View File
@@ -3,18 +3,12 @@ use std::env;
use anyhow::bail; use anyhow::bail;
use uzers::User; use uzers::User;
#[derive(Debug, PartialEq, Eq)]
enum RealUserLookup {
Uid(u32),
Name(String),
}
pub fn get_user_by_name(username: &str) -> anyhow::Result<User> { 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)) uzers::get_user_by_name(username).ok_or_else(|| anyhow::anyhow!("User ({}) not found", username))
} }
pub fn get_non_root_user() -> anyhow::Result<User> { pub fn get_non_root_user() -> anyhow::Result<User> {
let current_user = current_username()?; let current_user = whoami::username();
let user = if current_user == "root" { let user = if current_user == "root" {
get_real_user()? get_real_user()?
@@ -30,87 +24,16 @@ pub fn get_non_root_user() -> anyhow::Result<User> {
} }
pub fn get_current_user() -> anyhow::Result<User> { pub fn get_current_user() -> anyhow::Result<User> {
let current_user = current_username()?; let current_user = whoami::username();
get_user_by_name(&current_user) 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> { fn get_real_user() -> anyhow::Result<User> {
match real_user_lookup(|key| env::var(key).ok())? { // Read the UID from SUDO_UID or PKEXEC_UID environment variable if available.
RealUserLookup::Uid(uid) => uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found")), let uid = match env::var("SUDO_UID") {
RealUserLookup::Name(name) => get_user_by_name(&name), Ok(uid) => uid.parse::<u32>()?,
} _ => env::var("PKEXEC_UID")?.parse::<u32>()?,
} };
fn real_user_lookup(env_var: impl Fn(&str) -> Option<String>) -> anyhow::Result<RealUserLookup> { uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found"))
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());
}
#[test]
fn real_user_lookup_errors_without_root_origin_env() {
assert!(lookup(&[]).is_err());
}
} }
+18 -43
View File
@@ -3,10 +3,7 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::{ use crate::{gateway::Gateway, gp_params::ClientOs};
gateway::Gateway,
os_profile::{ClientOs, OsProfile},
};
use super::vpn_state::ConnectInfo; use super::vpn_state::ConnectInfo;
@@ -39,7 +36,6 @@ pub struct ConnectArgs {
os: Option<ClientOs>, os: Option<ClientOs>,
os_version: Option<String>, os_version: Option<String>,
client_version: Option<String>, client_version: Option<String>,
host_id: Option<String>,
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
@@ -69,7 +65,6 @@ impl ConnectArgs {
os: None, os: None,
os_version: None, os_version: None,
client_version: None, client_version: None,
host_id: None,
certificate: None, certificate: None,
sslkey: None, sslkey: None,
key_password: None, key_password: None,
@@ -115,10 +110,6 @@ impl ConnectArgs {
self.client_version.clone() self.client_version.clone()
} }
pub fn host_id(&self) -> Option<String> {
self.host_id.clone()
}
pub fn certificate(&self) -> Option<String> { pub fn certificate(&self) -> Option<String> {
self.certificate.clone() self.certificate.clone()
} }
@@ -210,12 +201,23 @@ impl ConnectRequest {
self self
} }
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self { pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.args.os = Some(profile.client_os()); self.args.user_agent = user_agent.into();
self.args.os_version = Some(profile.os_version().to_string()); self
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()); 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());
self self
} }
@@ -312,12 +314,6 @@ mod tests {
use serde_json::json; use serde_json::json;
use super::*; 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] #[test]
fn connect_request_serializes_allow_extend_session() { fn connect_request_serializes_allow_extend_session() {
@@ -328,25 +324,4 @@ mod tests {
assert_eq!(value["args"]["allowExtendSession"], json!(true)); 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())
);
}
} }
+1 -15
View File
@@ -1,17 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{os_profile::HostIdentity, service::vpn_state::VpnState}; use crate::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. /// Represents the VPN environment configuration.
/// When a client connects, the gpservice sends the current VPN environment /// When a client connects, the gpservice sends the current VPN environment
@@ -30,7 +19,4 @@ pub struct VpnEnv {
/// The gpauth executable path /// The gpauth executable path
/// Used by the client to launch gpauth for authentication /// Used by the client to launch gpauth for authentication
pub auth_executable: String, pub auth_executable: String,
/// Host identity collected by gpservice.
pub host_info: HostInfo,
} }
+35 -7
View File
@@ -4,6 +4,8 @@ use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning { pub struct SessionWarning {
pub prior_secs: u32, pub prior_secs: u32,
@@ -14,6 +16,9 @@ pub struct SessionWarning {
pub struct SessionRequestArgs { pub struct SessionRequestArgs {
cookie: String, cookie: String,
user_agent: Option<String>, user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
@@ -25,6 +30,9 @@ impl SessionRequestArgs {
Self { Self {
cookie, cookie,
user_agent: None, user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None, certificate: None,
sslkey: None, sslkey: None,
key_password: None, key_password: None,
@@ -37,6 +45,21 @@ impl SessionRequestArgs {
self 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 { pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into(); self.certificate = certificate.into();
self self
@@ -65,6 +88,18 @@ impl SessionRequestArgs {
self.user_agent.clone() 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> { pub fn certificate(&self) -> Option<String> {
self.certificate.clone() self.certificate.clone()
} }
@@ -264,11 +299,4 @@ mod tests {
fn reschedule_after_extension_requires_lifetime() { fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none()); 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
@@ -0,0 +1,108 @@
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,6 +5,7 @@ pub mod checksum;
pub mod crypto; pub mod crypto;
pub mod endpoint; pub mod endpoint;
pub mod env_utils; pub mod env_utils;
pub mod host_utils;
pub mod lock_file; pub mod lock_file;
pub mod openssl; pub mod openssl;
pub mod redact; pub mod redact;
+8 -31
View File
@@ -24,49 +24,26 @@ mod unix {
use anyhow::bail; use anyhow::bail;
use gtk::{ use gtk::{
EventBox, EventBox,
glib::{self, Cast}, glib::Cast,
traits::{EventBoxExt, GtkWindowExt, WidgetExt}, traits::{EventBoxExt, GtkWindowExt, WidgetExt},
}; };
use log::info; use log::info;
use tauri::WebviewWindow; use tauri::WebviewWindow;
use tokio::process::Command; 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<()> { pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland"; let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland { if is_wayland {
let gtk_win = win.gtk_window()?; 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 operations must run on the main thread. When this function is called gtk_win.hide();
// from a background thread (e.g., rspc handler on a tokio worker), calling gtk_win.show_all();
// 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 { } else {
if !win.is_visible()? { if !win.is_visible()? {
win.show()?; win.show()?;
+9 -18
View File
@@ -1,6 +1,10 @@
use std::{env, path::PathBuf, process::Command}; use std::{
env,
path::{Path, PathBuf},
process::Command,
};
fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) { fn apply_patches(patches_dir: &Path, build_src: &Path) {
let patches = std::fs::read_dir(patches_dir) let patches = std::fs::read_dir(patches_dir)
.expect("Failed to read patches directory") .expect("Failed to read patches directory")
.filter_map(|entry| entry.ok()) .filter_map(|entry| entry.ok())
@@ -30,7 +34,7 @@ fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
} }
} }
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { fn build_libxml2(deps_dir: &Path, out_dir: &Path) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2"); let libxml2_dir = deps_dir.join("libxml2");
// The temporary location where we will build // The temporary location where we will build
@@ -89,7 +93,7 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
dst dst
} }
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { fn build_openconnect(deps_dir: &Path, out_dir: &Path) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect"); let openconnect_dir = deps_dir.join("openconnect");
let patches_dir = deps_dir.join("patches"); let patches_dir = deps_dir.join("patches");
@@ -143,13 +147,6 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
config.env("LIBS", "-liconv"); 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 dst = config.build();
let lib_dir = dst.join("lib"); let lib_dir = dst.join("lib");
@@ -197,12 +194,6 @@ fn main() {
println!("cargo:rerun-if-changed=src/ffi/vpn.c"); println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h"); 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 // Prevent silent fallback to dynamic libraries
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {
@@ -213,6 +204,6 @@ fn main() {
cc::Build::new() cc::Build::new()
.file("src/ffi/vpn.c") .file("src/ffi/vpn.c")
.include("src/ffi") .include("src/ffi")
.include(&oc_dst.join("include")) .include(oc_dst.join("include"))
.compile("vpn"); .compile("vpn");
} }
@@ -1,101 +0,0 @@
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,7 +15,6 @@ pub(crate) struct ConnectOptions {
pub os: *const c_char, pub os: *const c_char,
pub os_version: *const c_char, pub os_version: *const c_char,
pub client_version: *const c_char, pub client_version: *const c_char,
pub host_id: *const c_char,
pub local_hostname: *const c_char, pub local_hostname: *const c_char,
pub script: *const c_char, pub script: *const c_char,
-5
View File
@@ -80,7 +80,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("USER_AGENT: %s", options->user_agent); INFO("USER_AGENT: %s", options->user_agent);
INFO("OS: %s", options->os); INFO("OS: %s", options->os);
INFO("CLIENT_VERSION: %s", options->client_version); 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("VPNC_SCRIPT: %s", options->script);
INFO("SCRIPT_TUN: %d", g_script_tun); INFO("SCRIPT_TUN: %d", g_script_tun);
INFO("CSD_USER: %d", options->csd_uid); INFO("CSD_USER: %d", options->csd_uid);
@@ -121,10 +120,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
options->client_version); options->client_version);
} }
if (options->host_id) {
openconnect_set_gp_host_id(vpninfo, options->host_id);
}
effective_local_hostname = options->local_hostname; effective_local_hostname = options->local_hostname;
if (!effective_local_hostname && !uname(&utsbuf)) { if (!effective_local_hostname && !uname(&utsbuf)) {
effective_local_hostname = utsbuf.nodename; effective_local_hostname = utsbuf.nodename;
-1
View File
@@ -25,7 +25,6 @@ typedef struct vpn_options {
const char *os; const char *os;
const char *os_version; const char *os_version;
const char *client_version; const char *client_version;
const char *host_id;
const char *local_hostname; const char *local_hostname;
const char *script; const char *script;
-45
View File
@@ -64,7 +64,6 @@ pub struct Vpn {
os: CString, os: CString,
os_version: Option<CString>, os_version: Option<CString>,
client_version: Option<CString>, client_version: Option<CString>,
host_id: Option<CString>,
local_hostname: Option<CString>, local_hostname: Option<CString>,
script: CString, script: CString,
@@ -125,7 +124,6 @@ impl Vpn {
os: self.os.as_ptr(), os: self.os.as_ptr(),
os_version: Self::option_to_ptr(&self.os_version), os_version: Self::option_to_ptr(&self.os_version),
client_version: Self::option_to_ptr(&self.client_version), client_version: Self::option_to_ptr(&self.client_version),
host_id: Self::option_to_ptr(&self.host_id),
local_hostname: Self::option_to_ptr(&self.local_hostname), local_hostname: Self::option_to_ptr(&self.local_hostname),
script: self.script.as_ptr(), script: self.script.as_ptr(),
@@ -187,7 +185,6 @@ pub struct VpnBuilder {
os: Option<String>, os: Option<String>,
os_version: Option<String>, os_version: Option<String>,
client_version: Option<String>, client_version: Option<String>,
host_id: Option<String>,
local_hostname: Option<String>, local_hostname: Option<String>,
certificate: Option<String>, certificate: Option<String>,
@@ -220,7 +217,6 @@ impl VpnBuilder {
os: None, os: None,
os_version: None, os_version: None,
client_version: None, client_version: None,
host_id: None,
local_hostname: None, local_hostname: None,
certificate: None, certificate: None,
@@ -275,11 +271,6 @@ impl VpnBuilder {
self 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 { pub fn local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self {
self.local_hostname = local_hostname.into(); self.local_hostname = local_hostname.into();
self self
@@ -387,7 +378,6 @@ impl VpnBuilder {
os: Self::to_cstring(&os), os: Self::to_cstring(&os),
os_version: self.os_version.as_deref().map(Self::to_cstring), os_version: self.os_version.as_deref().map(Self::to_cstring),
client_version: self.client_version.as_deref().map(Self::to_cstring), client_version: self.client_version.as_deref().map(Self::to_cstring),
host_id: self.host_id.as_deref().map(Self::to_cstring),
local_hostname: self.local_hostname.as_deref().map(Self::to_cstring), local_hostname: self.local_hostname.as_deref().map(Self::to_cstring),
script: Self::to_cstring(&script), script: Self::to_cstring(&script),
@@ -463,39 +453,4 @@ mod tests {
assert_eq!(info.lifetime_secs, None); assert_eq!(info.lifetime_secs, None);
assert_eq!(info.lifetime_warning, 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");
}
} }
-2
View File
@@ -3,7 +3,6 @@ use std::{io, path::Path};
use is_executable::IsExecutable; use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/vpnc-script",
"/usr/libexec/gpclient/vpnc-script", "/usr/libexec/gpclient/vpnc-script",
"/usr/lib/gpclient/vpnc-script", "/usr/lib/gpclient/vpnc-script",
"/usr/local/share/vpnc-scripts/vpnc-script", "/usr/local/share/vpnc-scripts/vpnc-script",
@@ -20,7 +19,6 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
]; ];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[ const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh", "/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh", "/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
+51 -280
View File
@@ -21,12 +21,10 @@
inherit system; inherit system;
overlays = [ (import rust-overlay) ]; overlays = [ (import rust-overlay) ];
}; };
inherit (pkgs) lib;
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml); cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
pname = "globalprotect-openconnect"; pname = "globalprotect-openconnect";
version = cargoToml.workspace.package.version; version = cargoToml.workspace.package.version;
releaseTag = "snapshot";
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
@@ -36,111 +34,47 @@
}; };
src = pkgs.fetchzip { src = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${releaseTag}/globalprotect-openconnect-${version}.tar.gz"; url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/globalprotect-openconnect-${version}.tar.gz";
hash = "sha256-fBoOcUPaiylhJc3P3x0cdmvUQwYO2e1xIPvq4NZ6hLc="; hash = "sha256-NS3tIZxkT9A4eqmfkcl29bHHJrrgVs/XSQBOz99cP30=";
}; };
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name; cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
gpguiHashes = {
x86_64 = "sha256-orhK5844Cebc+IKtYBdc1OekkvJJv1suBzc0n3TNn8g=";
aarch64 = "sha256-Lvdefh/ddk1TlWmVTluHFNZQbVAJrSkuYyzzDHcyIm0=";
};
gpgui = pkgs.fetchzip { gpgui = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${releaseTag}/gpgui_${cpu}.bin.tar.xz"; url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/gpgui_${cpu}.bin.tar.xz";
hash = gpguiHashes.${cpu}; hash = {
x86_64 = "sha256-1XBdrKJOhSViZOgfqohZjdzV6qzx/qpy0yhkbZ8DumA=";
aarch64 = "sha256-humujgf/M31SkBABc14g/ujjacGHxqElzNuCClhTAfA=";
}.${cpu};
}; };
in
binaryHashes = { {
x86_64 = "sha256-/lvi+xF3xR8urBMkBI0R6aVSs34msarzTpkebH17TeU="; # For `nix build`
aarch64 = "sha256-hMV4xTMC1k3klX5BBRw2ThvjYDDYZkFEld+rDMfd3qU="; packages.default = naersk'.buildPackage {
};
binaryPackage = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${releaseTag}/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
'';
installNixosPolkitRule = ''
chmod u+w $out/share $out/share/polkit-1 2>/dev/null || true
install -d $out/share/polkit-1/rules.d
cat > $out/share/polkit-1/rules.d/49-gpgui.rules <<EOF
polkit.addRule(function(action, subject) {
if (
action.id == "org.freedesktop.policykit.exec" &&
action.lookup("program") == "$out/bin/gpservice" &&
subject.active
) {
return polkit.Result.YES;
}
});
EOF
'';
fromSource = naersk'.buildPackage {
inherit pname version src; inherit pname version src;
# Must be set to true to avoid issues with the Tauri build process # Must be set to true to avoid issues with the Tauri build process
singleStep = true; singleStep = true;
buildInputs = linuxBuildInputs; 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
];
nativeBuildInputs = nativeBuildInputs =
with pkgs; with pkgs;
@@ -155,7 +89,13 @@
wrapGAppsHook4 wrapGAppsHook4
]; ];
runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies; runtimeDependencies =
with pkgs;
[ ]
++ lib.optionals stdenv.isLinux [
libappindicator-gtk3
glib-networking
];
overrideMain = overrideMain =
{ ... }: { ... }:
@@ -184,192 +124,23 @@
cp -r packaging/files/usr/lib $out/lib cp -r packaging/files/usr/lib $out/lib
cp -r packaging/files/usr/libexec $out/libexec cp -r packaging/files/usr/libexec $out/libexec
${rewriteSourceInstallPaths} # Change the `/usr/bin/gpclient` path in the desktop file
${installNixosPolkitRule} 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
''; '';
}; };
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
install -Dm755 ${gpgui}/gpgui $out/bin/gpgui
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"
"--ro-bind-try"
"/etc/gpgui"
"/etc/gpgui"
];
};
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}
${installNixosPolkitRule}
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 = { apps.default = {
type = "app"; type = "app";
program = "${self.packages.${system}.default}/bin/gpclient"; program = "${self.packages.${system}.default}/bin/gpclient";
-1
View File
@@ -58,7 +58,6 @@ build() {
make build \ make build \
INCLUDE_GUI="${INCLUDE_GUI:-0}" \ INCLUDE_GUI="${INCLUDE_GUI:-0}" \
BUILD_GUI_HELPER="${BUILD_GUI_HELPER:-1}" \ BUILD_GUI_HELPER="${BUILD_GUI_HELPER:-1}" \
BUILD_WEBVIEW_AUTH="${BUILD_WEBVIEW_AUTH:-1}" \
LIBXML2_STATIC="${LIBXML2_STATIC:-1}" LIBXML2_STATIC="${LIBXML2_STATIC:-1}"
} }
-18
View File
@@ -1,18 +0,0 @@
<?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>
-53
View File
@@ -1,53 +0,0 @@
name: "@PKG_NAME@"
version: "@VERSION@"
origin: "security/@PKG_NAME@"
comment: "GlobalProtect VPN client based on OpenConnect"
maintainer: "Kevin Yue <[email protected]>"
www: "https://github.com/yuezk/GlobalProtect-openconnect"
abi: "@ABI@"
arch: "@ARCH@"
prefix: "@PREFIX@"
licenselogic: single
licenses: ["GPLv3"]
categories: ["security", "net"]
deps: {
"gmp": {
origin: "math/gmp"
version: "*"
}
"gnome-keyring": {
origin: "security/gnome-keyring"
version: "*"
}
"gnutls": {
origin: "security/gnutls"
version: "*"
}
"libayatana-appindicator": {
origin: "devel/libayatana-appindicator"
version: "*"
}
"libxml2": {
origin: "textproc/libxml2"
version: "*"
}
"nettle": {
origin: "security/nettle"
version: "*"
}
"p11-kit": {
origin: "security/p11-kit"
version: "*"
}
"polkit": {
origin: "sysutils/polkit"
version: "*"
}
"webkit2-gtk_41": {
origin: "www/webkit2-gtk"
version: "*"
}
}
desc: <<EOD
A GlobalProtect VPN client based on OpenConnect.
EOD
-10
View File
@@ -1,10 +0,0 @@
[Desktop Entry]
Type=Application
Name=GP Connect
Comment=A GUI client for GlobalProtect VPN
GenericName=GlobalProtect VPN Client
Categories=Network;Dialup;
Exec=/usr/local/bin/gpclient launch-gui %u
MimeType=x-scheme-handler/globalprotectcallback;
Icon=gpgui
Keywords=GlobalProtect;Openconnect;SAML;connection;VPN;
-1
View File
@@ -1 +0,0 @@
GlobalProtect VPN client based on OpenConnect
-1
View File
@@ -1 +0,0 @@
A GlobalProtect VPN client based on OpenConnect.
+1 -2
View File
@@ -23,8 +23,7 @@ Build-Depends: debhelper (>= 9),
libayatana-appindicator3-1, libayatana-appindicator3-1,
gnome-keyring, gnome-keyring,
libwebkit2gtk-4.1-dev, libwebkit2gtk-4.1-dev,
cargo-@RUST_VERSION@, rust-@RUST_VERSION@-all
rustc-@RUST_VERSION@
Homepage: https://github.com/yuezk/GlobalProtect-openconnect Homepage: https://github.com/yuezk/GlobalProtect-openconnect
Package: globalprotect-openconnect Package: globalprotect-openconnect
-1
View File
@@ -1,7 +1,6 @@
#!/usr/bin/make -f #!/usr/bin/make -f
export BUILD_GUI_HELPER = @BUILD_GUI_HELPER@ export BUILD_GUI_HELPER = @BUILD_GUI_HELPER@
export BUILD_WEBVIEW_AUTH = @BUILD_WEBVIEW_AUTH@
export DISABLE_RUST_TOOLCHAIN = 0 export DISABLE_RUST_TOOLCHAIN = 0
export PATH := /usr/lib/rust-@RUST_VERSION@/bin:/usr/local/cargo/bin:$(PATH) export PATH := /usr/lib/rust-@RUST_VERSION@/bin:/usr/local/cargo/bin:$(PATH)
-1
View File
@@ -32,7 +32,6 @@ COPY . .
RUN RUSTFLAGS="-C target-feature=-crt-static" \ RUN RUSTFLAGS="-C target-feature=-crt-static" \
make build \ make build \
BUILD_GUI_HELPER=0 \ BUILD_GUI_HELPER=0 \
BUILD_WEBVIEW_AUTH=0 \
INCLUDE_GUI=0 \ INCLUDE_GUI=0 \
LIBXML2_STATIC=1 LIBXML2_STATIC=1
@@ -5,15 +5,15 @@ LOGFILE="/tmp/gpclient-hipreport.log"
LINUX_GPCLIENT_BIN="/usr/bin/gpclient" LINUX_GPCLIENT_BIN="/usr/bin/gpclient"
ARM64_HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient" ARM64_HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient"
LOCAL_GPCLIENT_BIN="/usr/local/bin/gpclient" X86_64_HOMEBREW_GPCLIENT_BIN="/usr/local/bin/gpclient"
GPCLIENT_BIN="" GPCLIENT_BIN=""
if [ -x "$LINUX_GPCLIENT_BIN" ]; then if [ -x "$LINUX_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LINUX_GPCLIENT_BIN" GPCLIENT_BIN="$LINUX_GPCLIENT_BIN"
elif [ -x "$ARM64_HOMEBREW_GPCLIENT_BIN" ]; then elif [ -x "$ARM64_HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$ARM64_HOMEBREW_GPCLIENT_BIN" GPCLIENT_BIN="$ARM64_HOMEBREW_GPCLIENT_BIN"
elif [ -x "$LOCAL_GPCLIENT_BIN" ]; then elif [ -x "$X86_64_HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LOCAL_GPCLIENT_BIN" GPCLIENT_BIN="$X86_64_HOMEBREW_GPCLIENT_BIN"
else else
echo "Error: gpclient binary not found." > "$LOGFILE" echo "Error: gpclient binary not found." > "$LOGFILE"
exit 1 exit 1
+20 -37
View File
@@ -2,66 +2,49 @@
# Usage: ./scripts/gh-release.sh <tag> # Usage: ./scripts/gh-release.sh <tag>
set -euo pipefail set -e
shopt -s nullglob
REPO="yuezk/GlobalProtect-openconnect" REPO="yuezk/GlobalProtect-openconnect"
TAG=${1:-} TAG=$1
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
RELEASE_NOTES="Release $TAG"
if [ -z "$TAG" ]; then if [ -z "$TAG" ]; then
echo "Usage: ./scripts/gh-release.sh <tag>" echo "Usage: ./scripts/gh-release.sh <tag>"
exit 1 exit 1
fi fi
upload_files() {
local files=("$@")
if [ ${#files[@]} -eq 0 ]; then
echo "No release assets found to upload"
exit 1
fi
gh -R "$REPO" release upload "$TAG" "${files[@]}"
}
release_assets() {
"$SCRIPT_DIR/release-assets.sh" "$TAG"
}
# For snapshot release, we don't create a release, just clear the existing assets and upload new ones. # For snapshot release, we don't create a release, just clear the existing assets and upload new ones.
# This is to avoid notification spam. # This is to avoid notification spam.
release_snapshot() { release_snapshot() {
while IFS= read -r asset; do RELEASE_NOTES='**!!! DO NOT USE THIS RELEASE IN PRODUCTION !!!**'
if [ -n "$asset" ]; then
gh -R "$REPO" release delete-asset "$TAG" "$asset" --yes # Get the existing assets
fi gh -R "$REPO" release view "$TAG" --json assets --jq '.assets[].name' \
done < <(gh -R "$REPO" release view "$TAG" --json assets --jq '.assets[].name') | xargs -I {} gh -R "$REPO" release delete-asset "$TAG" {} --yes
echo "Uploading new assets..." echo "Uploading new assets..."
# Upload all artifacts for snapshot release because we don't need to guarantee stability. # Upload all artifacts for snapshot release because we don't need to guarantee stability.
mapfile -t files < <(release_assets) gh -R "$REPO" release upload "$TAG" \
upload_files "${files[@]}" "$PROJECT_DIR"/.build/artifacts/artifact-*/*
} }
release_tag() { release_tag() {
echo "Removing existing release..." echo "Removing existing release..."
gh -R "$REPO" release delete "$TAG" --yes --cleanup-tag || true gh -R "$REPO" release delete $TAG --yes --cleanup-tag || true
echo "Creating release..." echo "Creating release..."
local release_notes_file # Only upload the source tarball and GUI components for tagged release.
release_notes_file="$(mktemp)" # Other components will be built in `release.yml` from the standalone
"$SCRIPT_DIR/release-notes.sh" "$TAG" > "$release_notes_file" # source tarball and uploaded. This is to ensure the source tarball is stable.
gh -R "$REPO" release create $TAG \
# Upload source tarballs, GUI components, and BSD packages. Other Linux
# packages are built in `release.yml` from the standalone source tarball.
gh -R "$REPO" release create "$TAG" \
--title "$TAG" \ --title "$TAG" \
--notes-file "$release_notes_file" --notes "$RELEASE_NOTES" \
"$PROJECT_DIR"/.build/artifacts/artifact-source*/* \
mapfile -t files < <(release_assets) "$PROJECT_DIR"/.build/artifacts/artifact-gpgui-*/*
upload_files "${files[@]}"
} }
if [[ $TAG == *"snapshot" ]]; then if [[ $TAG == *"snapshot" ]]; then
-59
View File
@@ -1,59 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
release_version="${1:-}"
release_tag="${2:-}"
if git diff --quiet -- flake.nix; then
echo "flake.nix hashes are already up to date"
exit 0
fi
if [[ -z "$release_version" ]]; then
release_version="$(grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')"
fi
version="${release_version#v}"
if [[ -z "$release_tag" ]]; then
release_tag="v$version"
fi
branch_suffix="v${version}"
title="chore: update flake hashes for v${version}"
body="Updates the Nix flake fetchzip hashes for v${version} release assets."
if [[ "$release_tag" != "v$version" ]]; then
branch_suffix="${branch_suffix}-${release_tag}"
title="chore: update flake hashes for v${version} from ${release_tag}"
body="Updates the Nix flake fetchzip hashes for v${version} using ${release_tag} release assets."
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if [[ "$release_tag" == "snapshot" ]]; then
source_branch="${GITHUB_REF_NAME:-$(git branch --show-current)}"
source_branch_slug="$(printf '%s' "$source_branch" | sed -E 's#[/[:space:]]+#-#g; s#[^A-Za-z0-9._-]##g; s#^-+##; s#-+$##')"
branch="chore/flake-${source_branch_slug}"
git switch -C "$branch"
git add flake.nix
git commit -m "$title"
git push --force origin "$branch"
echo "Updated snapshot flake hashes on branch $branch from $source_branch; skipping PR creation"
exit 0
fi
branch="chore/update-flake-hashes-${branch_suffix}"
git switch -C "$branch"
git add flake.nix
git commit -m "$title"
git push --force 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 "$title" --body "$body"
else
gh pr create --title "$title" --body "$body" --base main --head "$branch"
fi
-37
View File
@@ -1,37 +0,0 @@
#!/bin/bash
set -euo pipefail
shopt -s nullglob
SELECTION=${1:-}
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
ARTIFACT_DIR=${2:-"$PROJECT_DIR/.build/artifacts"}
if [ -z "$SELECTION" ]; then
echo "Usage: ./scripts/release-assets.sh <snapshot|tag|all|release-tag> [artifact-dir]" >&2
exit 1
fi
if [[ "$SELECTION" == *"snapshot"* ]]; then
SELECTION=snapshot
elif [ "$SELECTION" != "all" ]; then
SELECTION=tag
fi
case "$SELECTION" in
snapshot|all)
printf '%s\n' "$ARTIFACT_DIR"/artifact-*/*
;;
tag)
printf '%s\n' \
"$ARTIFACT_DIR"/artifact-source*/* \
"$ARTIFACT_DIR"/artifact-gpgui-*/* \
"$ARTIFACT_DIR"/artifact-bsd-*/*
;;
*)
echo "Unknown release asset selection: $SELECTION" >&2
exit 1
;;
esac
-32
View File
@@ -1,32 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
tag="${1:-}"
if [[ -z "$tag" ]]; then
echo "Usage: $0 <tag>" >&2
exit 1
fi
version="${tag#v}"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
changelog="$script_dir/../changelog.md"
awk -v version="$version" '
$0 == "## " version {
found = 1
next
}
found && /^## / {
exit
}
found {
print
}
END {
if (!found) {
exit 1
}
}
' "$changelog"
+6 -27
View File
@@ -9,11 +9,10 @@ PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
FLAKE_FILE="$PROJECT_DIR/flake.nix" FLAKE_FILE="$PROJECT_DIR/flake.nix"
usage() { usage() {
echo "Usage: $0 [version] [release-tag]" echo "Usage: $0 [version]"
echo echo
echo "Updates flake.nix fetchzip hashes from the published GitHub release assets." echo "Updates flake.nix fetchzip hashes from the published GitHub release assets."
echo "When version is omitted, the workspace package version from Cargo.toml is used." echo "When version is omitted, the workspace package version from Cargo.toml is used."
echo "When release-tag is omitted, v<version> is used. Use snapshot to test snapshot assets."
} }
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
@@ -36,21 +35,12 @@ if [[ -z "$version" ]]; then
version="$(grep '^version' "$PROJECT_DIR/Cargo.toml" | head -1 | sed 's/version *= *"\(.*\)"/\1/')" version="$(grep '^version' "$PROJECT_DIR/Cargo.toml" | head -1 | sed 's/version *= *"\(.*\)"/\1/')"
fi fi
version="${version#v}" version="${version#v}"
release_tag="${2:-}"
if [[ -z "$release_tag" ]]; then
release_tag="v$version"
fi
if [[ -z "$version" ]]; then if [[ -z "$version" ]]; then
echo "Could not determine release version" >&2 echo "Could not determine release version" >&2
exit 1 exit 1
fi fi
if [[ -z "$release_tag" ]]; then
echo "Could not determine release tag" >&2
exit 1
fi
prefetch_hash() { prefetch_hash() {
local url="$1" local url="$1"
local attempt local attempt
@@ -77,35 +67,24 @@ prefetch_hash() {
release_url() { release_url() {
local asset="$1" local asset="$1"
echo "https://github.com/$REPO/releases/download/$release_tag/$asset" echo "https://github.com/$REPO/releases/download/v$version/$asset"
} }
source_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect-$version.tar.gz")")" source_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect-$version.tar.gz")")"
gpgui_x86_64_hash="$(prefetch_hash "$(release_url "gpgui_x86_64.bin.tar.xz")")" gpgui_x86_64_hash="$(prefetch_hash "$(release_url "gpgui_x86_64.bin.tar.xz")")"
gpgui_aarch64_hash="$(prefetch_hash "$(release_url "gpgui_aarch64.bin.tar.xz")")" gpgui_aarch64_hash="$(prefetch_hash "$(release_url "gpgui_aarch64.bin.tar.xz")")"
binary_x86_64_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect_${version}_x86_64.bin.tar.xz")")"
binary_aarch64_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect_${version}_aarch64.bin.tar.xz")")"
SOURCE_HASH="$source_hash" \ SOURCE_HASH="$source_hash" \
GPGUI_X86_64_HASH="$gpgui_x86_64_hash" \ GPGUI_X86_64_HASH="$gpgui_x86_64_hash" \
GPGUI_AARCH64_HASH="$gpgui_aarch64_hash" \ GPGUI_AARCH64_HASH="$gpgui_aarch64_hash" \
BINARY_X86_64_HASH="$binary_x86_64_hash" \
BINARY_AARCH64_HASH="$binary_aarch64_hash" \
RELEASE_TAG="$release_tag" \
perl -0pi -e ' perl -0pi -e '
s|(releaseTag = ")[^"]+(";)|$1 . $ENV{"RELEASE_TAG"} . $2|e; s|(url = "https://github\.com/yuezk/GlobalProtect-openconnect/releases/download/v\$\{version\}/globalprotect-openconnect-\$\{version\}\.tar\.gz";\n\s*hash = ")[^"]+(";)|$1 . $ENV{"SOURCE_HASH"} . $2|e;
s|(url = "https://github\.com/yuezk/GlobalProtect-openconnect/releases/download/\$\{releaseTag\}/globalprotect-openconnect-\$\{version\}\.tar\.gz";\n\s*hash = ")[^"]+(";)|$1 . $ENV{"SOURCE_HASH"} . $2|e; s|(x86_64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_X86_64_HASH"} . $2|e;
s|(gpguiHashes = \{\n\s*x86_64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_X86_64_HASH"} . $2|e; s|(aarch64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_AARCH64_HASH"} . $2|e;
s|(gpguiHashes = \{\n\s*x86_64 = "[^"]+";\n\s*aarch64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_AARCH64_HASH"} . $2|e;
s|(binaryHashes = \{\n\s*x86_64 = ")[^"]+(";)|$1 . $ENV{"BINARY_X86_64_HASH"} . $2|e;
s|(binaryHashes = \{\n\s*x86_64 = "[^"]+";\n\s*aarch64 = ")[^"]+(";)|$1 . $ENV{"BINARY_AARCH64_HASH"} . $2|e;
' "$FLAKE_FILE" ' "$FLAKE_FILE"
grep -F "$source_hash" "$FLAKE_FILE" > /dev/null grep -F "$source_hash" "$FLAKE_FILE" > /dev/null
grep -F "$gpgui_x86_64_hash" "$FLAKE_FILE" > /dev/null grep -F "$gpgui_x86_64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$gpgui_aarch64_hash" "$FLAKE_FILE" > /dev/null grep -F "$gpgui_aarch64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$binary_x86_64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$binary_aarch64_hash" "$FLAKE_FILE" > /dev/null
grep -F "releaseTag = \"$release_tag\";" "$FLAKE_FILE" > /dev/null
echo "Updated flake.nix hashes for v$version assets from $release_tag" echo "Updated flake.nix hashes for v$version"