Compare commits

...
Author SHA1 Message Date
Kevin Yue 912842e69b fix: log the number of gateways found in portal config 2026-05-13 09:05:58 +08:00
Kevin Yue 771a894f5a fix: enhance route deletion logic in vpnc-script to handle multiple routes
#609
2026-05-12 21:53:00 +08:00
Kevin Yue 6ae9cc4320 ci: simplify build matrix setup in GitHub Actions workflow 2026-05-12 21:52:47 +08:00
Kevin Yue bdedc6ee66 fix: preserve webview auth session for gateway fallback 2026-05-12 08:22:19 +08:00
Kevin Yue 5974a60b59 fix: improve CSC criteria support 2026-05-11 21:38:35 +08:00
Kevin Yue 1efb9a86e6 chore: include git commit in app versions 2026-05-11 00:29:37 +08:00
Kevin Yue 1a9b6563b2 chore: log portal csc diagnostics 2026-05-11 00:01:53 +08:00
Kevin Yue 623cb8caf1 fix: support portal csc config flow 2026-05-10 15:33:04 +08:00
Kevin Yue 5169321c3a fix: default gateway context fields 2026-05-10 13:47:12 +08:00
Kevin Yue 2a046670bd fix: align gateway login context with official client 2026-05-10 13:09:54 +08:00
Kevin Yue efe1046e84 chore: log redacted SAML auth metadata 2026-05-10 11:03:43 +08:00
Kevin Yue fb0645594a fix: preserve SAML portal user auth cookie 2026-05-10 10:55:57 +08:00
Kevin Yue 7d63836e35 ci: support remote auth in docker image 2026-05-09 22:43:44 +08:00
Kevin Yue 3e23fc7d22 ci: add Alpine docker runtime libraries 2026-05-09 20:53:34 +08:00
Kevin Yue 8bf05d381e ci: dynamically link Alpine docker build 2026-05-09 20:36:24 +08:00
Kevin Yue 1ab36a1137 fix: gate gtk dependency behind tauri feature 2026-05-09 20:21:37 +08:00
Kevin Yue 18b788e664 ci: align docker packaging path 2026-05-09 20:10:24 +08:00
Kevin Yue ebadab8f06 ci: publish docker images by digest 2026-05-09 20:02:59 +08:00
Kevin Yue 81d13deaab refactor: simplify SAML browser selection 2026-05-09 09:24:26 +08:00
Kevin Yue 6f91a79081 docs: add minimal Alpine gpclient image 2026-05-09 09:04:28 +08:00
Kevin Yue 4d252fa31c ci: simplify gpgui matrix names 2026-05-09 07:45:32 +08:00
Kevin Yue 398475c649 ci: preserve gpgui check names 2026-05-09 07:41:21 +08:00
Kevin Yue 13d4aa398c ci: matrix gpgui libc builds 2026-05-09 07:38:24 +08:00
Kevin Yue 9423665fe5 ci: remove unsupported release action input 2026-05-09 01:26:26 +08:00
Kevin Yue 5e8dbfa26d ci: disambiguate APK release assets 2026-05-09 01:14:23 +08:00
github-actions[bot] d96b3f9c0d chore: update flake hashes for v2.5.4 (#607)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-08 17:03:26 +00:00
35 changed files with 2259 additions and 147 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.build
.git
.vendor
apps/gpgui-helper/node_modules
target
vendor.tar.xz
+104 -62
View File
@@ -29,19 +29,8 @@ concurrency:
cancel-in-progress: true
jobs:
setup-matrix:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Set up matrix
id: set-matrix
run: |
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "ubuntu-24.04-arm", "arch": "ubuntu-24.04-arm"}]' >> $GITHUB_OUTPUT
tarball:
runs-on: ubuntu-latest
needs: [setup-matrix]
steps:
- uses: pnpm/action-setup@v5
with:
@@ -132,12 +121,15 @@ jobs:
build-gp:
needs:
- setup-matrix
- tarball
strategy:
fail-fast: false
matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
package: [deb, rpm, pkg, apk, binary, ubuntu-rolling]
runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
@@ -179,73 +171,82 @@ jobs:
path: |
build-gp-${{ matrix.package }}/artifacts/*
build-gpgui:
needs:
- setup-matrix
build-docker-image:
strategy:
fail-fast: false
matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.os.arch }})
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: gpgui-source/gpgui
- name: Tarball
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: .
file: packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build gpgui in Docker
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:gpgui-builder-tauri2
- name: Install gpgui in Docker
run: |
cd gpgui-source
tar -xJf *.bin.tar.xz
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:gpgui-builder-tauri2 \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: artifact-gpgui-${{ matrix.os.arch }}
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
retention-days: 1
build-gpgui-musl:
needs:
- setup-matrix
build-gpgui:
strategy:
fail-fast: false
matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
libc:
- name: glibc
builder: gpgui-builder-tauri2
artifact_suffix: ""
- name: musl
builder: gpgui-alpine-builder-tauri2
artifact_suffix: "-musl"
runs-on: ${{ matrix.os.runner }}
name: build-gpgui-musl (${{ matrix.os.arch }})
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
with:
@@ -277,19 +278,19 @@ jobs:
run: |
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:gpgui-alpine-builder-tauri2
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }}
- name: Install gpgui in Docker
run: |
cd gpgui-source
tar -xJf *.bin.tar.xz
docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:gpgui-alpine-builder-tauri2 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
with:
name: artifact-gpgui-musl-${{ matrix.os.arch }}
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
@@ -302,8 +303,8 @@ jobs:
- tarball
- tarball-offline
- build-gp
- build-docker-image
- build-gpgui
- build-gpgui-musl
steps:
- name: Prepare workspace
@@ -323,9 +324,50 @@ jobs:
with:
path: gh-release/gp/.build/artifacts
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-amd64/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-ubuntu-24.04-arm/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Create GH release
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
publish-docker-image:
needs:
- build-docker-image
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
+14 -3
View File
@@ -79,13 +79,24 @@ jobs:
needs: [check, resolve-series]
name: publish-ppa (${{ matrix.series }})
runs-on: ubuntu-latest
container:
image: ubuntu:${{ matrix.series }}
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Install container tools
run: |
apt-get update
apt-get install -y ca-certificates curl gpg sudo
mkdir -p /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list
apt-get update
apt-get install -y gh
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code
+120 -1
View File
@@ -40,6 +40,11 @@ on:
description: 'Build binary package'
required: true
default: true
release-docker:
type: boolean
description: 'Publish Docker image'
required: true
default: true
gh-release:
type: boolean
description: 'Update GitHub release'
@@ -84,7 +89,7 @@ jobs:
}
const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && value)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
.map(([key, value]) => key.replace('release-', ''))
return JSON.stringify({
@@ -139,6 +144,110 @@ jobs:
path: |
build-${{ matrix.package }}/artifacts/*
build-docker-image:
needs:
- check
if: ${{ inputs.release-docker }}
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Prepare workspace
run: rm -rf docker-image && mkdir -p docker-image/source
- name: Download ${{ inputs.tag }} source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir docker-image
tar -xzf docker-image/*.tar.gz -C docker-image/source --strip-components=1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: docker-image/source
file: docker-image/source/packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
publish-docker-image:
needs:
- build-docker-image
if: ${{ inputs.release-docker }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
TAG: ${{ inputs.tag }}
run: |
VERSION="${TAG#v}"
tags=(-t "$IMAGE:$TAG")
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
tags+=(-t "$IMAGE:$VERSION" -t "$IMAGE:latest")
fi
docker buildx imagetools create "${tags[@]}" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$TAG"
gh-release:
needs:
- build
@@ -151,6 +260,16 @@ jobs:
uses: actions/download-artifact@v8
with:
path: gh-release
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/artifact-ubuntu-latest-apk/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Update release
uses: softprops/action-gh-release@v1
with:
+1
View File
@@ -8,6 +8,7 @@
.cargo
.build
SNAPSHOT
SOURCE_COMMIT
# Tauri generated files
gen
Generated
+1
View File
@@ -1702,6 +1702,7 @@ dependencies = [
"log-reload",
"machine-uid",
"md5",
"netdev",
"openssl",
"os_info",
"pem",
+12
View File
@@ -7,6 +7,16 @@ RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
SOURCE_COMMIT_VALUE := $(shell \
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
elif [ -n "$$GITHUB_SHA" ]; then \
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
elif [ -f SOURCE_COMMIT ]; then \
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
else \
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
fi)
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
@@ -55,11 +65,13 @@ clean-tarball:
rm -rf .vendor
rm -rf vendor.tar.xz
rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball
mkdir -p .cargo
mkdir -p .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build
+50 -1
View File
@@ -23,6 +23,7 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
- [Alpine Linux](#alpine-linux)
- [Gentoo](#gentoo)
- [NixOS](#nixos)
- [Official Docker Image](#official-docker-image)
- [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions)
@@ -262,6 +263,54 @@ If you want it managed as part of your NixOS system configuration, use the steps
sudo nixos-rebuild switch
```
### Official Docker Image
The official Docker image provides the CLI tools on Alpine Linux:
```bash
docker pull yuezk/globalprotect-openconnect:<version>
```
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
Run it with access to the TUN device:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
For browser authentication in a headless environment, use remote browser authentication:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
```bash
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
Alternatively, pipe `gpauth` remote-browser output into `gpclient`:
```bash
docker run --rm -it --entrypoint gpauth yuezk/globalprotect-openconnect:<version> \
<portal> --browser remote 2>/dev/null \
| docker run --rm -i --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
### Other Distributions
#### Manual Installation
@@ -318,7 +367,7 @@ This project includes a DevContainer configuration that provides a consistent, r
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
```
To build without the GUI helper run the same command as above, but with `BUILD_GUI=0` passed as an argument to `make`.
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
5. **Locate build artifacts:**
+1 -1
View File
@@ -21,7 +21,7 @@ clap.workspace = true
env_logger.workspace = true
log.workspace = true
serde_json.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tempfile.workspace = true
compile-time.workspace = true
+59
View File
@@ -1,4 +1,63 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
#[cfg(feature = "webview-auth")]
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPAUTH_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+8 -1
View File
@@ -11,7 +11,14 @@ use log::info;
use serde_json::json;
use tempfile::NamedTempFile;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)]
#[command(
+56
View File
@@ -0,0 +1,56 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
let commit = env_commit("GPCLIENT_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(&source_commit))
.or_else(|| git_commit(&repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+13 -6
View File
@@ -19,7 +19,14 @@ use crate::{
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
pub(crate) struct SharedArgs<'a> {
pub(crate) fix_openssl: bool,
@@ -147,11 +154,11 @@ fn init_logger(cli: &Cli) {
// Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = &cli.command {
let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() {
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
if !auth_data.is_empty()
&& let Ok(log_file) = File::create(temp_dir().join("gpcallback.log"))
{
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
}
+179 -13
View File
@@ -2,6 +2,7 @@ use std::{
borrow::Cow,
cell::RefCell,
fs,
str::FromStr,
sync::{Arc, Mutex},
};
@@ -13,7 +14,10 @@ use gpapi::{
clap::{ToVerboseArg, args::Os},
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login},
gateway::{
GatewayLogin, GatewayLoginContext, GatewaySelection, SessionExtensionAuth, gateway_login,
gateway_login_with_context,
},
gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
process::{
@@ -38,6 +42,56 @@ struct GatewayLoginSession {
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")]
@@ -130,6 +184,13 @@ pub(crate) struct ConnectArgs {
)]
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"
@@ -154,7 +215,6 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
default_browser: bool,
#[cfg(feature = "webview-auth")]
#[arg(
long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`.\nOr the path to the browser executable.\nUse 'remote' for headless servers.",
@@ -193,16 +253,23 @@ pub(crate) struct ConnectHandler<'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)),
}
}
@@ -235,6 +302,10 @@ impl<'a> ConnectHandler<'a> {
builder.computer(local_hostname);
}
for preference in &self.args.csc_preferences {
builder.csc_preference_override(&preference.domain, &preference.key, &preference.value);
}
builder.build()
}
@@ -295,7 +366,7 @@ impl<'a> ConnectHandler<'a> {
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)
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false, None)
.await;
}
@@ -307,7 +378,7 @@ impl<'a> ConnectHandler<'a> {
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)
.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.");
@@ -327,6 +398,11 @@ impl<'a> ConnectHandler<'a> {
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)
@@ -350,22 +426,33 @@ impl<'a> ConnectHandler<'a> {
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).await {
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 client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
return self
.connect_gateway_with_prelogin(portal, gateway, client_version, allow_extend_session)
.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 client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
self
@@ -386,6 +473,7 @@ impl<'a> ConnectHandler<'a> {
gateway: &str,
client_version: Option<&str>,
allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
@@ -395,7 +483,9 @@ impl<'a> ConnectHandler<'a> {
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let login_session = self.login_gateway(gateway, &cred, &gp_params).await?;
let login_session = self
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.await?;
self
.connect_gateway(
@@ -414,11 +504,17 @@ impl<'a> ConnectHandler<'a> {
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
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,
@@ -548,7 +644,6 @@ impl<'a> ConnectHandler<'a> {
} else {
None
};
let os_version = self.args.os_version();
let verbose = self.shared_args.verbose.to_verbose_arg();
let user_agent = self.user_agent();
@@ -557,7 +652,7 @@ impl<'a> ConnectHandler<'a> {
.saml_request(prelogin.saml_request())
.user_agent(&user_agent)
.os(self.args.os.as_str())
.os_version(Some(&os_version))
.os_version(Some(os_version))
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser)
@@ -565,10 +660,29 @@ impl<'a> ConnectHandler<'a> {
#[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(self.args.clean)
.clean(clean_auth)
.default_browser(use_default_browser);
let cred = auth_launcher.launch().await?;
@@ -679,3 +793,55 @@ fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
#[cfg(test)]
mod tests {
use 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));
}
}
+59
View File
@@ -1,3 +1,62 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPGUI_HELPER_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+8 -1
View File
@@ -7,7 +7,14 @@ use log::info;
use crate::app::App;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const GP_API_KEY: &[u8; 32] = &[0; 32];
#[derive(Parser)]
+60
View File
@@ -0,0 +1,60 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPSERVICE_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPSERVICE_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+8 -1
View File
@@ -16,7 +16,14 @@ use tokio::sync::{mpsc, watch};
use crate::{vpn_task::VpnTask, ws_server::WsServer};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)]
#[command(version = VERSION)]
+3 -2
View File
@@ -36,6 +36,7 @@ machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
netdev.workspace = true
# Optional dependencies for features
tauri = { workspace = true, optional = true }
@@ -51,10 +52,10 @@ os_info = { version = "3", default-features = false }
# Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = "0.18"
gtk = { version = "0.18", optional = true }
[features]
tauri = ["dep:tauri"]
tauri = ["dep:tauri", "dep:gtk"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
logger = ["dep:env_logger", "dep:log-reload"]
+27 -2
View File
@@ -72,7 +72,11 @@ impl SamlAuthData {
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)
let auth_data =
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?;
auth_data.log_summary("html");
Ok(auth_data)
}
Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!(
"SAML auth status: {}",
@@ -102,6 +106,7 @@ impl SamlAuthData {
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
auth_data.log_summary("gpcallback-cas");
return Ok(auth_data);
}
@@ -122,9 +127,28 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
fn log_summary(&self, source: &str) {
info!(
"Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}",
source,
!self.username.is_empty(),
optional_len(self.prelogin_cookie.as_deref()),
optional_len(self.portal_userauthcookie.as_deref()),
optional_len(self.token.as_deref())
);
}
}
fn optional_len(value: Option<&str>) -> usize {
value.unwrap_or_default().len()
}
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
@@ -160,11 +184,12 @@ mod tests {
#[test]
fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHBvcnRhbC11c2VyYXV0aGNvb2tpZT5wb3J0YWwtdXNlcmF1dGhjb29raWU8L3BvcnRhbC11c2VyYXV0aGNvb2tpZT48c2FtbC11c2VybmFtZT54eXpAZW1haWwuY29tPC9zYW1sLXVzZXJuYW1lPjxzYW1sLXNsbz5ubzwvc2FtbC1zbG8+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie"));
}
}
+60 -3
View File
@@ -41,14 +41,21 @@ impl From<&CachedCredential> for PasswordCredential {
pub struct PreloginCredential {
username: String,
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
}
impl PreloginCredential {
pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self {
pub fn new(
username: &str,
prelogin_cookie: Option<&str>,
portal_userauthcookie: Option<&str>,
token: Option<&str>,
) -> Self {
Self {
username: username.to_string(),
prelogin_cookie: prelogin_cookie.map(|s| s.to_string()),
portal_userauthcookie: portal_userauthcookie.map(|s| s.to_string()),
token: token.map(|s| s.to_string()),
}
}
@@ -61,6 +68,10 @@ impl PreloginCredential {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
@@ -70,9 +81,10 @@ impl From<SamlAuthData> for PreloginCredential {
fn from(value: SamlAuthData) -> Self {
let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie();
let portal_userauthcookie = value.portal_userauthcookie();
let token = value.token();
Self::new(&username, prelogin_cookie, token)
Self::new(&username, prelogin_cookie, portal_userauthcookie, token)
}
}
@@ -186,7 +198,13 @@ impl Credential {
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()),
Credential::Prelogin(cred) => (
None,
cred.prelogin_cookie(),
cred.portal_userauthcookie(),
None,
cred.token(),
),
Credential::AuthCookie(cred) => (
None,
None,
@@ -255,3 +273,42 @@ impl From<&CachedCredential> for Credential {
Self::Cached(value.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prelogin_credential_params_include_saml_cookies() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
Some("portal-userauthcookie".to_string()),
)
.unwrap();
let cred = Credential::from(auth_data);
let params = cred.to_params();
assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(params.get("passwd"), Some(&""));
assert_eq!(params.get("prelogin-cookie"), Some(&"prelogin-cookie"));
assert_eq!(params.get("portal-userauthcookie"), Some(&"portal-userauthcookie"));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
}
#[test]
fn prelogin_credential_params_keep_cas_token_without_cookies() {
let auth_data =
SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap();
let cred = Credential::from(auth_data);
let params = cred.to_params();
assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(params.get("prelogin-cookie"), Some(&""));
assert_eq!(params.get("portal-userauthcookie"), Some(&""));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
assert_eq!(params.get("token"), Some(&"cas-token"));
}
}
+138 -6
View File
@@ -1,4 +1,4 @@
use std::{borrow::Cow, collections::HashMap};
use std::{borrow::Cow, collections::HashMap, net::UdpSocket};
use anyhow::bail;
use log::{debug, info, warn};
@@ -9,6 +9,7 @@ use xmltree::Element;
use crate::{
credential::Credential,
error::PortalError,
gateway::GatewayLoginContext,
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
@@ -19,7 +20,16 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
gateway_login_with_options(gateway, cred, gp_params, None, false).await
}
pub async fn gateway_login_with_context(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: &GatewayLoginContext,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
}
pub async fn gateway_login_with_extend_lifetime(
@@ -27,13 +37,14 @@ pub async fn gateway_login_with_extend_lifetime(
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
gateway_login_with_options(gateway, cred, gp_params, None, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
@@ -42,9 +53,23 @@ async fn gateway_login_with_options(
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime);
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host()))
});
let params = build_gateway_login_params(
&gateway,
cred,
gp_params,
context,
client_ip.as_deref(),
extend_lifetime,
);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref());
let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
@@ -84,6 +109,8 @@ 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
@@ -100,6 +127,30 @@ fn build_gateway_login_params(
);
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());
}
@@ -107,6 +158,31 @@ fn build_gateway_login_params(
params
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>) {
let Some(context) = context else {
return;
};
info!(
"Gateway login context: host_present={}, gateway_name_present={}, connect_method_present={}, selection_type={}, internal={}, clientgpversion_present={}, client_ip_present={}",
!context.host().is_empty(),
!context.name().is_empty(),
context.connect_method().is_some(),
context.selection().as_login_param(),
context.kind().as_login_param(),
context.client_version().is_some(),
client_ip.is_some()
);
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
@@ -193,6 +269,7 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
#[cfg(test)]
mod tests {
use super::*;
use crate::gateway::{Gateway, GatewayKind, GatewaySelection};
#[test]
fn mfa() {
@@ -210,9 +287,17 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, false);
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]
@@ -220,11 +305,58 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_login_params_include_official_context_fields() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto)
.with_connect_method(Some("on-demand"))
.with_client_version(Some("6.3.3-915"));
let params = build_gateway_login_params(
"us1.vpn.example.com",
&cred,
&gp_params,
Some(&context),
Some("192.168.0.102"),
false,
);
assert_eq!(params.get("host").map(String::as_str), Some("us1.vpn.example.com"));
assert_eq!(params.get("gw").map(String::as_str), Some("US_East"));
assert_eq!(params.get("gateway-name").map(String::as_str), Some("US_East"));
assert_eq!(params.get("connect-method").map(String::as_str), Some("on-demand"));
assert_eq!(params.get("selection-type").map(String::as_str), Some("auto"));
assert_eq!(params.get("internal").map(String::as_str), Some("no"));
assert_eq!(params.get("clientgpversion").map(String::as_str), Some("6.3.3-915"));
assert_eq!(params.get("client-ip").map(String::as_str), Some("192.168.0.102"));
assert_eq!(params.get("client-ipv6").map(String::as_str), Some(""));
}
#[test]
fn manual_gateway_selection_maps_to_manual_param() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual);
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, Some(&context), None, false);
assert_eq!(params.get("selection-type").map(String::as_str), Some("manual"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
+145
View File
@@ -23,10 +23,130 @@ pub(crate) struct PriorityRule {
pub struct Gateway {
pub(crate) name: String,
pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
pub(crate) priority: u32,
pub(crate) priority_rules: Vec<PriorityRule>,
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewayKind {
Internal,
External,
}
impl GatewayKind {
pub fn as_login_param(self) -> &'static str {
match self {
GatewayKind::Internal => "yes",
GatewayKind::External => "no",
}
}
}
impl Default for GatewayKind {
fn default() -> Self {
Self::External
}
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewaySelection {
Auto,
Manual,
}
impl GatewaySelection {
pub fn as_login_param(self) -> &'static str {
match self {
GatewaySelection::Auto => "auto",
GatewaySelection::Manual => "manual",
}
}
}
impl Default for GatewaySelection {
fn default() -> Self {
Self::Auto
}
}
#[derive(Debug, Clone)]
pub struct GatewayLoginContext {
host: String,
name: String,
kind: GatewayKind,
selection: GatewaySelection,
connect_method: Option<String>,
client_version: Option<String>,
client_ip: Option<String>,
}
impl GatewayLoginContext {
pub fn new(gateway: &Gateway, selection: GatewaySelection) -> Self {
let name = if gateway.name().is_empty() {
gateway.server()
} else {
gateway.name()
};
Self {
host: gateway.server().to_string(),
name: name.to_string(),
kind: gateway.kind(),
selection,
connect_method: None,
client_version: None,
client_ip: None,
}
}
pub fn with_connect_method(mut self, connect_method: Option<&str>) -> Self {
self.connect_method = connect_method.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_version(mut self, client_version: Option<&str>) -> Self {
self.client_version = client_version.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_ip(mut self, client_ip: Option<String>) -> Self {
self.client_ip = client_ip.filter(|s| !s.is_empty());
self
}
pub(crate) fn host(&self) -> &str {
&self.host
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn kind(&self) -> GatewayKind {
self.kind
}
pub(crate) fn selection(&self) -> GatewaySelection {
self.selection
}
pub(crate) fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub(crate) fn client_version(&self) -> Option<&str> {
self.client_version.as_deref()
}
pub(crate) fn client_ip(&self) -> Option<&str> {
self.client_ip.as_deref()
}
}
impl Display for Gateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.name, self.address)
@@ -38,6 +158,7 @@ impl Gateway {
Self {
name,
address,
kind: GatewayKind::External,
priority: 0,
priority_rules: vec![],
}
@@ -50,4 +171,28 @@ impl Gateway {
pub fn server(&self) -> &str {
&self.address
}
pub fn kind(&self) -> GatewayKind {
self.kind
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_gateway_without_kind_as_external() {
let gateway: Gateway = serde_json::from_str(
r#"{
"name": "US East",
"address": "us-east.example.com",
"priority": 1,
"priorityRules": []
}"#,
)
.unwrap();
assert_eq!(gateway.kind(), GatewayKind::External);
}
}
+63 -4
View File
@@ -3,21 +3,28 @@ use xmltree::Element;
use crate::utils::xml::ElementExt;
use super::{Gateway, PriorityRule};
use super::{Gateway, GatewayKind, PriorityRule};
pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?;
let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways...");
node_gateways.descendant("internal").and_then(|n| n.child("list"))
node_gateways
.descendant("internal")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::Internal))
} else {
None
};
let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways...");
node_gateways.descendant("external").and_then(|n| n.child("list"))
node_gateways
.descendant("external")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::External))
})?;
let (gateway_list, kind) = gateway_list;
let gateways = gateway_list
.children("entry")
@@ -28,12 +35,13 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option
let priority = parse_priority(gateway_item);
let priority_rules = gateway_item
.child("priority-rule")
.map(|n| parse_priority_rules(n))
.map(parse_priority_rules)
.unwrap_or_default();
Gateway {
name,
address,
kind,
priority,
priority_rules,
}
@@ -62,3 +70,54 @@ fn parse_priority(element: &Element) -> u32 {
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_external_gateways_marks_gateway_kind() {
let xml = r#"
<policy>
<gateways>
<external>
<list>
<entry name="us1.vpn.example.com">
<description>US_East</description>
</entry>
</list>
</external>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, false).unwrap();
assert_eq!(gateways[0].name(), "US_East");
assert_eq!(gateways[0].server(), "us1.vpn.example.com");
assert_eq!(gateways[0].kind(), GatewayKind::External);
}
#[test]
fn parse_internal_gateways_marks_gateway_kind_when_preferred() {
let xml = r#"
<policy>
<gateways>
<internal>
<list>
<entry name="internal.vpn.example.com">
<description>Internal</description>
</entry>
</list>
</internal>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, true).unwrap();
assert_eq!(gateways[0].kind(), GatewayKind::Internal);
}
}
+22
View File
@@ -58,6 +58,7 @@ pub struct GpParams {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
// Used for MFA
input_str: Option<String>,
otp: Option<String>,
@@ -100,6 +101,13 @@ impl GpParams {
self.client_version.as_deref()
}
pub fn csc_preference_override(&self, domain: &str, key: &str) -> Option<&str> {
self
.csc_preference_overrides
.get(&csc_preference_key(domain, key))
.map(String::as_str)
}
pub fn set_input_str(&mut self, input_str: &str) {
self.input_str = Some(input_str.to_string());
}
@@ -152,6 +160,7 @@ pub struct GpParamsBuilder {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
}
impl GpParamsBuilder {
@@ -169,6 +178,7 @@ impl GpParamsBuilder {
certificate: Default::default(),
sslkey: Default::default(),
key_password: Default::default(),
csc_preference_overrides: Default::default(),
}
}
@@ -222,6 +232,13 @@ impl GpParamsBuilder {
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 {
GpParams {
is_gateway: self.is_gateway,
@@ -234,12 +251,17 @@ impl GpParamsBuilder {
certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(),
csc_preference_overrides: self.csc_preference_overrides.clone(),
input_str: 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()
+181 -25
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
@@ -11,9 +13,11 @@ use crate::{
error::PortalError,
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
};
use super::csc;
#[derive(Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PortalConfig {
@@ -21,6 +25,7 @@ pub struct PortalConfig {
auth_cookie: AuthCookieCredential,
config_cred: Credential,
gateways: Vec<Gateway>,
connect_method: Option<String>,
config_digest: Option<String>,
/**
* Variants:
@@ -60,6 +65,10 @@ impl PortalConfig {
self.internal_host_detection
}
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub fn version(&self) -> Option<&str> {
self.version.as_deref()
}
@@ -118,14 +127,11 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let url = format!("{}/global-protect/getconfig.esp", portal);
let client = Client::try_from(gp_params)?;
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &server);
params.insert("host", &server);
let swg_nonce = csc::swg_nonce();
let params = build_config_params(cred, gp_params, &server, &swg_nonce);
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
@@ -152,11 +158,102 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
debug!("Portal config response: {}", res_xml);
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
info!("Portal returned CSC criteria: {}", csc_criteria_summary(&root));
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml);
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root);
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root)
}
fn build_config_params<'a>(
cred: &'a Credential,
gp_params: &'a GpParams,
server: &'a str,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", server);
params.insert("host", server);
params.insert("csc-digest", "");
params.insert("config-digest", "");
params.insert("csc-support", "yes");
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
async fn retrieve_csc_config(
client: &Client,
portal: &str,
root: &Element,
username: &str,
gp_params: &GpParams,
) -> anyhow::Result<String> {
let csc_req = csc::build_csc_request(root, username, gp_params)?;
let swg_nonce = csc::swg_nonce();
let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce);
let url = format!("{}/global-protect/getconfig_csc.esp", portal);
info!("Portal CSC config request summary: {}", csc_req.summary());
info!("Portal CSC config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal CSC config error: {}", err.reason);
}
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})
}
fn redact_params(params: &HashMap<&str, &str>) -> String {
let params = params.iter().map(|(key, value)| (*key, *value)).collect::<Vec<_>>();
redact_form_params(&params)
}
fn csc_criteria_summary(root: &Element) -> String {
let auth_cookie = present(root.descendant_text("portal-csc-auth-cookie").as_deref());
let config_digest = present(root.descendant_text("config-digest").as_deref());
let custom_check_entries = root
.descendant("custom-checks")
.map(|custom_checks| custom_checks.descendants("entry").len())
.unwrap_or_default();
format!("auth_cookie={auth_cookie}, config_digest={config_digest}, custom_check_entries={custom_check_entries}")
}
fn present(value: Option<&str>) -> &'static str {
match value {
Some(value) if !value.is_empty() => "present",
_ => "empty",
}
}
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
let mut ihd_enabled = false;
let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true;
prefer_internal = internal_host_detect(&ihd_node)
prefer_internal = internal_host_detect(ihd_node)
}
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -169,9 +266,12 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
.descendant_text("portal-prelogonuserauthcookie")
.unwrap_or_default();
let config_digest = root.descendant_text("config-digest");
let connect_method = parse_connect_method(&root);
if gateways.is_empty() {
gateways.push(Gateway::new(server.to_string(), server.to_string()));
} else {
info!("Found {} gateways in portal config", gateways.len());
}
let version = root.descendant_text("version").map(|s| s.to_string());
@@ -183,6 +283,7 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie),
config_cred: cred.clone(),
gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version,
@@ -198,6 +299,13 @@ fn parse_allow_extend_session(root: &Element) -> Option<bool> {
}
}
fn parse_connect_method(root: &Element) -> Option<String> {
root
.descendant_text("connect-method")
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
}
// Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool {
let ip_info = [
@@ -208,23 +316,24 @@ fn internal_host_detect(element: &Element) -> bool {
info!("Found internal-host-detection, performing DNS lookup");
for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref()) {
if !ip_address.is_empty() && !host.is_empty() {
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
&& !ip_address.is_empty()
&& !host.is_empty()
{
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
}
}
@@ -240,6 +349,20 @@ mod tests {
Element::parse(xml.as_bytes()).unwrap()
}
#[test]
fn getconfig_params_include_csc_support_fields() {
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_config_params(&cred, &gp_params, "vpn.example.com", "123");
assert_eq!(params.get("csc-support"), Some(&"yes"));
assert_eq!(params.get("csc-digest"), Some(&""));
assert_eq!(params.get("config-digest"), Some(&""));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
assert_eq!(params.get("host"), Some(&"vpn.example.com"));
}
#[test]
fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
@@ -267,4 +390,37 @@ mod tests {
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn parses_connect_method() {
let root = parse_xml("<policy><connect-method>on-demand</connect-method></policy>");
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
}
#[test]
fn parses_csc_policy_response_as_portal_config() {
let root = parse_xml(
r#"<policy>
<portal-userauthcookie>user-cookie</portal-userauthcookie>
<portal-prelogonuserauthcookie>prelogon-cookie</portal-prelogonuserauthcookie>
<gateways>
<external>
<list>
<entry name="US_East">
<description>us1.vpn.example.com</description>
</entry>
</list>
</external>
</gateways>
</policy>"#,
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
assert_eq!(config.gateways().len(), 1);
}
}
+715
View File
@@ -0,0 +1,715 @@
use std::{
collections::HashMap,
fmt::Write,
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use xmltree::{Element, EmitterConfig, XMLNode};
use crate::{
gp_params::GpParams,
utils::{host_utils, xml::ElementExt},
};
const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__";
pub(super) struct CscRequest {
pub(super) auth_cookie: String,
pub(super) config_digest: String,
pub(super) csc_digest: String,
pub(super) csc_data: String,
summary: CscBuildSummary,
host_id: String,
serial_number: String,
}
impl CscRequest {
pub(super) fn summary(&self) -> String {
format!(
"digest_len={}, xml_len={}, plist_entries={}, plist_present={}, plist_missing={}, process_entries={}, process_present={}, process_missing={}",
self.csc_digest.len(),
self.csc_data.len(),
self.summary.plist_entries,
self.summary.plist_present,
self.summary.plist_missing,
self.summary.process_entries,
self.summary.process_present,
self.summary.process_missing,
)
}
}
#[derive(Default)]
struct CscBuildSummary {
plist_entries: usize,
plist_present: usize,
plist_missing: usize,
process_entries: usize,
process_present: usize,
process_missing: usize,
}
struct CscDataInput<'a> {
criteria: &'a Element,
auth_cookie: &'a str,
username: &'a str,
gp_params: &'a GpParams,
host_id: &'a str,
serial_number: &'a str,
csc_digest: &'a str,
}
pub(super) trait CscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String>;
fn process_exists(&self, name: &str) -> bool;
}
struct SystemCscDataReader;
impl CscDataReader for SystemCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
read_macos_preference(domain, key)
}
fn process_exists(&self, name: &str) -> bool {
linux_process_names().iter().any(|process_name| process_name == name)
}
}
pub(super) fn swg_nonce() -> String {
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis())
.unwrap_or_default();
(millis % 2_147_483_647).to_string()
}
pub(super) fn is_config_criteria(root: &Element) -> bool {
root.name == "config-criteria"
}
pub(super) fn build_csc_request(root: &Element, username: &str, gp_params: &GpParams) -> anyhow::Result<CscRequest> {
let reader = SystemCscDataReader;
build_csc_request_with_reader(root, username, gp_params, &reader)
}
pub(super) fn build_csc_request_with_reader(
root: &Element,
username: &str,
gp_params: &GpParams,
reader: &dyn CscDataReader,
) -> anyhow::Result<CscRequest> {
let auth_cookie = root
.descendant_text("portal-csc-auth-cookie")
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow::anyhow!("CSC criteria response does not contain portal-csc-auth-cookie"))?;
let config_digest = root.descendant_text("config-digest").unwrap_or_default();
let host_id = collect_host_id(gp_params);
let serial_number = collect_serial_number();
let mut summary = CscBuildSummary::default();
let csc_data = build_csc_data(
CscDataInput {
criteria: root,
auth_cookie: &auth_cookie,
username,
gp_params,
host_id: &host_id,
serial_number: &serial_number,
csc_digest: DIGEST_PLACEHOLDER,
},
reader,
&mut summary,
)?;
let csc_digest = pan_md5_hex(csc_data.as_bytes());
let csc_data = csc_data.replace(DIGEST_PLACEHOLDER, &csc_digest);
Ok(CscRequest {
auth_cookie,
config_digest,
csc_digest,
csc_data,
summary,
host_id,
serial_number,
})
}
pub(super) fn csc_params<'a>(
req: &'a CscRequest,
username: &'a str,
gp_params: &'a GpParams,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = HashMap::new();
params.insert("user", username);
params.insert("clientVer", "4100");
params.insert("clientos", gp_params.client_os());
params.insert("os-version", gp_params.os_version().unwrap_or_default());
params.insert("hostid", req.host_id.as_str());
params.insert("serialno", req.serial_number.as_str());
params.insert("portal-cc-auth-cookie", req.auth_cookie.as_str());
params.insert("config-digest", req.config_digest.as_str());
params.insert("csc-digest", req.csc_digest.as_str());
params.insert("csc-data", req.csc_data.as_str());
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
fn build_csc_data(
input: CscDataInput<'_>,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> anyhow::Result<String> {
let mut root = Element::new("hip-report");
push_text(&mut root, "portal-csc-auth-cookie", input.auth_cookie);
push_text(&mut root, "user-name", &urlencoding::encode(input.username));
push_text(&mut root, "client-os", &client_os_report_value(input.gp_params));
push_text(&mut root, "host-id", input.host_id);
push_text(&mut root, "device-serial-number", input.serial_number);
push_text(&mut root, "csc-digest", input.csc_digest);
root.children.push(XMLNode::Element(Element::new("categories")));
root.children.push(XMLNode::Element(build_custom_checks(
input.criteria,
input.gp_params,
reader,
summary,
)));
let mut bytes = Vec::new();
root.write_with_config(
&mut bytes,
EmitterConfig::new()
.perform_indent(true)
.write_document_declaration(true),
)?;
String::from_utf8(bytes).map_err(Into::into)
}
fn build_custom_checks(
criteria: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut custom_checks = Element::new("custom-checks");
let Some(requested_checks) = criteria.descendant("custom-checks") else {
return custom_checks;
};
if gp_params.client_os() == "Mac"
&& let Some(plist) = requested_checks
.child("mac-os")
.and_then(|mac_os| mac_os.child("plist"))
{
custom_checks
.children
.push(XMLNode::Element(build_plist_checks(plist, gp_params, reader, summary)));
}
if gp_params.client_os() == "Linux"
&& let Some(process_list) = requested_checks
.child("linux")
.and_then(|linux| linux.child("process-list"))
.or_else(|| requested_checks.child("process-list"))
{
custom_checks.children.push(XMLNode::Element(build_process_list_checks(
process_list,
reader,
summary,
)));
}
custom_checks
}
fn build_plist_checks(
plist: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("plist");
for entry in plist.children("entry") {
let domain = entry.attr("name").unwrap_or_default();
let mut out_entry = Element::new("entry");
out_entry.attributes.insert("name".to_string(), domain.to_string());
let keys = plist_entry_keys(entry);
let values: Vec<_> = keys
.iter()
.map(|key| {
let value = gp_params
.csc_preference_override(domain, key)
.map(str::to_string)
.or_else(|| reader.read_preference(domain, key));
(key.as_str(), value)
})
.collect();
let plist_exists = values.iter().any(|(_, value)| value.is_some());
summary.plist_entries += keys.len();
summary.plist_present += values.iter().filter(|(_, value)| value.is_some()).count();
summary.plist_missing += values.iter().filter(|(_, value)| value.is_none()).count();
push_text(&mut out_entry, "exist", yes_no(plist_exists));
push_text(&mut out_entry, "value", "");
let mut preference_value = Element::new("preference-value");
for (key, value) in values {
let mut pref_entry = Element::new("entry");
pref_entry.attributes.insert("name".to_string(), key.to_string());
push_text(&mut pref_entry, "exist", yes_no(value.is_some()));
push_text(&mut pref_entry, "value", value.as_deref().unwrap_or_default());
preference_value.children.push(XMLNode::Element(pref_entry));
}
out_entry.children.push(XMLNode::Element(preference_value));
out.children.push(XMLNode::Element(out_entry));
}
out
}
fn build_process_list_checks(
process_list: &Element,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("process-list");
for process_name in process_list_names(process_list) {
let exists = reader.process_exists(&process_name);
summary.process_entries += 1;
if exists {
summary.process_present += 1;
} else {
summary.process_missing += 1;
}
let mut entry = Element::new("entry");
entry.attributes.insert("name".to_string(), process_name.clone());
push_text(&mut entry, "exist", yes_no(exists));
push_text(&mut entry, "value", if exists { &process_name } else { "" });
out.children.push(XMLNode::Element(entry));
}
out
}
fn plist_entry_keys(entry: &Element) -> Vec<String> {
let keys: Vec<String> = entry
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.to_string())
.collect();
if keys.is_empty() {
entry
.attr("name")
.map(|name| vec![name.to_string()])
.unwrap_or_default()
} else {
keys
}
}
fn process_list_names(process_list: &Element) -> Vec<String> {
let mut names: Vec<String> = process_list
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.collect();
names.extend(
process_list
.children("entry")
.into_iter()
.filter_map(|entry| entry.attr("name"))
.map(str::to_string),
);
names.sort();
names.dedup();
names
}
fn pan_md5_hex(value: &[u8]) -> String {
let digest = md5::compute(value);
let mut out = String::new();
for byte in digest.0 {
write!(&mut out, "{:x}", byte).expect("writing to String should not fail");
}
out
}
fn collect_host_id(gp_params: &GpParams) -> String {
match gp_params.client_os() {
"Mac" => netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.unwrap_or_default(),
"Windows" => host_utils::get_machine_id().to_string(),
_ => host_utils::derive_uuid(&[]),
}
}
fn collect_serial_number() -> String {
collect_macos_serial_number()
.or_else(collect_linux_serial_number)
.or_else(collect_windows_serial_number)
.unwrap_or_default()
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.into_iter()
.filter_map(|path| fs::read_to_string(path).ok())
.map(|value| value.trim().to_string())
.find(|value| !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M.")
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn read_macos_preference(domain: &str, key: &str) -> Option<String> {
if cfg!(not(target_os = "macos")) {
return None;
}
let output = Command::new("defaults").args(["read", domain, key]).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn linux_process_names() -> Vec<String> {
let Ok(entries) = fs::read_dir("/proc") else {
return Vec::new();
};
entries
.filter_map(Result::ok)
.filter_map(|entry| {
entry
.file_name()
.to_str()
.filter(|name| name.chars().all(|ch| ch.is_ascii_digit()))
.map(|_| entry.path().join("stat"))
})
.filter_map(|path| fs::read_to_string(path).ok())
.filter_map(|stat| {
let start = stat.find('(')?;
let end = stat.rfind(')')?;
stat.get(start + 1..end).map(str::to_string)
})
.filter(|name| !name.is_empty())
.collect()
}
fn client_os_report_value(gp_params: &GpParams) -> String {
gp_params
.os_version()
.unwrap_or_else(|| gp_params.client_os())
.replace(' ', "+")
}
fn push_text(parent: &mut Element, name: &str, value: &str) {
let mut element = Element::new(name);
element.children.push(XMLNode::Text(value.to_string()));
parent.children.push(XMLNode::Element(element));
}
fn yes_no(value: bool) -> &'static str {
if value { "yes" } else { "no" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gp_params::{ClientOs, GpParams};
struct TestCscDataReader {
values: HashMap<String, String>,
processes: Vec<String>,
}
impl CscDataReader for TestCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
self.values.get(&format!("{domain}:{key}")).cloned()
}
fn process_exists(&self, name: &str) -> bool {
self.processes.iter().any(|process| process == name)
}
}
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
fn gp_params(client_os: ClientOs) -> GpParams {
GpParams::builder()
.client_os(client_os)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.build()
}
#[test]
fn detects_config_criteria_response() {
assert!(is_config_criteria(&parse_xml("<config-criteria/>")));
assert!(!is_config_criteria(&parse_xml("<policy/>")));
}
#[test]
fn builds_macos_plist_csc_report_with_existing_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings">
<key><member>ExampleKey</member></key>
</entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([(
"com.example.settings:ExampleKey".to_string(),
"ExampleValue".to_string(),
)]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "[email protected]", &gp_params(ClientOs::Mac), &reader).unwrap();
assert_eq!(req.auth_cookie, "cookie");
assert!(req.csc_data.contains("<user-name>alice%40example.com</user-name>"));
assert!(req.csc_data.contains("<client-os>Apple+Mac+OS+X+26.4.1</client-os>"));
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
#[test]
fn reports_missing_macos_plist_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>Missing</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
assert!(req.csc_data.contains("<exist>no</exist>"));
assert!(req.csc_data.contains("<value />") || req.csc_data.contains("<value></value>"));
}
#[test]
fn macos_plist_override_works_without_native_preference() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings"><key><member>ExampleKey</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = GpParams::builder()
.client_os(ClientOs::Mac)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.csc_preference_override("com.example.settings", "ExampleKey", "ExampleValue")
.build();
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
}
#[test]
fn unsupported_client_os_ignores_macos_plist_branch() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>HipID</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([("com.example:HipID".to_string(), "present".to_string())]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(!req.csc_data.contains("<plist>"));
assert!(!req.csc_data.contains("<exist>no</exist>"));
assert!(!req.csc_data.contains("present"));
}
#[test]
fn builds_linux_process_list_report() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<linux>
<process-list>
<entry name="present-process" />
<entry name="missing-process" />
</process-list>
</linux>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: vec!["present-process".to_string()],
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(req.csc_data.contains(r#"<entry name="present-process">"#));
assert!(req.csc_data.contains("<value>present-process</value>"));
assert!(req.csc_data.contains(r#"<entry name="missing-process">"#));
assert!(req.summary().contains("process_entries=2"));
assert!(req.summary().contains("process_present=1"));
assert!(req.summary().contains("process_missing=1"));
}
#[test]
fn uses_pan_non_padded_md5_digest() {
assert_eq!(pan_md5_hex(b""), "d41d8cd98f0b24e980998ecf8427e");
assert_ne!(pan_md5_hex(b""), format!("{:x}", md5::compute(b"")));
}
#[test]
fn builds_getconfig_csc_params() {
let req = CscRequest {
auth_cookie: "cookie".to_string(),
config_digest: "config-digest".to_string(),
csc_digest: "csc-digest".to_string(),
csc_data: "<hip-report><host-id>host</host-id><device-serial-number>serial</device-serial-number></hip-report>"
.to_string(),
summary: CscBuildSummary::default(),
host_id: "host".to_string(),
serial_number: "serial".to_string(),
};
let nonce = "123";
let gp_params = gp_params(ClientOs::Mac);
let params = csc_params(&req, "alice", &gp_params, nonce);
assert_eq!(params.get("user"), Some(&"alice"));
assert_eq!(params.get("hostid"), Some(&"host"));
assert_eq!(params.get("serialno"), Some(&"serial"));
assert_eq!(params.get("portal-cc-auth-cookie"), Some(&"cookie"));
assert_eq!(params.get("config-digest"), Some(&"config-digest"));
assert_eq!(params.get("csc-digest"), Some(&"csc-digest"));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
}
#[test]
fn generated_getconfig_csc_params_include_final_digest_and_data() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks />
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = gp_params(ClientOs::Linux);
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
let params = csc_params(&req, "alice", &gp_params, "123");
assert_eq!(params.get("csc-digest"), Some(&req.csc_digest.as_str()));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
}
+1
View File
@@ -1,4 +1,5 @@
mod config;
mod csc;
mod prelogin;
pub use config::*;
+54
View File
@@ -123,6 +123,46 @@ pub fn redact_uri(uri: &str) -> String {
url.to_string()
}
pub fn redact_form_params(params: &[(&str, &str)]) -> String {
let mut pairs = params
.iter()
.map(|(key, value)| (*key, redact_form_value(key, value)))
.collect::<Vec<_>>();
pairs.sort_by(|(left, _), (right, _)| left.cmp(right));
form_urlencoded::Serializer::new(String::new())
.extend_pairs(pairs)
.finish()
}
fn redact_form_value(key: &str, value: &str) -> String {
if value.is_empty() || is_safe_form_param(key) {
return value.to_string();
}
format!("redacted-{}", value.len())
}
fn is_safe_form_param(key: &str) -> bool {
matches!(
key,
"clientVer"
| "clientos"
| "config-digest"
| "csc-digest"
| "csc-support"
| "direct"
| "ipv6-support"
| "jnlpReady"
| "ok"
| "os-version"
| "prot"
| "swg-auth-token"
| "swg-nonce"
)
}
fn redact_query(query: Option<&str>) -> Option<String> {
let query = query?;
@@ -190,6 +230,20 @@ mod tests {
assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x");
}
#[test]
fn it_should_redact_form_params() {
let params = [
("portal-userauthcookie", "secret-cookie"),
("csc-support", "yes"),
("prelogin-cookie", ""),
];
assert_eq!(
redact_form_params(&params),
"csc-support=yes&portal-userauthcookie=redacted-13&prelogin-cookie="
);
}
#[test]
fn it_should_redact_data_uri() {
let uri = "data:text/plain;a";
+4 -4
View File
@@ -46,10 +46,10 @@ impl ElementExt for Element {
}
for child in &self.children {
if let Some(element) = child.as_element() {
if let Some(found) = element.descendant(name) {
return Some(found);
}
if let Some(element) = child.as_element()
&& let Some(found) = element.descendant(name)
{
return Some(found);
}
}
+9 -5
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)
.expect("Failed to read patches directory")
.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");
// The temporary location where we will build
@@ -89,7 +93,7 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
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 patches_dir = deps_dir.join("patches");
@@ -200,6 +204,6 @@ fn main() {
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include(&oc_dst.join("include"))
.include(oc_dst.join("include"))
.compile("vpn");
}
+2 -2
View File
@@ -44,11 +44,11 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
}
pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(&VPNC_SCRIPT_LOCATIONS)
find_executable(VPNC_SCRIPT_LOCATIONS)
}
pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(&CSD_WRAPPER_LOCATIONS)
find_executable(CSD_WRAPPER_LOCATIONS)
}
/// If file exists, check if it is executable
+3 -3
View File
@@ -35,7 +35,7 @@
src = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/globalprotect-openconnect-${version}.tar.gz";
hash = "sha256-KgmWKp04jXsQuptXbxAdRP92Bgn46cm8+PboJ+lRc20=";
hash = "sha256-NS3tIZxkT9A4eqmfkcl29bHHJrrgVs/XSQBOz99cP30=";
};
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
@@ -43,8 +43,8 @@
gpgui = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/gpgui_${cpu}.bin.tar.xz";
hash = {
x86_64 = "sha256-hBiEreTOqfCudXNM4FZnQEdUT3mHenTodqGONx03YUA=";
aarch64 = "sha256-9gLCRE0gA0PxX4yKoV51aiJa31VuAGiHck429iMY7rA=";
x86_64 = "sha256-1XBdrKJOhSViZOgfqohZjdzV6qzx/qpy0yhkbZ8DumA=";
aarch64 = "sha256-humujgf/M31SkBABc14g/ujjacGHxqElzNuCClhTAfA=";
}.${cpu};
};
in
+68
View File
@@ -0,0 +1,68 @@
# syntax=docker/dockerfile:1
ARG ALPINE_VERSION=3.23
ARG RUST_VERSION=1.89
FROM rust:${RUST_VERSION}-alpine AS builder
WORKDIR /src
RUN apk add --no-cache \
autoconf \
automake \
build-base \
file \
gettext-dev \
gmp-dev \
gnutls-dev \
libtool \
libxml2-dev \
linux-headers \
lz4-dev \
make \
nettle-dev \
openssl-dev \
p11-kit-dev \
patch \
pkgconf \
zlib-dev
COPY . .
RUN RUSTFLAGS="-C target-feature=-crt-static" \
make build \
BUILD_GUI_HELPER=0 \
INCLUDE_GUI=0 \
LIBXML2_STATIC=1
RUN install -Dm755 target/release/gpclient /out/usr/bin/gpclient \
&& install -Dm755 target/release/gpauth /out/usr/bin/gpauth \
&& install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script /out/usr/libexec/gpclient/vpnc-script \
&& install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh /out/usr/libexec/gpclient/hipreport.sh
FROM alpine:${ALPINE_VERSION}
ENV SUDO_UID=1000 \
HOME=/root
RUN apk add --no-cache \
ca-certificates \
gmp \
gnutls \
iproute2 \
iputils \
libgcc \
libxml2 \
lz4-libs \
nettle \
openssl \
p11-kit \
zlib \
&& addgroup -g 1000 gp \
&& adduser -D -u 1000 -G gp gp \
&& update-ca-certificates
COPY --from=builder /out/ /
ENTRYPOINT ["gpclient"]
CMD ["--help"]
@@ -336,7 +336,11 @@ if [ -n "$IPROUTE" ]; then
del_vpngateway_route() {
echo "$VPNGATEWAY" | grep -q : && FAMILY=-6 || FAMILY=-4
$IPROUTE route $route_syntax_del "$VPNGATEWAY"
# iproute2 deletes only one matching route at a time. The connect path may
# add one host route per matching uplink, so remove them until none remain.
while $IPROUTE $FAMILY route $route_syntax_del "$VPNGATEWAY" 2>/dev/null ; do
:
done
if [ $FAMILY != -4 ]; then
$IPROUTE $FAMILY route flush cache 2>/dev/null
fi