mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-17 21:56:14 -05:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
888f288c0d | ||
|
|
580b81e7bb | ||
|
|
8724ed3b37 | ||
|
|
01075cb6dc | ||
|
|
b7b708e9cd |
No files matched your search
@@ -1,30 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Logs**
|
||||
- For the GUI version, you can find the logs at `~/.local/share/gpclient/gpclient.log`
|
||||
- For the CLI version, copy the output of the `gpclient` command.
|
||||
|
||||
**Environment:**
|
||||
- OS: [e.g. Ubuntu 22.04]
|
||||
- Desktop Environment: [e.g. GNOME or KDE]
|
||||
- Output of `ps aux | grep 'gnome-keyring\|kwalletd5' | grep -v grep`: [Required for secure store error]
|
||||
- Is remote SSH? [Yes/No]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,115 @@
|
||||
name: Bug report
|
||||
description: Report a problem with GP Connect or gpclient.
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for reporting a problem. You can report against your installed version; you do not need to upgrade first.
|
||||
|
||||
Review everything before posting. Remove passwords, cookies, tokens, SAML payloads, and private VPN addresses. Do not attach a complete environment dump.
|
||||
- type: dropdown
|
||||
id: component
|
||||
attributes:
|
||||
label: Affected component
|
||||
options:
|
||||
- CLI connection
|
||||
- GP Connect GUI
|
||||
- Login window or browser authentication
|
||||
- Installation or update
|
||||
- Credential storage
|
||||
- Other or unsure
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Application version
|
||||
description: Run gpclient --version, or use the version shown in the GUI's About dialog. Include helper versions if relevant.
|
||||
placeholder: "For example: gpclient 3.0.1"
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: installation
|
||||
attributes:
|
||||
label: Installation method
|
||||
options:
|
||||
- APT
|
||||
- AUR
|
||||
- RPM package or repository
|
||||
- Nix
|
||||
- Homebrew
|
||||
- Downloaded release package
|
||||
- FreeBSD or OpenBSD package
|
||||
- Source build
|
||||
- Other or unknown
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating system and version
|
||||
description: Include the Linux distribution, macOS version, or FreeBSD/OpenBSD version, and architecture if known.
|
||||
placeholder: "For example: Fedora 43 x86_64, macOS 26 arm64, or FreeBSD 14.4 amd64"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: reproduction
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Include the exact command and options, or the GUI steps. Replace private portal names with a placeholder and omit credentials.
|
||||
placeholder: |
|
||||
1. Run sudo gpclient connect <portal> --browser
|
||||
2. ...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual behavior
|
||||
description: Describe the failure and any error message.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: regression
|
||||
attributes:
|
||||
label: Last working version and recent changes
|
||||
description: If this worked before, give the last working app version and any recent OS, desktop, graphics driver, or package updates. It is okay if you do not know.
|
||||
- type: textarea
|
||||
id: diagnostics
|
||||
attributes:
|
||||
label: Diagnostics
|
||||
description: Run gpclient diagnostics as your normal desktop user, without sudo. If the command is unavailable, use the standalone script linked below or provide the relevant information manually. Reports include raw desktop identifiers and are not guaranteed anonymous; review before posting.
|
||||
render: text
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**Older versions:** download and inspect the [standalone diagnostic script](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/scripts/collect-diagnostics.sh), then run it with `sh collect-diagnostics.sh`. See [collection instructions](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/docs/diagnostics.md). Do not pipe a download directly into a shell.
|
||||
|
||||
If you cannot run either collector, provide the relevant details below. You do not need graphics details for unrelated connection problems.
|
||||
- type: textarea
|
||||
id: rendering
|
||||
attributes:
|
||||
label: Window or rendering failures only
|
||||
description: Desktop/compositor and version; Wayland or X11; GPU and driver version; GTK/WebKitGTK version when available; VM or remote session; any rendering environment overrides. Skip for unrelated problems. The diagnostics report may already contain this information.
|
||||
- type: textarea
|
||||
id: authentication
|
||||
attributes:
|
||||
label: Authentication or credential storage failures only
|
||||
description: Embedded login window or external browser (name/version)? At what stage does it stop? For credential storage errors, include the keyring implementation or macOS Keychain error. Omit cookies, tokens, passwords, and SAML data.
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant logs
|
||||
description: For the CLI, paste relevant terminal output. For the GUI, use its built-in option to open or export logs, if available. Review and remove sensitive authentication data before posting; avoid full verbose logs unless requested.
|
||||
render: text
|
||||
- type: textarea
|
||||
id: screenshots
|
||||
attributes:
|
||||
label: Screenshots and additional context
|
||||
description: Attach screenshots if helpful. Hide private portal names, account details, and other sensitive content.
|
||||
@@ -0,0 +1,98 @@
|
||||
name: Build Linux GUI
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
required: true
|
||||
type: string
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
builder:
|
||||
required: true
|
||||
type: string
|
||||
artifact_suffix:
|
||||
default: ""
|
||||
type: string
|
||||
verify_desktop_assets:
|
||||
default: false
|
||||
type: boolean
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os:
|
||||
- runner: ubuntu-latest
|
||||
arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
arch: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.os.runner }}
|
||||
name: build (${{ matrix.os.arch }})
|
||||
steps:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9
|
||||
- name: Prepare workspace
|
||||
run: rm -rf gpgui-source && mkdir gpgui-source
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: gpgui-source/gp
|
||||
submodules: recursive
|
||||
- name: Checkout gpgui
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
repository: yuezk/gpgui
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui-source/gpgui
|
||||
- name: Verify Linux desktop assets
|
||||
if: matrix.os.arch == 'amd64' && inputs.verify_desktop_assets
|
||||
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
|
||||
- name: Tarball
|
||||
run: |
|
||||
cd gpgui-source
|
||||
tar -czf gpgui.tar.gz gpgui gp
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
docker run --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e GPGUI_BUILD_VERSION \
|
||||
-e GPGUI_UPDATE_CHANNEL \
|
||||
-e GPGUI_LICENSE_SIGNING_KEYS \
|
||||
-v "$(pwd)/gpgui-source:/workspace" "yuezk/gpdev:$GPGUI_BUILDER"
|
||||
- name: Install gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
run: |
|
||||
cd gpgui-source
|
||||
tar -xJf ./*.bin.tar.xz
|
||||
docker run --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-v "$(pwd):/workspace" "yuezk/gpdev:$GPGUI_BUILDER" \
|
||||
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
|
||||
- name: Upload gpgui
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: artifact-gpgui${{ inputs.artifact_suffix }}-${{ matrix.os.arch }}
|
||||
if-no-files-found: error
|
||||
path: |
|
||||
gpgui-source/*.bin.tar.xz
|
||||
gpgui-source/*.bin.tar.xz.sha256
|
||||
+250
-120
@@ -2,26 +2,37 @@ name: Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: 'Build channel. Stable builds require matching vX.Y.Z refs in both repositories.'
|
||||
required: true
|
||||
default: snapshot
|
||||
type: choice
|
||||
options: [snapshot, stable]
|
||||
build_only:
|
||||
description: 'Build and test artifacts without publishing releases, images, or update feeds'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
gp_branch:
|
||||
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
|
||||
description: 'GlobalProtect-openconnect ref to build (use the matching tag for stable builds)'
|
||||
required: true
|
||||
default: dev
|
||||
gpgui_branch:
|
||||
description: 'gpgui branch to use for the snapshot release'
|
||||
description: 'gpgui ref to build (use the matching tag for stable builds)'
|
||||
required: true
|
||||
default: dev
|
||||
build_macos:
|
||||
description: 'Build Apple Silicon artifacts for the snapshot release'
|
||||
description: 'Build Apple Silicon artifacts for this run'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_bsd:
|
||||
description: 'Build FreeBSD/OpenBSD packages for the snapshot release'
|
||||
description: 'Build FreeBSD/OpenBSD packages for this run'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_bsd_arm64:
|
||||
description: 'Build optional FreeBSD/OpenBSD arm64 packages for the snapshot release. Slow and disabled by default'
|
||||
description: 'Build optional FreeBSD/OpenBSD arm64 packages for this run. Slow and disabled by default'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
@@ -40,11 +51,29 @@ on:
|
||||
- v*.*.*
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && 'release' || github.ref }}
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && (inputs.build_only && github.run_id || 'release') || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/') }}
|
||||
|
||||
jobs:
|
||||
validate-inputs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Validate stable refs
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
GP_REF: ${{ inputs.gp_branch }}
|
||||
GPGUI_REF: ${{ inputs.gpgui_branch }}
|
||||
run: |
|
||||
if [[ "$EVENT" == workflow_dispatch && "$CHANNEL" == stable ]]; then
|
||||
if [[ ! "$GP_REF" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || "$GP_REF" != "$GPGUI_REF" ]]; then
|
||||
echo "Stable builds require matching vX.Y.Z refs" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
test-gp:
|
||||
needs: validate-inputs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout GlobalProtect-openconnect
|
||||
@@ -54,19 +83,35 @@ jobs:
|
||||
repository: yuezk/GlobalProtect-openconnect
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
submodules: recursive
|
||||
- name: Run Rust tests in Docker
|
||||
- name: Run Rust tests as a non-root user with focused privilege checks
|
||||
run: |
|
||||
docker run --rm \
|
||||
--user root \
|
||||
--user vscode \
|
||||
-e HOME=/home/vscode \
|
||||
-e CARGO_TARGET_DIR=/tmp/gp-test-target \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e LIBXML2_STATIC=1 \
|
||||
-e PKEXEC_UID=1000 \
|
||||
-v "$(pwd):/workspace" \
|
||||
-v "$(pwd):/workspace:ro" \
|
||||
-w /workspace \
|
||||
yuezk/gpdev:binary-builder-tauri2 \
|
||||
cargo test --workspace
|
||||
sh -ec '
|
||||
test "$(id -u)" -ne 0
|
||||
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
|
||||
cp -R /workspace /tmp/gp-test-workspace
|
||||
cd /tmp/gp-test-workspace
|
||||
cargo test --workspace --locked
|
||||
|
||||
# Exercise only the paths that require an actual root process.
|
||||
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
|
||||
process::auth_launcher::tests::custom_authenticator_crash_does_not_request_recovery -- --exact
|
||||
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
|
||||
process::collection::tests::root_owned_sticky_directories_protect_collectors_without_trusting_writable_files -- --exact
|
||||
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpservice \
|
||||
--bin gpservice device_anchor::tests
|
||||
'
|
||||
|
||||
tarball:
|
||||
needs: validate-inputs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -85,10 +130,12 @@ jobs:
|
||||
submodules: recursive
|
||||
|
||||
- name: Create tarball
|
||||
env:
|
||||
IS_SNAPSHOT: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel == 'snapshot') || (github.event_name != 'workflow_dispatch' && !startsWith(github.ref, 'refs/tags/')) }}
|
||||
run: |
|
||||
cd source/gp
|
||||
# Generate the SNAPSHOT file for non-tagged commits
|
||||
if [[ "${{ github.ref }}" != "refs/tags/"* ]]; then
|
||||
# Stable manual builds use tagged source even when dispatched from main.
|
||||
if [[ "$IS_SNAPSHOT" == true ]]; then
|
||||
touch SNAPSHOT
|
||||
fi
|
||||
make tarball
|
||||
@@ -97,7 +144,7 @@ jobs:
|
||||
|
||||
- name: Generate RPM spec file
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
run: |
|
||||
cd source/gp
|
||||
|
||||
@@ -157,7 +204,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
build-gp:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
needs:
|
||||
- tarball
|
||||
strategy:
|
||||
@@ -208,7 +255,7 @@ jobs:
|
||||
build-gp-${{ matrix.package }}/artifacts/*
|
||||
|
||||
build-docker-image:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
if: ${{ !(startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -233,11 +280,13 @@ jobs:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
- name: Login to Docker Hub
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
- name: Build and push by digest
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
@@ -245,20 +294,37 @@ jobs:
|
||||
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: Build local image for verification
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: packaging/docker/alpine/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: yuezk/globalprotect-openconnect:build-test
|
||||
load: true
|
||||
push: false
|
||||
- name: Verify CLI tools
|
||||
env:
|
||||
IMAGE: yuezk/globalprotect-openconnect
|
||||
DIGEST: ${{ steps.build.outputs.digest }}
|
||||
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
|
||||
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"'
|
||||
image_ref="$IMAGE@$DIGEST"
|
||||
if [[ "$BUILD_ONLY" == "true" ]]; then
|
||||
image_ref="$IMAGE:build-test"
|
||||
fi
|
||||
docker run --rm "$image_ref" --help
|
||||
docker run --rm --entrypoint gpauth "$image_ref" --help
|
||||
docker run --rm --entrypoint sh "$image_ref" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
|
||||
- name: Export digest
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
run: |
|
||||
mkdir -p /tmp/digests
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
- name: Upload digest
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
@@ -266,96 +332,162 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
build-gpgui:
|
||||
build-gpgui-glibc:
|
||||
needs: validate-inputs
|
||||
name: build-gpgui (glibc)
|
||||
uses: ./.github/workflows/build-gpgui-linux.yaml
|
||||
with:
|
||||
gp_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
gpgui_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
builder: gpgui-builder-tauri2
|
||||
verify_desktop_assets: true
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
|
||||
build-gpgui-musl:
|
||||
needs: validate-inputs
|
||||
name: build-gpgui (musl)
|
||||
uses: ./.github/workflows/build-gpgui-linux.yaml
|
||||
with:
|
||||
gp_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
gpgui_ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
builder: gpgui-alpine-builder-tauri2
|
||||
artifact_suffix: -musl
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
|
||||
nix-source:
|
||||
needs: [build-gpgui-glibc]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
arch: amd64
|
||||
system: x86_64-linux
|
||||
artifact_arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
arch: ubuntu-24.04-arm
|
||||
libc:
|
||||
- name: glibc
|
||||
builder: gpgui-builder-tauri2
|
||||
artifact_suffix: ""
|
||||
- name: musl
|
||||
builder: gpgui-alpine-builder-tauri2
|
||||
artifact_suffix: "-musl"
|
||||
runs-on: ${{ matrix.os.runner }}
|
||||
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }})
|
||||
system: aarch64-linux
|
||||
artifact_arch: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
name: nix-source (${{ matrix.platform.system }})
|
||||
env:
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
NIXPKGS: locked
|
||||
steps:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9
|
||||
- name: Prepare workspace
|
||||
run: rm -rf gpgui-source && mkdir gpgui-source
|
||||
- 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
|
||||
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: Verify Linux desktop assets
|
||||
if: matrix.os.arch == 'amd64' && matrix.libc.name == 'glibc'
|
||||
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
|
||||
- name: Tarball
|
||||
run: |
|
||||
cd gpgui-source
|
||||
tar -czf gpgui.tar.gz gpgui gp
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
docker run --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-e GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }} \
|
||||
-e GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }} \
|
||||
-e GPGUI_LICENSE_SIGNING_KEYS \
|
||||
-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 --rm \
|
||||
-e COREPACK_INTEGRITY_KEYS=0 \
|
||||
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \
|
||||
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
|
||||
- name: Upload gpgui
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }}
|
||||
if-no-files-found: error
|
||||
path: |
|
||||
gpgui-source/*.bin.tar.xz
|
||||
gpgui-source/*.bin.tar.xz.sha256
|
||||
- name: Checkout source and dependencies
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
submodules: recursive
|
||||
path: gp
|
||||
- name: Download current GUI artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: artifact-gpgui-${{ matrix.platform.artifact_arch }}
|
||||
path: nix-artifacts/gui
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
- name: Configure current source and GUI inputs
|
||||
run: |
|
||||
echo "GP_SOURCE=$PWD/gp" >> "$GITHUB_ENV"
|
||||
gui_archive=$(find "$PWD/nix-artifacts/gui" -name '*.bin.tar.xz' -type f)
|
||||
test -f "$gui_archive"
|
||||
echo "GP_GUI_ARCHIVE=$gui_archive" >> "$GITHUB_ENV"
|
||||
- name: Build source package
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix source \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
bash gp/scripts/tests/nix-desktop-authorization.sh result
|
||||
- name: Test source runtime in NixOS
|
||||
if: matrix.platform.system == 'x86_64-linux'
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix runtime-source \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
|
||||
nix-prebuilt:
|
||||
needs: [build-gp, build-gpgui-glibc]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- runner: ubuntu-latest
|
||||
system: x86_64-linux
|
||||
artifact_arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
system: aarch64-linux
|
||||
artifact_arch: ubuntu-24.04-arm
|
||||
nixpkgs: [locked, nixos-25.11, nixos-26.05, nixpkgs-unstable]
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
name: nix-prebuilt (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
|
||||
env:
|
||||
NIX_SYSTEM: ${{ matrix.platform.system }}
|
||||
NIXPKGS: ${{ matrix.nixpkgs }}
|
||||
steps:
|
||||
- name: Checkout packaging and tests
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
|
||||
submodules: recursive
|
||||
path: gp
|
||||
- name: Download current Linux binary artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: artifact-gp-binary-${{ matrix.platform.artifact_arch }}
|
||||
path: nix-artifacts/binaries
|
||||
- name: Download current GUI artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: artifact-gpgui-${{ matrix.platform.artifact_arch }}
|
||||
path: nix-artifacts/gui
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
- name: Configure current artifact inputs
|
||||
run: |
|
||||
echo "GP_SOURCE=$PWD/gp" >> "$GITHUB_ENV"
|
||||
binary_archive=$(find "$PWD/nix-artifacts/binaries" -name '*.bin.tar.xz' -type f)
|
||||
gui_archive=$(find "$PWD/nix-artifacts/gui" -name '*.bin.tar.xz' -type f)
|
||||
test -f "$binary_archive"
|
||||
test -f "$gui_archive"
|
||||
echo "GP_BINARY_ARCHIVE=$binary_archive" >> "$GITHUB_ENV"
|
||||
echo "GP_GUI_ARCHIVE=$gui_archive" >> "$GITHUB_ENV"
|
||||
- name: Build package through host NixOS module
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix module \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
bash gp/scripts/tests/nix-desktop-authorization.sh result
|
||||
- name: Build standalone prebuilt package
|
||||
if: matrix.nixpkgs == 'locked'
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
- name: Test prebuilt runtime in NixOS
|
||||
if: matrix.nixpkgs == 'locked' && matrix.platform.system == 'x86_64-linux'
|
||||
run: |
|
||||
nix build --impure --file gp/nix/ci.nix runtime-prebuilt \
|
||||
--extra-experimental-features "nix-command flakes" --print-build-logs
|
||||
|
||||
trigger-gpgui-macos:
|
||||
if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.build_macos) }}
|
||||
needs: test-gp
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_macos) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_MACOS_ON_TAG == 'true') }}
|
||||
permissions:
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
name: trigger private macOS release
|
||||
name: trigger private macOS build
|
||||
outputs:
|
||||
run_id: ${{ steps.dispatch.outputs.run_id }}
|
||||
run_url: ${{ steps.dispatch.outputs.run_url }}
|
||||
steps:
|
||||
- name: Dispatch private macOS release
|
||||
- name: Dispatch private macOS build
|
||||
id: dispatch
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
||||
PUBLIC_GH_TOKEN: ${{ github.token }}
|
||||
CHANNEL: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
CHANNEL: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
GP_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref_name }}
|
||||
GPGUI_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
@@ -378,7 +510,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
expected_title="macOS $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
|
||||
expected_title="macOS build $CHANNEL $RELEASE_TAG ($REQUEST_ID)"
|
||||
jq -n \
|
||||
--arg workflow_ref "$GPGUI_REF" \
|
||||
--arg request_id "$REQUEST_ID" \
|
||||
@@ -398,14 +530,14 @@ jobs:
|
||||
gpgui_ref: $gpgui_ref
|
||||
}
|
||||
}' | gh api --method POST \
|
||||
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
|
||||
repos/yuezk/gpgui/actions/workflows/build-macos.yaml/dispatches \
|
||||
--input -
|
||||
|
||||
run_id=""
|
||||
run_url=""
|
||||
for _ in {1..40}; do
|
||||
runs="$(gh api \
|
||||
'repos/yuezk/gpgui/actions/workflows/release-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
|
||||
'repos/yuezk/gpgui/actions/workflows/build-macos.yaml/runs?event=workflow_dispatch&per_page=50')"
|
||||
run_id="$(jq -r --arg title "$expected_title" \
|
||||
'[.workflow_runs[] | select(.display_title == $title)] | first | .id // empty' \
|
||||
<<<"$runs")"
|
||||
@@ -427,6 +559,7 @@ jobs:
|
||||
exit 1
|
||||
|
||||
setup-bsd-matrix:
|
||||
needs: validate-inputs
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
enabled: ${{ steps.matrix.outputs.enabled }}
|
||||
@@ -435,7 +568,7 @@ jobs:
|
||||
- name: Build matrix
|
||||
id: matrix
|
||||
env:
|
||||
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
BUILD_BSD_ON_TAG: ${{ startsWith(github.ref, 'refs/tags/') && vars.BUILD_BSD_ON_TAG == 'true' }}
|
||||
BUILD_BSD: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd }}
|
||||
BUILD_BSD_ARM64: ${{ github.event_name == 'workflow_dispatch' && inputs.build_bsd_arm64 }}
|
||||
run: |
|
||||
@@ -443,7 +576,7 @@ jobs:
|
||||
import json
|
||||
import os
|
||||
|
||||
build_bsd = os.environ["IS_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
|
||||
build_bsd = os.environ["BUILD_BSD_ON_TAG"] == "true" or os.environ["BUILD_BSD"] == "true"
|
||||
build_bsd_arm64 = os.environ["BUILD_BSD_ARM64"] == "true"
|
||||
include = []
|
||||
|
||||
@@ -570,7 +703,7 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
cd "${{ matrix.workspace }}/gp"
|
||||
@@ -627,7 +760,7 @@ jobs:
|
||||
export AUTOCONF_VERSION=2.72
|
||||
export AUTOMAKE_VERSION=1.17
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && 'snapshot' || 'stable' }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
cd "${{ matrix.workspace }}/gp"
|
||||
@@ -653,7 +786,7 @@ jobs:
|
||||
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
|
||||
|
||||
gh-release:
|
||||
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
|
||||
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/')) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
@@ -662,11 +795,15 @@ jobs:
|
||||
attestations: write
|
||||
artifact-metadata: write
|
||||
needs:
|
||||
- test-gp
|
||||
- nix-source
|
||||
- nix-prebuilt
|
||||
- tarball
|
||||
- tarball-offline
|
||||
- build-gp
|
||||
- build-docker-image
|
||||
- build-gpgui
|
||||
- build-gpgui-glibc
|
||||
- build-gpgui-musl
|
||||
- setup-bsd-matrix
|
||||
- build-gpgui-frontend
|
||||
- build-bsd
|
||||
@@ -676,7 +813,7 @@ jobs:
|
||||
env:
|
||||
NEEDS_JSON: ${{ toJson(needs) }}
|
||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
@@ -685,14 +822,14 @@ jobs:
|
||||
|
||||
needs = json.loads(os.environ["NEEDS_JSON"])
|
||||
bsd_matrix_enabled = os.environ["BSD_MATRIX_ENABLED"] == "true"
|
||||
is_tag = os.environ["IS_TAG"] == "true"
|
||||
is_stable = os.environ["IS_STABLE"] == "true"
|
||||
failed = []
|
||||
|
||||
for name, data in needs.items():
|
||||
result = data["result"]
|
||||
if result in {"failure", "cancelled"}:
|
||||
failed.append(f"{name}: {result}")
|
||||
elif name in {"build-gp", "build-docker-image"} and result == "skipped" and is_tag:
|
||||
elif name in {"build-gp", "build-docker-image", "nix-prebuilt"} and result == "skipped" and is_stable:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
@@ -736,7 +873,7 @@ jobs:
|
||||
|
||||
- name: Generate release asset checksums
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
run: |
|
||||
cd gh-release/gp
|
||||
mkdir -p .build
|
||||
@@ -758,22 +895,20 @@ jobs:
|
||||
- name: Create GH release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
run: |
|
||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||
|
||||
wait-gpgui-macos:
|
||||
if: ${{ always() && needs.trigger-gpgui-macos.result != 'skipped' }}
|
||||
needs:
|
||||
- gh-release
|
||||
- trigger-gpgui-macos
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 130
|
||||
steps:
|
||||
- name: Wait for private macOS release
|
||||
- name: Wait for private macOS build
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
|
||||
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
|
||||
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
|
||||
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
|
||||
run: |
|
||||
@@ -783,21 +918,14 @@ jobs:
|
||||
echo "The private macOS workflow was not started" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
|
||||
gh api --method POST \
|
||||
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
|
||||
echo "The public release failed; cancelled $PRIVATE_RUN_URL" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for _ in $(seq 1 480); do
|
||||
run="$(gh api "repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID")"
|
||||
status="$(jq -r '.status' <<<"$run")"
|
||||
conclusion="$(jq -r '.conclusion // ""' <<<"$run")"
|
||||
if [[ "$status" == "completed" ]]; then
|
||||
echo "Private macOS workflow completed: $PRIVATE_RUN_URL"
|
||||
echo "Private macOS build completed: $PRIVATE_RUN_URL"
|
||||
if [[ "$conclusion" != "success" ]]; then
|
||||
echo "Private macOS workflow concluded with: $conclusion" >&2
|
||||
echo "Private macOS build concluded with: $conclusion" >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
@@ -807,15 +935,17 @@ jobs:
|
||||
|
||||
gh api --method POST \
|
||||
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
|
||||
echo "Private macOS workflow timed out: $PRIVATE_RUN_URL" >&2
|
||||
echo "Private macOS build timed out: $PRIVATE_RUN_URL" >&2
|
||||
exit 1
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- test-gp
|
||||
- build-docker-image
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -833,9 +963,9 @@ jobs:
|
||||
working-directory: /tmp/digests
|
||||
env:
|
||||
IMAGE: yuezk/globalprotect-openconnect
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
run: |
|
||||
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
|
||||
$(printf "$IMAGE@sha256:%s " *)
|
||||
|
||||
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
|
||||
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$RELEASE_TAG" /tmp/digests all
|
||||
@@ -11,6 +11,18 @@ on:
|
||||
type: string
|
||||
required: true
|
||||
default: "1"
|
||||
build_id:
|
||||
description: 'Existing Copr build ID to verify; leave empty to submit a new build'
|
||||
type: string
|
||||
required: false
|
||||
distros:
|
||||
description: 'Space-separated distro releases, e.g. fedora-44 fedora-45; all configured architectures are included'
|
||||
type: string
|
||||
required: false
|
||||
|
||||
concurrency:
|
||||
group: publish-copr
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -19,9 +31,14 @@ jobs:
|
||||
publish-copr:
|
||||
runs-on: ubuntu-latest
|
||||
container: fedora:latest
|
||||
timeout-minutes: 210
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Install tools
|
||||
run: dnf install -y copr-cli gh
|
||||
run: dnf install -y copr-cli gh python3 zstd
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Check inputs
|
||||
env:
|
||||
@@ -29,14 +46,28 @@ jobs:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Revision must be a positive integer" >&2
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
|
||||
|
||||
- name: Resolve publication distros
|
||||
id: targets
|
||||
env:
|
||||
DISTROS: ${{ inputs.distros }}
|
||||
BUILD_ID: ${{ inputs.build_id }}
|
||||
run: |
|
||||
build_args=()
|
||||
if [[ -n "$BUILD_ID" ]]; then
|
||||
build_args+=(--build-id "$BUILD_ID")
|
||||
fi
|
||||
python3 scripts/select-publication-targets.py copr \
|
||||
--distros "$DISTROS" "${build_args[@]}"
|
||||
|
||||
- name: Download published spec
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
@@ -49,6 +80,7 @@ jobs:
|
||||
--dir publish-copr
|
||||
|
||||
- name: Set package revision
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
@@ -66,6 +98,7 @@ jobs:
|
||||
grep '^Release:' "$spec"
|
||||
|
||||
- name: Configure COPR authentication
|
||||
if: ${{ inputs.build_id == '' }}
|
||||
env:
|
||||
COPR_CONFIG: ${{ secrets.COPR_CONFIG }}
|
||||
run: |
|
||||
@@ -73,8 +106,38 @@ jobs:
|
||||
printf '%s\n' "$COPR_CONFIG" > "$HOME/.config/copr"
|
||||
chmod 600 "$HOME/.config/copr"
|
||||
|
||||
- name: Build and publish COPR package
|
||||
- name: Submit or select Copr build
|
||||
id: build
|
||||
env:
|
||||
EXISTING_BUILD_ID: ${{ inputs.build_id }}
|
||||
CHROOTS: ${{ steps.targets.outputs.targets }}
|
||||
run: |
|
||||
copr-cli build \
|
||||
yuezk/globalprotect-openconnect \
|
||||
publish-copr/globalprotect-openconnect.spec
|
||||
set -euo pipefail
|
||||
build_id="$EXISTING_BUILD_ID"
|
||||
if [[ -z "$build_id" ]]; then
|
||||
read -r -a chroots <<< "$CHROOTS"
|
||||
chroot_args=()
|
||||
for chroot in "${chroots[@]}"; do
|
||||
chroot_args+=(--chroot "$chroot")
|
||||
done
|
||||
copr-cli build --nowait yuezk/globalprotect-openconnect \
|
||||
"${chroot_args[@]}" \
|
||||
publish-copr/globalprotect-openconnect.spec | tee copr-submission.log
|
||||
build_id="$(sed -n 's/^Created builds: \([0-9][0-9]*\)$/\1/p' copr-submission.log)"
|
||||
fi
|
||||
[[ "$build_id" =~ ^[0-9]+$ ]]
|
||||
echo "id=$build_id" >> "$GITHUB_OUTPUT"
|
||||
echo "Copr build: https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/build/$build_id/" \
|
||||
>> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Wait for Copr builds and public repositories
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
BUILD_ID: ${{ steps.build.outputs.id }}
|
||||
CHROOTS: ${{ steps.targets.outputs.targets }}
|
||||
run: |
|
||||
read -r -a chroots <<< "$CHROOTS"
|
||||
python3 scripts/wait-for-publication.py copr \
|
||||
--chroots "${chroots[@]}" \
|
||||
--build-id "$BUILD_ID" --version "${TAG#v}" --revision "$REVISION"
|
||||
@@ -11,6 +11,18 @@ on:
|
||||
type: string
|
||||
required: true
|
||||
default: "1"
|
||||
verify_only:
|
||||
description: 'Verify the existing source and publication without uploading again'
|
||||
type: boolean
|
||||
default: false
|
||||
repositories:
|
||||
description: 'Space-separated distro repositories, e.g. 16.0 openSUSE_Tumbleweed; empty keeps enabled targets'
|
||||
type: string
|
||||
required: false
|
||||
|
||||
concurrency:
|
||||
group: publish-obs
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -18,15 +30,19 @@ permissions:
|
||||
jobs:
|
||||
publish-obs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 210
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Install metadata decompressor
|
||||
run: sudo apt-get update && sudo apt-get install -y zstd
|
||||
- name: Check inputs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Revision must be a positive integer" >&2
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -61,7 +77,22 @@ jobs:
|
||||
"$source_dir/.build/rpm/globalprotect-openconnect.changes" \
|
||||
publish-obs/files/
|
||||
|
||||
- name: Select OBS publication targets
|
||||
env:
|
||||
REPOSITORIES: ${{ inputs.repositories }}
|
||||
VERIFY_ONLY: ${{ inputs.verify_only }}
|
||||
OBS_USERNAME: yuezk
|
||||
OBS_PASSWORD: ${{ secrets.OBS_PASSWORD }}
|
||||
run: |
|
||||
verify_args=()
|
||||
if [[ "$VERIFY_ONLY" == 'true' ]]; then
|
||||
verify_args+=(--verify-only)
|
||||
fi
|
||||
python3 scripts/select-publication-targets.py obs \
|
||||
--repositories "$REPOSITORIES" "${verify_args[@]}" --output publish-obs/targets.json
|
||||
|
||||
- name: Publish OBS package
|
||||
if: ${{ !inputs.verify_only }}
|
||||
uses: yuezk/publish-obs-package@main
|
||||
with:
|
||||
project: home:yuezk
|
||||
@@ -70,3 +101,12 @@ jobs:
|
||||
password: ${{ secrets.OBS_PASSWORD }}
|
||||
files: ./publish-obs/files/*
|
||||
commit_message: 'Release ${{ inputs.tag }}-${{ inputs.revision }}'
|
||||
|
||||
- name: Wait for OBS builds and public repositories
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
python3 scripts/wait-for-publication.py obs \
|
||||
--targets-file publish-obs/targets.json \
|
||||
--version "${TAG#v}" --revision "$REVISION" --files publish-obs/files
|
||||
@@ -20,6 +20,18 @@ on:
|
||||
type: "string"
|
||||
required: true
|
||||
default: "1.91"
|
||||
verify_only:
|
||||
description: 'Verify an existing upload without building or uploading source again'
|
||||
type: boolean
|
||||
default: false
|
||||
concurrency:
|
||||
group: publish-ppa
|
||||
cancel-in-progress: false
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -28,7 +40,12 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then
|
||||
echo "Tag $TAG does not exist"
|
||||
exit 1
|
||||
@@ -67,8 +84,14 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
declare -A seen=()
|
||||
for item in "${series[@]}"; do
|
||||
ubuntu-distro-info --series "$item" >/dev/null
|
||||
if [[ -n "${seen[$item]+present}" ]]; then
|
||||
echo "Duplicate Ubuntu series: $item" >&2
|
||||
exit 1
|
||||
fi
|
||||
seen[$item]=1
|
||||
done
|
||||
|
||||
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
|
||||
@@ -79,6 +102,7 @@ jobs:
|
||||
needs: [check, resolve-series]
|
||||
name: publish-ppa (${{ matrix.series }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 210
|
||||
container:
|
||||
image: ubuntu:${{ matrix.series }}
|
||||
strategy:
|
||||
@@ -88,7 +112,7 @@ jobs:
|
||||
- name: Install container tools
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y ca-certificates curl gpg sudo
|
||||
apt-get install -y ca-certificates curl gpg sudo python3 distro-info distro-info-data
|
||||
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
|
||||
@@ -97,9 +121,12 @@ jobs:
|
||||
> /etc/apt/sources.list.d/github-cli.list
|
||||
apt-get update
|
||||
apt-get install -y gh
|
||||
- uses: actions/checkout@v6
|
||||
- name: Prepare workspace
|
||||
if: ${{ !inputs.verify_only }}
|
||||
run: rm -rf publish-ppa && mkdir publish-ppa
|
||||
- name: Download ${{ inputs.tag }} offline source code
|
||||
if: ${{ !inputs.verify_only }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
run: |
|
||||
@@ -108,17 +135,23 @@ jobs:
|
||||
--pattern '*.offline.tar.gz' \
|
||||
--dir publish-ppa
|
||||
- name: Patch the source code
|
||||
if: ${{ !inputs.verify_only }}
|
||||
run: |
|
||||
cd publish-ppa
|
||||
|
||||
# Rename the source tarball without the offline suffix
|
||||
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
|
||||
archives=(./*.offline.tar.gz)
|
||||
[[ "${#archives[@]}" -eq 1 && -f "${archives[0]}" ]]
|
||||
archive="${archives[0]%.offline.tar.gz}.tar.gz"
|
||||
mv -v -- "${archives[0]}" "$archive"
|
||||
|
||||
# Extract the source tarball
|
||||
tar -xzf *.tar.gz
|
||||
tar -xzf "$archive"
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
cd globalprotect-openconnect-*/
|
||||
source_dirs=(./globalprotect-openconnect-*/)
|
||||
[[ "${#source_dirs[@]}" -eq 1 && -d "${source_dirs[0]}" ]]
|
||||
cd "${source_dirs[0]}"
|
||||
|
||||
# Prepare the debian directory with custom files
|
||||
mkdir -p .build/debian
|
||||
@@ -137,6 +170,7 @@ jobs:
|
||||
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
|
||||
|
||||
- name: Publish to PPA
|
||||
if: ${{ !inputs.verify_only }}
|
||||
uses: yuezk/publish-ppa-package@main
|
||||
with:
|
||||
repository: "yuezk/globalprotect-openconnect"
|
||||
@@ -149,3 +183,13 @@ jobs:
|
||||
extra_ppa: "yuezk/globalprotect-openconnect"
|
||||
series: ${{ matrix.series }}
|
||||
revision: ${{ inputs.revision }}
|
||||
|
||||
- name: Wait for Launchpad builds and public package indexes
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
REVISION: ${{ inputs.revision }}
|
||||
SERIES: ${{ matrix.series }}
|
||||
run: |
|
||||
ubuntu_version="$(ubuntu-distro-info --series "$SERIES" --release | cut -d' ' -f1)"
|
||||
python3 scripts/wait-for-publication.py ppa --series "$SERIES" \
|
||||
--version "${TAG#v}-ppa${REVISION}~ubuntu${ubuntu_version}"
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Release infrastructure checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/**'
|
||||
- 'scripts/wait-for-publication.py'
|
||||
- 'scripts/select-publication-targets.py'
|
||||
- 'scripts/verify-docker-publication.sh'
|
||||
- 'scripts/tests/test_*publication.py'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.github/workflows/**'
|
||||
- 'scripts/wait-for-publication.py'
|
||||
- 'scripts/select-publication-targets.py'
|
||||
- 'scripts/verify-docker-publication.sh'
|
||||
- 'scripts/tests/test_*publication.py'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Validate workflow expressions and schema
|
||||
run: |
|
||||
docker run --rm -v "$PWD:/repo" -w /repo \
|
||||
rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 \
|
||||
-shellcheck='' -pyflakes=''
|
||||
- name: Check Docker publication script
|
||||
run: |
|
||||
bash -n scripts/verify-docker-publication.sh
|
||||
shellcheck scripts/verify-docker-publication.sh
|
||||
- name: Test publication verification
|
||||
run: python3 -m unittest discover -s scripts/tests -p 'test_*publication.py'
|
||||
@@ -215,6 +215,7 @@ jobs:
|
||||
if: ${{ inputs.release-docker }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -244,7 +245,12 @@ jobs:
|
||||
docker buildx imagetools create "${tags[@]}" \
|
||||
$(printf "$IMAGE@sha256:%s " *)
|
||||
|
||||
docker buildx imagetools inspect "$IMAGE:$TAG"
|
||||
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$TAG" /tmp/digests "${{ inputs.arch }}"
|
||||
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
for alias in "$VERSION" latest; do
|
||||
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$alias" /tmp/digests "${{ inputs.arch }}"
|
||||
done
|
||||
fi
|
||||
|
||||
gh-release:
|
||||
needs:
|
||||
|
||||
@@ -104,14 +104,19 @@ jobs:
|
||||
test -x result/bin/gpgui-helper
|
||||
test -x result/bin/gpgui
|
||||
test ! -L result/bin/gpservice
|
||||
head -n1 result/bin/gpclient | grep '^#!'
|
||||
head -n1 result/bin/gpservice | grep '^#!'
|
||||
grep -q '/run/wrappers/bin/pkexec' result/bin/gpclient
|
||||
grep -q 'gpservice_public=.*/bin/gpservice' result/bin/gpclient
|
||||
grep -q 'exec .*/bin/gpservice' result/bin/gpservice
|
||||
! grep -q '@gpservice_public@\|@gpservice_fhs@\|\$out/bin/gpservice' result/bin/gpclient result/bin/gpservice
|
||||
test -x result/libexec/gpclient/gp-vpnc-script-installer
|
||||
test -x result/libexec/gpclient/gp-hip-script-installer
|
||||
result/bin/gpclient --version
|
||||
result/bin/gpservice --version
|
||||
result/bin/gpauth --version
|
||||
|
||||
! grep -R '/usr/bin/gp' result/share
|
||||
if grep -R '/usr/bin/gp' result/share; then
|
||||
echo "Desktop assets contain paths outside the Nix package" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Verify desktop authorization runs on the host
|
||||
run: bash scripts/tests/nix-desktop-authorization.sh result
|
||||
|
||||
open-pull-request:
|
||||
needs:
|
||||
|
||||
Generated
+81
-72
@@ -214,7 +214,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "auth"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"block2",
|
||||
@@ -423,7 +423,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "browser-launcher"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"log",
|
||||
@@ -538,9 +538,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.5.1"
|
||||
version = "1.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"
|
||||
checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
@@ -719,7 +719,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compile-time"
|
||||
@@ -1274,15 +1277,15 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.18.0"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "embed-resource"
|
||||
version = "3.0.11"
|
||||
version = "3.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"
|
||||
checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"memchr",
|
||||
@@ -1828,7 +1831,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpapi"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
@@ -1846,6 +1849,7 @@ dependencies = [
|
||||
"log-reload",
|
||||
"md5",
|
||||
"netdev",
|
||||
"nix 0.31.3",
|
||||
"openssl",
|
||||
"os_info",
|
||||
"oslog",
|
||||
@@ -1859,11 +1863,13 @@ dependencies = [
|
||||
"serde_urlencoded",
|
||||
"sha256",
|
||||
"snow",
|
||||
"socket2",
|
||||
"specta",
|
||||
"tauri",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"url",
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
@@ -1876,7 +1882,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpauth"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"auth",
|
||||
@@ -1895,7 +1901,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpclient"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -1914,13 +1920,14 @@ dependencies = [
|
||||
"sysinfo",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"uzers",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpgui-helper"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -1941,13 +1948,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gphip"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
"chrono",
|
||||
"gpapi",
|
||||
"log",
|
||||
"netdev",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1959,7 +1965,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpservice"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -1976,6 +1982,7 @@ dependencies = [
|
||||
"mac_address",
|
||||
"nix 0.31.3",
|
||||
"openconnect",
|
||||
"openssl",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha256",
|
||||
@@ -2044,9 +2051,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.19"
|
||||
version = "0.4.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
|
||||
checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -2178,9 +2185,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.11.1"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
|
||||
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
@@ -2525,9 +2532,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jiff"
|
||||
version = "0.2.37"
|
||||
version = "0.2.38"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb"
|
||||
checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383"
|
||||
dependencies = [
|
||||
"defmt",
|
||||
"jiff-core",
|
||||
@@ -2552,9 +2559,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "0.2.37"
|
||||
version = "0.2.38"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212"
|
||||
checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c"
|
||||
dependencies = [
|
||||
"jiff-core",
|
||||
"proc-macro2",
|
||||
@@ -2564,9 +2571,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jiff-tzdb"
|
||||
version = "0.1.8"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"
|
||||
checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7"
|
||||
|
||||
[[package]]
|
||||
name = "jiff-tzdb-platform"
|
||||
@@ -2720,9 +2727,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
version = "0.2.190"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
[[package]]
|
||||
name = "libdbus-sys"
|
||||
@@ -2813,12 +2820,12 @@ checksum = "d3d25b0e0b648a86960ac23b7ad4abb9717601dec6f66c165f5b037f3f03065f"
|
||||
|
||||
[[package]]
|
||||
name = "mac_address"
|
||||
version = "1.1.8"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303"
|
||||
checksum = "b367b50a9be9a5d3b5718c1da74e5d6b9c17647f89752ee2562a470cc3c4eb1a"
|
||||
dependencies = [
|
||||
"nix 0.29.0",
|
||||
"winapi",
|
||||
"nix 0.30.1",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2887,9 +2894,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.3"
|
||||
version = "1.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
@@ -3033,9 +3040,9 @@ checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
|
||||
|
||||
[[package]]
|
||||
name = "nix"
|
||||
version = "0.29.0"
|
||||
version = "0.30.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
|
||||
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
@@ -3105,9 +3112,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.4"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
|
||||
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
|
||||
dependencies = [
|
||||
"objc2-encode",
|
||||
"objc2-exception-helper",
|
||||
@@ -3379,12 +3386,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openconnect"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
dependencies = [
|
||||
"autotools",
|
||||
"cc",
|
||||
"fs_extra",
|
||||
"is_executable",
|
||||
"libc",
|
||||
"log",
|
||||
"pkg-config",
|
||||
]
|
||||
@@ -3673,9 +3681,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
@@ -4653,6 +4661,7 @@ checksum = "4ccbb212565d2dc177bc15ecb7b039d66c4490da892436a4eee5b394d620c9bc"
|
||||
dependencies = [
|
||||
"specta-macros",
|
||||
"thiserror 1.0.69",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4888,9 +4897,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
|
||||
|
||||
[[package]]
|
||||
name = "tauri"
|
||||
version = "2.12.0"
|
||||
version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb20ef8e6f97d6fe03039666cd82861f09a38b56291fa2f0f9fe140023f61c1a"
|
||||
checksum = "ed99ee9694a2deb776d91cae48ac7411ddfc89ecae2f9b5041111d8c88f2ace9"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
@@ -4939,9 +4948,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-build"
|
||||
version = "2.7.0"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644"
|
||||
checksum = "59563ca5b331fd97f27ee9672ec8d36d33bb3c9e2c9f6710a1a5687256052e45"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
@@ -4960,9 +4969,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-codegen"
|
||||
version = "2.7.0"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3926b73ac01df7c14f19ff872cd56e67213a87acc0000ea37ddb300f3d11a3e3"
|
||||
checksum = "e50213e463086ecc283d7e9f51c30cc0fd304ad457425158018be26dbf0d0a80"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"brotli",
|
||||
@@ -4987,9 +4996,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-macros"
|
||||
version = "2.7.0"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d21d0fa2c0529972ea6ecaf7404fcf40efac098eda0beb06ca682f41e33a6aa5"
|
||||
checksum = "8129fb43bb6e0d6b73ad3315cd172beaab17cd28899c594b1b32c80edbbfd99c"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -5001,9 +5010,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "2.12.0"
|
||||
version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9e6d5ef76985b32ff012a43b58df205d25a285e400ca878afcacddc5d5f3238"
|
||||
checksum = "c2a57a2a9b8c8b7fc00d35b510fe808ded7f9f1b44fc1cdda6aee38632ea5413"
|
||||
dependencies = [
|
||||
"cookie",
|
||||
"dpi",
|
||||
@@ -5026,9 +5035,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-wry"
|
||||
version = "2.12.0"
|
||||
version = "2.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa829eb69860cf1fb0bedb21d2d5f1effce3527d054a68ca1cd7355c654400a3"
|
||||
checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"http",
|
||||
@@ -5052,9 +5061,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.10.0"
|
||||
version = "2.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4dd257082deff79550de3409ed146104aeaf86fe38649615b04a304144939677"
|
||||
checksum = "2ff55a614843b9a3f010f211df637c94df2607175b8d0f6e0f4a7c19e18621ee"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli",
|
||||
@@ -5230,9 +5239,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.53.1"
|
||||
version = "1.53.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
|
||||
checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
@@ -5632,9 +5641,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.26.1"
|
||||
version = "1.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
|
||||
checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
@@ -5712,9 +5721,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.1"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
|
||||
checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
|
||||
dependencies = [
|
||||
"try-lock",
|
||||
]
|
||||
@@ -6486,12 +6495,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.55.0"
|
||||
version = "0.56.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
|
||||
checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6619,9 +6628,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.3"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
|
||||
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -6631,18 +6640,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.59"
|
||||
version = "0.8.61"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb"
|
||||
checksum = "879fb705ce98c32e41ebdb970fbe1204f8492423b314c6ab0354c3e7b5542866"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.59"
|
||||
version = "0.8.61"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82"
|
||||
checksum = "708882a28301d604fa039cc7727607a98d04c4b86dc76ec9cc683f805d709759"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -6672,9 +6681,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.0"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ members = [
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "2.6.5"
|
||||
version = "3.0.2"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
|
||||
@@ -145,7 +145,6 @@ install:
|
||||
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
|
||||
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
|
||||
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
|
||||
install -Dm755 target/release/gp-hip-runner $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
|
||||
install -Dm755 target/release/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
|
||||
install -Dm755 target/release/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
@@ -159,7 +158,6 @@ install:
|
||||
fi
|
||||
|
||||
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
|
||||
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
|
||||
|
||||
# Install the disconnect hooks
|
||||
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
|
||||
@@ -196,11 +194,9 @@ install-bsd:
|
||||
fi
|
||||
|
||||
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
|
||||
install -m 755 target/release/gp-hip-runner $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-runner
|
||||
install -m 755 target/release/gp-hip-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-script-installer
|
||||
install -m 755 target/release/gp-vpnc-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-vpnc-script-installer
|
||||
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script
|
||||
install -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh
|
||||
|
||||
install -d $(DESTDIR)$(PREFIX)/share/applications
|
||||
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop
|
||||
@@ -300,13 +296,11 @@ uninstall:
|
||||
rm -f $(DESTDIR)/usr/bin/gpclient
|
||||
rm -f $(DESTDIR)/usr/bin/gpauth
|
||||
rm -f $(DESTDIR)/usr/bin/gpservice
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui-helper
|
||||
rm -f $(DESTDIR)/usr/bin/gpgui
|
||||
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
|
||||
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
|
||||
|
||||
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A modern GlobalProtect VPN client for Linux, built on OpenConnect with full support for SSO authentication. This project provides both command-line and graphical interfaces for seamless VPN connectivity.
|
||||
A GlobalProtect VPN client built on OpenConnect with support for SSO authentication. It provides command-line tools and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="https://github.com/user-attachments/assets/2fb6116c-dc57-43f2-af75-9c3d97ab7122">
|
||||
@@ -15,12 +15,15 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
|
||||
- [Command-Line Interface](#command-line-interface)
|
||||
- [Graphical User Interface](#graphical-user-interface)
|
||||
- [Installation](#installation)
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
|
||||
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
|
||||
- [Other RPM-based Distributions](#other-rpm-based-distributions)
|
||||
- [Alpine Linux](#alpine-linux)
|
||||
- [FreeBSD](#freebsd)
|
||||
- [OpenBSD](#openbsd)
|
||||
- [Gentoo](#gentoo)
|
||||
- [NixOS](#nixos)
|
||||
- [Official Docker Image](#official-docker-image)
|
||||
@@ -28,11 +31,11 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
|
||||
- [Building from Source](#building-from-source)
|
||||
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||
- [NetworkManager Integration](#networkmanager-integration)
|
||||
- [License](#license)
|
||||
- [Licensing](#licensing)
|
||||
|
||||
## Features
|
||||
|
||||
- **Cross-Platform Linux Support** – Optimized for various Linux distributions
|
||||
- **Desktop Platform Support** – macOS, Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interface** – Available as both CLI and GUI applications
|
||||
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
|
||||
- **Browser Integration** – Authenticate using your default browser or any specified browser
|
||||
@@ -45,7 +48,7 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
|
||||
|
||||
### Command-Line Interface
|
||||
|
||||
The CLI version is fully open source and feature-rich, providing nearly identical functionality to the GUI version.
|
||||
The CLI is free and open source. Use it to authenticate, connect to portals or gateways, and generate HIP reports from the terminal.
|
||||
|
||||
#### Basic Commands
|
||||
|
||||
@@ -62,6 +65,7 @@ Commands:
|
||||
Options:
|
||||
--fix-openssl Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.
|
||||
--ignore-tls-errors Ignore the TLS errors
|
||||
--lock-file <LOCK_FILE> Path to the gpclient PID lock file
|
||||
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
|
||||
-v, --verbose... Enable verbose output, -v for debug, -vv for trace
|
||||
-q, --quiet... Decrease logging verbosity, -q for warnings, -qq for errors
|
||||
@@ -71,29 +75,48 @@ Options:
|
||||
|
||||
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
|
||||
|
||||
#### External Browser Authentication
|
||||
#### HIP reports
|
||||
|
||||
For browser-based authentication with the CLI:
|
||||
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
|
||||
|
||||
**Method 1:** Using sudo with environment preservation:
|
||||
```bash
|
||||
sudo gpclient connect --browser <portal>
|
||||
sudo gpclient connect <portal> --hip
|
||||
```
|
||||
|
||||
**Method 2:** Using authentication piping:
|
||||
Use `--hip=/absolute/path/to/script` for a custom executable. It runs as the `gpclient` process user unless `--hip-user` specifies another user. No installed HIP script is discovered automatically. `--hip-user` applies only to custom executables.
|
||||
|
||||
`gpclient hip` generates a report on demand for inspection; see `gpclient hip --help` for report inputs. The GUI's HIP tab supports generated reports, edited XML, and HIP Off on all desktop platforms. Linux, FreeBSD, and OpenBSD also support desktop-user scripts and explicitly approved root scripts.
|
||||
|
||||
#### External Browser Authentication
|
||||
|
||||
Use `gpclient` directly for browser-based authentication. It opens the browser as your normal desktop user while keeping VPN tunnel setup privileged:
|
||||
|
||||
```bash
|
||||
gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
To reuse a saved portal cookie for later connections, add `--cookie-cache`:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser --cookie-cache
|
||||
```
|
||||
|
||||
Add `--gateway <gateway>` to select a particular gateway. Cookie caching is handled by `gpclient`. Its default cache file is `$HOME/.config/gpclient/cookie.json`, which normally belongs to root when running with `sudo`. To choose a predictable location, specify the path explicitly:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser --cookie-cache=/absolute/path/to/cookie.json
|
||||
```
|
||||
|
||||
**Browser Options:**
|
||||
- Use `--browser` to auto-select Chrome, Firefox, then the system default browser
|
||||
|
||||
- Use `--browser` to try your recognized default browser first, then another detected browser, and finally the system URL handler
|
||||
- Use `--browser default` to use the system default browser
|
||||
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
|
||||
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
The GUI application provides an intuitive interface for managing VPN connections. Launch it from your application menu or via the terminal:
|
||||
GP Connect provides a desktop interface for managing VPN connections. On macOS, open GP Connect from Applications. On Linux, FreeBSD, and OpenBSD, launch it from your application menu or via the terminal:
|
||||
|
||||
```bash
|
||||
gpclient launch-gui
|
||||
@@ -109,6 +132,26 @@ gpclient launch-gui
|
||||
>
|
||||
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
|
||||
|
||||
### macOS
|
||||
|
||||
GP Connect requires Apple silicon and macOS 13 or later. The macOS app includes both the desktop application and the free `gpclient` CLI. The CLI does not require a GUI license.
|
||||
|
||||
#### Option 1: Install with Homebrew
|
||||
|
||||
```bash
|
||||
brew install --cask yuezk/gp-connect/gp-connect
|
||||
```
|
||||
|
||||
Open GP Connect from Applications, or connect from the terminal:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
#### Option 2: Install from DMG
|
||||
|
||||
Download the GP Connect `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, open it, and drag GP Connect into Applications.
|
||||
|
||||
### Debian / Ubuntu
|
||||
|
||||
#### Option 1: Install from PPA (Recommended)
|
||||
@@ -131,7 +174,7 @@ sudo apt-get install globalprotect-openconnect
|
||||
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo apt install --fix-broken globalprotect-openconnect_*.deb
|
||||
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb
|
||||
```
|
||||
|
||||
### Arch Linux / Manjaro
|
||||
@@ -245,6 +288,7 @@ Add the flake input and NixOS module to your `flake.nix`:
|
||||
|
||||
The module builds the package with your NixOS configuration's `pkgs`, so the
|
||||
GlobalProtect GUI and the system use the same Nixpkgs dependency versions.
|
||||
It also enables Polkit and its setuid `pkexec` wrapper for privileged operations.
|
||||
|
||||
```nix
|
||||
{
|
||||
@@ -294,6 +338,15 @@ NixOS does not run an imperative package-uninstall hook when a package is
|
||||
removed from the system configuration. Remove an installed replacement VPN
|
||||
script from the app settings before removing the package.
|
||||
|
||||
The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. Both `prebuilt` and `fromSource` run natively on the host with packaged dependencies and installer paths. The `fromSource` package builds the current flake checkout, including its Git submodules:
|
||||
|
||||
```bash
|
||||
git submodule update --init --recursive
|
||||
nix build "git+file://$PWD?submodules=1#fromSource"
|
||||
```
|
||||
|
||||
Local source builds require initialized Git submodules and a flake URL with `submodules=1`, as shown above. For a remote source flake, use a Git URL with submodules enabled, such as `git+https://github.com/yuezk/GlobalProtect-openconnect?submodules=1#fromSource`. The `prebuilt` package and NixOS module do not require Git submodules. Build output (`target`, `.build`, and `node_modules`) is excluded from the source input. Updating release asset hashes changes the prebuilt package, independently of source builds.
|
||||
|
||||
### Official Docker Image
|
||||
|
||||
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
||||
@@ -309,7 +362,7 @@ 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
|
||||
connect <portal>
|
||||
```
|
||||
|
||||
For browser authentication in a headless environment, use remote browser authentication:
|
||||
@@ -336,16 +389,6 @@ docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
|
||||
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
|
||||
@@ -353,14 +396,16 @@ The image includes `gpclient` and `gpauth` only. It does not include embedded we
|
||||
#### Manual Installation
|
||||
|
||||
1. **Install dependencies:**
|
||||
- `webkit2gtk`
|
||||
- WebKitGTK 4.1 (for example, `libwebkit2gtk-4.1-0` on Debian/Ubuntu)
|
||||
- `libsecret`
|
||||
- `libayatana-appindicator` or `libappindicator-gtk3`
|
||||
- polkit (`pkexec`) for GUI-launched VPN connections
|
||||
|
||||
2. **Download and extract:**
|
||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
```bash
|
||||
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
|
||||
cd globalprotect-openconnect_${version}
|
||||
```
|
||||
|
||||
3. **Install:**
|
||||
@@ -370,11 +415,11 @@ The image includes `gpclient` and `gpauth` only. It does not include embedded we
|
||||
|
||||
## Building from Source
|
||||
|
||||
You can build the application from source using either a DevContainer (recommended) or a local development environment.
|
||||
The instructions below build the open-source components on Linux. For FreeBSD and OpenBSD, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
|
||||
### Method 1: Using DevContainer (Recommended)
|
||||
### Method 1: Using DevContainer
|
||||
|
||||
This project includes a DevContainer configuration that provides a consistent, reproducible build environment with all dependencies pre-installed.
|
||||
This project includes a DevContainer configuration for Linux development. The repository's `rust-toolchain.toml` selects the Rust toolchain; rustup may need to download it on the first build.
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
@@ -398,7 +443,7 @@ This project includes a DevContainer configuration that provides a consistent, r
|
||||
|
||||
3. **Build the project:**
|
||||
|
||||
To build everything including the GUI helper run this command:
|
||||
To build the open-source components, including the GUI helper, run:
|
||||
```bash
|
||||
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
|
||||
@@ -406,13 +451,17 @@ This project includes a DevContainer configuration that provides a consistent, r
|
||||
```
|
||||
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
|
||||
|
||||
5. **Locate build artifacts:**
|
||||
4. **Locate build artifacts:**
|
||||
|
||||
The compiled binaries will be available in `target/release/`:
|
||||
- `gpclient` – CLI client
|
||||
- `gpservice` – Background service
|
||||
- `gpauth` – Authentication helper
|
||||
- `gpgui-helper` – GUI helper
|
||||
- `gp-hip-script-installer` – Privileged HIP script installer
|
||||
- `gp-vpnc-script-installer` – Privileged VPN script installer
|
||||
|
||||
The proprietary GP Connect desktop application is distributed separately. Use `INCLUDE_GUI=1` with `make build` to download its matching published Linux build for installation.
|
||||
|
||||
#### Alternative: Using VS Code
|
||||
|
||||
@@ -431,7 +480,7 @@ This project includes a DevContainer configuration that provides a consistent, r
|
||||
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
|
||||
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
|
||||
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
|
||||
- `nodejs` and `pnpm` (optional)
|
||||
- Node.js and pnpm if rebuilding the GUI helper frontend
|
||||
|
||||
#### Build Steps
|
||||
|
||||
@@ -451,7 +500,7 @@ This project includes a DevContainer configuration that provides a consistent, r
|
||||
sudo make install
|
||||
```
|
||||
|
||||
> **Note:** `DESTDIR` is not currently supported.
|
||||
To stage the files for packaging instead of installing them into the system, use `make install DESTDIR=/absolute/path/to/staging`.
|
||||
|
||||
### Testing Your Build
|
||||
|
||||
@@ -463,29 +512,35 @@ Verify the CLI client is working correctly:
|
||||
|
||||
### Build Options
|
||||
|
||||
- `BUILD_GUI_HELPER=0` – Build CLI components only (excludes GUI)
|
||||
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external or remote browser
|
||||
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
|
||||
- `OFFLINE=1` – Build in offline mode using vendored dependencies
|
||||
|
||||
## Frequently Asked Questions
|
||||
|
||||
When reporting a problem, follow the [diagnostics collection instructions](docs/diagnostics.md). A standalone script is available for versions without the diagnostics command; you do not need to upgrade first.
|
||||
|
||||
### Q: How do I resolve the "Secure Storage not ready" error?
|
||||
|
||||
**Solution 1:** Update to version 2.2.0 or later, which includes a file-based storage fallback.
|
||||
Unlock your desktop keyring and ensure the application can access it. On Linux and BSD, check that a keyring service such as GNOME Keyring is installed and running in your desktop session. On macOS, check Keychain access.
|
||||
|
||||
**Solution 2:** Install the `gnome-keyring` package and restart your system.
|
||||
Linux and BSD can use file storage when secure storage is unavailable during initial setup. An existing configuration that uses the keyring still needs access to that keyring.
|
||||
|
||||
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
### Q: How do I fix the "cannot open display" error when using CLI?
|
||||
|
||||
If you encounter `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`, try running the command with `sudo -E`:
|
||||
Run the client from a terminal in your normal desktop session and use an external browser:
|
||||
|
||||
```bash
|
||||
sudo -E gpclient connect <portal>
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
On a headless server, use `--browser remote` and complete authentication from another machine.
|
||||
|
||||
## NetworkManager Integration
|
||||
|
||||
- [WMP/GlobalProtect-SAML-NetworkManager](https://github.com/WMP/GlobalProtect-SAML-NetworkManager) – NetworkManager VPN plugin with SAML/SSO support for GNOME and KDE Plasma
|
||||
@@ -496,7 +551,7 @@ See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/iss
|
||||
### Trial and Pricing
|
||||
|
||||
The **CLI version** is completely free and open source.
|
||||
The **GUI version** is a paid application with a **7-day trial period** after installation.
|
||||
The **GUI version** is a paid application with a **7-day trial**. Start the trial in the app by verifying your email address with a one-time code. Installing the app alone does not start the trial.
|
||||
|
||||
### Open Source Licenses
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ env_logger.workspace = true
|
||||
inquire = "0.9"
|
||||
log.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
tokio-util.workspace = true
|
||||
sysinfo.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -18,6 +18,7 @@ use tokio::fs;
|
||||
use crate::{
|
||||
GP_CLIENT_LOCK_FILE,
|
||||
connect::{ConnectArgs, ConnectHandler},
|
||||
diagnostics::DiagnosticsArgs,
|
||||
disconnect::{DisconnectArgs, DisconnectHandler},
|
||||
hip::{HipArgs, HipHandler},
|
||||
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
|
||||
@@ -50,6 +51,23 @@ enum CliCommand {
|
||||
LaunchGui(LaunchGuiArgs),
|
||||
#[command(about = "Generate HIP report")]
|
||||
Hip(HipArgs),
|
||||
#[command(about = "Collect system diagnostics for a bug report without connecting to a VPN")]
|
||||
Diagnostics(DiagnosticsArgs),
|
||||
#[command(hide = true)]
|
||||
DetectInternalHost {
|
||||
#[arg(long)]
|
||||
address: std::net::IpAddr,
|
||||
#[arg(long)]
|
||||
hostname: String,
|
||||
},
|
||||
#[command(hide = true)]
|
||||
ResolveGateway {
|
||||
host: String,
|
||||
#[arg(long, default_value_t = 443)]
|
||||
port: u16,
|
||||
#[arg(long)]
|
||||
disable_ipv6: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
@@ -118,10 +136,9 @@ impl Args for Cli {
|
||||
impl Cli {
|
||||
fn can_run_alongside_client(&self) -> bool {
|
||||
match &self.command {
|
||||
CliCommand::Disconnect(_) => true,
|
||||
CliCommand::Hip(_) => true,
|
||||
CliCommand::Connect(_) => false,
|
||||
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
||||
_ => false,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +171,10 @@ impl Cli {
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
if let CliCommand::Diagnostics(args) = &self.command {
|
||||
return args.run(VERSION).await;
|
||||
}
|
||||
|
||||
// check if an instance is running
|
||||
if !self.can_run_alongside_client() && self.is_running().await {
|
||||
bail!("Another instance of the client is already running");
|
||||
@@ -179,6 +200,21 @@ impl Cli {
|
||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
||||
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
||||
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
||||
CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"),
|
||||
CliCommand::DetectInternalHost { address, hostname } => {
|
||||
let internal = gpapi::session::network::native::detect_in_helper(*address, hostname)?;
|
||||
println!("{}", serde_json::to_string(&internal)?);
|
||||
Ok(())
|
||||
}
|
||||
CliCommand::ResolveGateway {
|
||||
host,
|
||||
port,
|
||||
disable_ipv6,
|
||||
} => {
|
||||
let addresses = gpapi::session::network::native::lookup_in_helper(host, *port, *disable_ipv6)?;
|
||||
println!("{}", serde_json::to_string(&addresses)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,6 +256,38 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"--fix-openssl",
|
||||
"diagnostics",
|
||||
"--json",
|
||||
"--output",
|
||||
"report.json",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(matches!(cli.command, CliCommand::Diagnostics(_)));
|
||||
assert!(cli.can_run_alongside_client());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_helper_runs_alongside_client_and_is_hidden_from_help() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
"resolve-gateway",
|
||||
"localhost",
|
||||
"--port",
|
||||
"444",
|
||||
"--disable-ipv6",
|
||||
])
|
||||
.unwrap();
|
||||
assert!(cli.can_run_alongside_client());
|
||||
use clap::CommandFactory;
|
||||
let help = Cli::command().render_help().to_string();
|
||||
assert!(!help.contains("resolve-gateway"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_file_defaults_to_standard_path() {
|
||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
||||
|
||||
@@ -54,13 +54,16 @@ pub(crate) struct ConnectArgs {
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
|
||||
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
|
||||
default_missing_value = "",
|
||||
num_args=0..=1
|
||||
)]
|
||||
pub(super) hip: Option<String>,
|
||||
|
||||
#[arg(long, help = "The user used to run the HIP script")]
|
||||
#[arg(
|
||||
long,
|
||||
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
|
||||
)]
|
||||
pub(super) hip_user: Option<String>,
|
||||
|
||||
#[arg(
|
||||
|
||||
@@ -11,6 +11,14 @@ use log::info;
|
||||
|
||||
use super::ConnectHandler;
|
||||
|
||||
/// Replaces only the child launch boundary in workflow tests.
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
pub(super) struct AuthAttemptFixture {
|
||||
pub(super) outcomes: std::collections::VecDeque<anyhow::Result<Credential>>,
|
||||
pub(super) observed: Vec<(String, bool, bool)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CleanAuthState {
|
||||
requested: bool,
|
||||
@@ -44,6 +52,47 @@ impl ConnectHandler<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn obtain_credential_with_recovery(
|
||||
&self,
|
||||
mut response: Prelogin,
|
||||
server: &str,
|
||||
browser_allowed: bool,
|
||||
) -> anyhow::Result<(Prelogin, Credential)> {
|
||||
loop {
|
||||
self.check_cancelled()?;
|
||||
let result = self.obtain_credential(&response, server, browser_allowed).await;
|
||||
self.check_cancelled()?;
|
||||
match result {
|
||||
Ok(credential) => return Ok((response, credential)),
|
||||
Err(error) => {
|
||||
if !self.auth_recovery.borrow_mut().recover(&error) {
|
||||
return Err(self.auth_recovery.borrow().terminal(error));
|
||||
}
|
||||
log::warn!("Authenticator exited with a Wayland rendering error; retrying with DMABUF disabled");
|
||||
let refreshed = self
|
||||
.refresh_auth_prelogin(server, response.is_gateway(), browser_allowed)
|
||||
.await;
|
||||
response = refreshed.map_err(|error| self.auth_recovery.borrow().terminal(error))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn refresh_auth_prelogin(
|
||||
&self,
|
||||
server: &str,
|
||||
is_gateway: bool,
|
||||
browser_allowed: bool,
|
||||
) -> anyhow::Result<Prelogin> {
|
||||
let mut params = self.build_gp_params();
|
||||
params.set_is_gateway(is_gateway);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = gpapi::portal::prelogin(server, ¶ms, self.prelogin_options(browser_allowed)) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn obtain_credential(
|
||||
&self,
|
||||
prelogin: &Prelogin,
|
||||
@@ -76,6 +125,7 @@ impl ConnectHandler<'_> {
|
||||
let os_profile = self.os_profile.borrow().clone();
|
||||
let key_password = self.latest_key_password.borrow().clone();
|
||||
let auth_launcher = SamlAuthLauncher::new(server)
|
||||
.dmabuf_disabled(self.auth_recovery.borrow().dmabuf_disabled())
|
||||
.gateway(is_gateway)
|
||||
.saml_request(prelogin.saml_request())
|
||||
.os_profile(&os_profile)
|
||||
@@ -116,7 +166,21 @@ impl ConnectHandler<'_> {
|
||||
.clean(clean_auth)
|
||||
.default_browser(use_default_browser);
|
||||
|
||||
let cred = auth_launcher.launch().await?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
let mut fixture = self.auth_attempt_fixture.borrow_mut();
|
||||
if let Some(outcome) = fixture.outcomes.pop_front() {
|
||||
fixture.observed.push((
|
||||
prelogin.saml_request().to_owned(),
|
||||
self.auth_recovery.borrow().dmabuf_disabled(),
|
||||
clean_auth,
|
||||
));
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
|
||||
self.check_cancelled()?;
|
||||
Ok(cred)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use gpapi::{
|
||||
cookie_store::{self, StoredCookie},
|
||||
credential::AuthCookieCredential,
|
||||
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||
log_format::LogFormat,
|
||||
session::SessionMode,
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::{ConnectArgs, ConnectHandler};
|
||||
use crate::cli::SharedArgs;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct TestArgs {
|
||||
#[command(flatten)]
|
||||
connect: ConnectArgs,
|
||||
}
|
||||
|
||||
fn login_response() -> String {
|
||||
let mut fields = [""; 20];
|
||||
fields[1] = "issued-cookie";
|
||||
fields[3] = "gateway";
|
||||
fields[4] = "alice";
|
||||
fields[5] = "fixture-auth";
|
||||
fields[6] = "vsys1";
|
||||
fields[12] = "tunnel";
|
||||
format!(
|
||||
"<jnlp><application-desc>{}</application-desc></jnlp>",
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| format!("<argument>{field}</argument>"))
|
||||
.collect::<String>()
|
||||
)
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = tokio::spawn(async move {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
requests
|
||||
})
|
||||
.await
|
||||
.expect("Gateway fixture timed out")
|
||||
});
|
||||
(origin, worker)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
let (gateway, worker) = gateway(vec![("200 OK", login_response())]).await;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
handler.handle_impl().await.unwrap();
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(requests[0].starts_with("POST /ssl-vpn/login.esp "));
|
||||
assert!(requests[0].contains("portal-cookie"));
|
||||
assert_eq!(
|
||||
handler.sessions.borrow().members()[0].transport.authentication().mode(),
|
||||
SessionMode::Tunnel
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status></prelogin-response>".into(),
|
||||
),
|
||||
("403 Forbidden", "<response><error>rejected</error></response>".into()),
|
||||
("200 OK", login_response()),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--user", "alice", "--passwd-on-stdin"]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
handler.password_from_stdin.replace(Some("gateway-password".into()));
|
||||
let mut value = serde_json::to_value(Gateway::new("internal".into(), origin.clone())).unwrap();
|
||||
value["kind"] = serde_json::json!("internal");
|
||||
let gateway: Gateway = serde_json::from_value(value).unwrap();
|
||||
let session = handler
|
||||
.authenticate_gateway(
|
||||
&origin,
|
||||
&origin,
|
||||
&AuthCookieCredential::new("alice", "rejected-cookie", ""),
|
||||
false,
|
||||
GatewayLoginContext::new(&gateway, GatewaySelection::Auto),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(session.authentication.mode(), SessionMode::Tunnel);
|
||||
assert!(session.extension_auth.binding().is_none());
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 3);
|
||||
assert!(requests[1].contains("rejected-cookie"));
|
||||
assert!(requests[2].contains("gateway-password"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rendering_recovery_fetches_new_prelogin_metadata_and_preserves_gateway_mode() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status><region>old</region></prelogin-response>".into(),
|
||||
),
|
||||
(
|
||||
"200 OK",
|
||||
"<prelogin-response><status>Success</status><region>replacement</region></prelogin-response>".into(),
|
||||
),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
let original = handler.refresh_auth_prelogin(&origin, true, true).await.unwrap();
|
||||
let replacement = handler
|
||||
.refresh_auth_prelogin(&origin, original.is_gateway(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(original.region(), "old");
|
||||
assert_eq!(replacement.region(), "replacement");
|
||||
assert!(replacement.is_gateway());
|
||||
let requests = worker.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert!(
|
||||
requests
|
||||
.iter()
|
||||
.all(|request| request.starts_with("POST /ssl-vpn/prelogin.esp"))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[tokio::test]
|
||||
async fn cancellation_during_recovery_prelogin_stops_request() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let args = TestArgs::parse_from(["test", &origin]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
handler
|
||||
.auth_attempt_fixture
|
||||
.borrow_mut()
|
||||
.outcomes
|
||||
.push_back(Err(rendering_crash()));
|
||||
let (result, ()) = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
tokio::join!(
|
||||
async {
|
||||
let original = handler.refresh_auth_prelogin(&origin, false, false).await?;
|
||||
handler.obtain_credential_with_recovery(original, &origin, false).await
|
||||
},
|
||||
async {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut byte = [0];
|
||||
socket.read_exact(&mut byte).await.unwrap();
|
||||
handler.cancellation.cancel();
|
||||
}
|
||||
)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<gpapi::auth::AuthenticationCancelled>()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
fn rendering_crash() -> anyhow::Error {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
gpapi::process::rendering_recovery::RenderingCrash {
|
||||
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
fn saml_prelogin_response(region: &str, encoded_request: &str) -> String {
|
||||
format!(
|
||||
"<prelogin-response><status>Success</status><region>{region}</region><saml-auth-method>POST</saml-auth-method><saml-request>{encoded_request}</saml-request></prelogin-response>"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[tokio::test]
|
||||
async fn auth_crash_uses_fresh_saml_and_clean_once_with_shared_budget() {
|
||||
use gpapi::credential::{Credential, PreloginCredential};
|
||||
let (origin, worker) = gateway(vec![
|
||||
("200 OK", saml_prelogin_response("old-region", "b2xk")),
|
||||
("200 OK", saml_prelogin_response("new-region", "bmV3")),
|
||||
("200 OK", saml_prelogin_response("gateway-region", "Z2F0ZXdheQ==")),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
|
||||
Err(rendering_crash()),
|
||||
Ok(Credential::Prelogin(PreloginCredential::new(
|
||||
"alice",
|
||||
Some("new-cookie"),
|
||||
None,
|
||||
None,
|
||||
))),
|
||||
Err(rendering_crash()),
|
||||
]);
|
||||
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
|
||||
let (replacement, credential) = handler
|
||||
.obtain_credential_with_recovery(original, &origin, false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(replacement.region(), "new-region");
|
||||
assert_eq!(credential.username(), "alice");
|
||||
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
|
||||
let gateway_prelogin = handler.refresh_auth_prelogin(&origin, true, false).await.unwrap();
|
||||
let error = handler
|
||||
.obtain_credential_with_recovery(gateway_prelogin, &origin, false)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(
|
||||
handler.auth_attempt_fixture.borrow().observed,
|
||||
[
|
||||
("old".into(), false, true),
|
||||
("new".into(), true, false),
|
||||
("gateway".into(), true, false),
|
||||
]
|
||||
);
|
||||
assert_eq!(worker.await.unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[tokio::test]
|
||||
async fn exhausted_auth_recovery_is_terminal_before_portal_gateway_fallback() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
("200 OK", saml_prelogin_response("old-region", "b2xk")),
|
||||
("200 OK", saml_prelogin_response("new-region", "bmV3")),
|
||||
])
|
||||
.await;
|
||||
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
|
||||
Err(rendering_crash()),
|
||||
Err(anyhow::anyhow!(gpapi::error::PortalError::PreloginError(
|
||||
"second failure".into()
|
||||
))),
|
||||
]);
|
||||
let error = handler.handle_impl().await.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(handler.auth_attempt_fixture.borrow().observed.len(), 2);
|
||||
assert_eq!(worker.await.unwrap().len(), 2);
|
||||
}
|
||||
@@ -11,16 +11,16 @@ use gpapi::{
|
||||
clap::report,
|
||||
cookie_store,
|
||||
credential::{AuthCookieCredential, Credential},
|
||||
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
|
||||
gateway::{Gateway, GatewayLogin, GatewayLoginClient, GatewayLoginContext, GatewaySelection, SessionExtensionAuth},
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
portal::prelogin,
|
||||
portal::{PortalConfig, prelogin},
|
||||
process::users::get_user_by_name,
|
||||
utils::shutdown_signal,
|
||||
session::{GatewayAuthentication, SessionMode},
|
||||
};
|
||||
use inquire::Text;
|
||||
use log::{Level, info, warn};
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
use openconnect::{HipScript, HipSource, Vpn, VpnBuilder};
|
||||
use tokio::{runtime::Handle, task::JoinHandle};
|
||||
|
||||
use crate::session::{
|
||||
@@ -31,15 +31,15 @@ use super::{ConnectHandler, args::cookie_cache_path};
|
||||
|
||||
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
|
||||
|
||||
struct GatewayLoginSession {
|
||||
cookie: String,
|
||||
extension_auth: SessionExtensionAuth,
|
||||
pub(super) struct GatewayLoginSession {
|
||||
pub(super) authentication: GatewayAuthentication,
|
||||
pub(super) extension_auth: SessionExtensionAuth,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum GatewayConnectFailureStage {
|
||||
BeforeTunnel,
|
||||
AfterTunnel,
|
||||
BeforeEstablishment,
|
||||
AfterEstablishment,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -49,22 +49,22 @@ pub(super) struct GatewayConnectError {
|
||||
}
|
||||
|
||||
impl GatewayConnectError {
|
||||
fn before_tunnel(error: anyhow::Error) -> Self {
|
||||
fn before_establishment(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
stage: GatewayConnectFailureStage::BeforeTunnel,
|
||||
stage: GatewayConnectFailureStage::BeforeEstablishment,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
fn after_tunnel(error: anyhow::Error) -> Self {
|
||||
fn after_establishment(error: anyhow::Error) -> Self {
|
||||
Self {
|
||||
stage: GatewayConnectFailureStage::AfterTunnel,
|
||||
stage: GatewayConnectFailureStage::AfterEstablishment,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_before_tunnel(&self) -> bool {
|
||||
self.stage == GatewayConnectFailureStage::BeforeTunnel
|
||||
pub(super) fn is_before_establishment(&self) -> bool {
|
||||
self.stage == GatewayConnectFailureStage::BeforeEstablishment
|
||||
}
|
||||
|
||||
pub(super) fn as_error(&self) -> &anyhow::Error {
|
||||
@@ -77,59 +77,81 @@ impl GatewayConnectError {
|
||||
}
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<()> {
|
||||
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<anyhow::Result<()>> {
|
||||
let path = cookie_cache_path(self.args)?;
|
||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||
|
||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||
warn!(
|
||||
"Cached portal cookie for {} is not usable for gateway authentication. Clearing cache.",
|
||||
stored.server
|
||||
);
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
|
||||
info!(
|
||||
"Using cached portal cookie for {} (saved_at={}, gateway={})",
|
||||
stored.server, stored.saved_at, stored.last_gateway
|
||||
);
|
||||
|
||||
let cred: Credential = (&stored.auth_cookie).into();
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params, None).await {
|
||||
let credential = (&stored.auth_cookie).into();
|
||||
let mut params = self.build_gp_params();
|
||||
params.set_is_gateway(true);
|
||||
let session = match self
|
||||
.login_gateway(&stored.last_gateway, &credential, ¶ms, None)
|
||||
.await
|
||||
{
|
||||
Ok(session) => session,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"Cached portal cookie rejected by gateway {}: {}. Clearing cache and falling back to portal auth.",
|
||||
stored.last_gateway, err
|
||||
);
|
||||
Err(error) => {
|
||||
if self.cancellation.is_cancelled()
|
||||
|| error
|
||||
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||
.is_some()
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match self
|
||||
if session.authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||
self.logout_gateway(&stored.last_gateway).await;
|
||||
info!("Cached non-tunnel login requires fresh portal discovery");
|
||||
return None;
|
||||
}
|
||||
let result = self
|
||||
.connect_gateway(
|
||||
server,
|
||||
&stored.last_gateway,
|
||||
&login_session.cookie,
|
||||
&session.authentication,
|
||||
false,
|
||||
login_session.extension_auth,
|
||||
session.extension_auth,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => Some(()),
|
||||
Err(err) => {
|
||||
warn!("Gateway connect failed after cached-cookie login: {}", err.as_error());
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => Some(Ok(())),
|
||||
Err(error) if self.cancellation.is_cancelled() => Some(Err(error.into_error())),
|
||||
Err(error) => {
|
||||
self.logout_gateway(&stored.last_gateway).await;
|
||||
warn!("Cached gateway connection failed: {}", error.as_error());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cached_portal_credential(&self, server: &str) -> Option<Credential> {
|
||||
if self.args.cookie_on_stdin {
|
||||
return None;
|
||||
}
|
||||
let path = cookie_cache_path(self.args)?;
|
||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
info!("Using cached credential for fresh portal discovery");
|
||||
Some((&stored.auth_cookie).into())
|
||||
}
|
||||
|
||||
pub(super) fn clear_cookie_cache(&self) {
|
||||
if let Some(path) = cookie_cache_path(self.args) {
|
||||
cookie_store::clear(&path);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn connect_gateway_with_prelogin(
|
||||
&self,
|
||||
portal: &str,
|
||||
@@ -143,9 +165,13 @@ impl ConnectHandler<'_> {
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let gateway_browser_auth_allowed = true;
|
||||
let prelogin = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()).await?;
|
||||
let cred = self
|
||||
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
|
||||
let prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()) => result?,
|
||||
};
|
||||
let (_, cred) = self
|
||||
.obtain_credential_with_recovery(prelogin, gateway, gateway_browser_auth_allowed)
|
||||
.await?;
|
||||
|
||||
let login_session = self
|
||||
@@ -156,7 +182,7 @@ impl ConnectHandler<'_> {
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.cookie,
|
||||
&login_session.authentication,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
@@ -164,94 +190,108 @@ impl ConnectHandler<'_> {
|
||||
.map_err(GatewayConnectError::into_error)
|
||||
}
|
||||
|
||||
/// Connect to a gateway using the official client's auth flow:
|
||||
///
|
||||
/// 1. Call gateway prelogin and retain the response (SAML data is held as a fallback).
|
||||
/// 2. If the portal provided auth cookies, attempt gateway login using them.
|
||||
/// 3. If that login succeeds, proceed directly to the VPN connection.
|
||||
/// 4. If no portal auth cookies exist or portal-cookie login fails, use the retained gateway prelogin response to authenticate
|
||||
/// against the gateway (SAML or username/password) and obtain a gateway-issued
|
||||
/// credential.
|
||||
/// 5. Retry gateway login with the gateway credential (now carrying the gateway's
|
||||
/// `prelogin-cookie`) and connect on success.
|
||||
pub(super) async fn connect_gateway_with_fallback(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &Gateway,
|
||||
portal_cred: &AuthCookieCredential,
|
||||
config: &PortalConfig,
|
||||
selection: GatewaySelection,
|
||||
remaining: &[&Gateway],
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
let session = self
|
||||
.authenticate_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
portal_cred,
|
||||
config.default_browser().unwrap_or(false),
|
||||
GatewayLoginContext::new(gateway, selection).with_connect_method(config.connect_method()),
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
if !self.args.cookie_only && session.authentication.mode() == SessionMode::NonTunnel {
|
||||
if gateway.kind() != gpapi::gateway::GatewayKind::Internal {
|
||||
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||
"Non-tunnel authentication requires freshly discovered internal gateways"
|
||||
)));
|
||||
}
|
||||
return self
|
||||
.connect_internal_gateways(portal, config, portal_cred, gateway, session, remaining)
|
||||
.await
|
||||
.map_err(GatewayConnectError::after_establishment);
|
||||
}
|
||||
self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
&session.authentication,
|
||||
config.allow_extend_session().unwrap_or(false),
|
||||
session.extension_auth,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn authenticate_gateway(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
portal_cred: &AuthCookieCredential,
|
||||
allow_extend_session: bool,
|
||||
portal_config_default_browser: bool,
|
||||
gateway_context: GatewayLoginContext,
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
info!("Connecting to gateway with portal-cookie first, gateway prelogin fallback...");
|
||||
|
||||
) -> anyhow::Result<GatewayLoginSession> {
|
||||
self.check_cancelled()?;
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
let gateway_browser_auth_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
||||
|
||||
let gateway_prelogin = prelogin(gateway, &gp_params, self.prelogin_options(gateway_browser_auth_allowed))
|
||||
.await
|
||||
.map_err(GatewayConnectError::before_tunnel)?;
|
||||
let browser_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
||||
let gateway_prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(gateway, &gp_params, self.prelogin_options(browser_allowed)) => result?,
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
|
||||
if portal_cred.can_authenticate_gateway() {
|
||||
let portal_cred_for_login: Credential = portal_cred.into();
|
||||
let credential: Credential = portal_cred.into();
|
||||
match self
|
||||
.login_gateway(gateway, &portal_cred_for_login, &gp_params, Some(&gateway_context))
|
||||
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||
.await
|
||||
{
|
||||
Ok(login_session) => {
|
||||
info!("Gateway login with portal auth cookies succeeded");
|
||||
Ok(session) => {
|
||||
self.save_cookie_cache(portal, gateway, portal_cred);
|
||||
return self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.cookie,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
.await;
|
||||
return Ok(session);
|
||||
}
|
||||
Err(err) => {
|
||||
info!("Gateway login with portal auth cookies failed: {}", err);
|
||||
info!("Falling back to gateway prelogin authentication...");
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
let error = self.auth_recovery.borrow().terminal(error);
|
||||
if error
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
if error
|
||||
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
info!("Portal cookie login failed; using gateway prelogin authentication: {error}");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
|
||||
}
|
||||
|
||||
let gateway_cred = match self
|
||||
.obtain_credential(&gateway_prelogin, gateway, gateway_browser_auth_allowed)
|
||||
.await
|
||||
{
|
||||
Ok(cred) => cred,
|
||||
Err(err) => {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
return Err(GatewayConnectError::before_tunnel(err));
|
||||
}
|
||||
};
|
||||
|
||||
let login_session = match self
|
||||
.login_gateway(gateway, &gateway_cred, &gp_params, Some(&gateway_context))
|
||||
.await
|
||||
{
|
||||
Ok(login_session) => login_session,
|
||||
Err(err) => {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
return Err(GatewayConnectError::before_tunnel(err));
|
||||
}
|
||||
};
|
||||
|
||||
self
|
||||
.connect_gateway(
|
||||
portal,
|
||||
gateway,
|
||||
&login_session.cookie,
|
||||
allow_extend_session,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
let (_, credential) = self
|
||||
.obtain_credential_with_recovery(gateway_prelogin, gateway, browser_allowed)
|
||||
.await
|
||||
.inspect_err(|_| self.print_direct_gateway_recommendation(gateway))?;
|
||||
self.check_cancelled()?;
|
||||
let result = self
|
||||
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
|
||||
@@ -308,24 +348,39 @@ impl ConnectHandler<'_> {
|
||||
gateway_context: Option<&GatewayLoginContext>,
|
||||
) -> anyhow::Result<GatewayLoginSession> {
|
||||
let mut gp_params = gp_params.clone();
|
||||
gp_params.prepare_client_identity()?;
|
||||
let cancellation = self.cancellation.clone();
|
||||
let internal = gateway_context.is_some_and(|context| context.kind() == gpapi::gateway::GatewayKind::Internal);
|
||||
let mut client = GatewayLoginClient::new(gateway, gp_params)?;
|
||||
|
||||
loop {
|
||||
let login = match gateway_context {
|
||||
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?,
|
||||
None => gateway_login(gateway, cred, &gp_params).await?,
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
let login = client.login(cred, gateway_context, &cancellation).await?;
|
||||
|
||||
match login {
|
||||
GatewayLogin::Cookie(cookie) => {
|
||||
GatewayLogin::Authenticated(authentication) => {
|
||||
let descriptor = Gateway::new(gateway.to_string(), gateway.to_string());
|
||||
client.register_session(
|
||||
descriptor.clone(),
|
||||
authentication.clone(),
|
||||
&mut self.sessions.borrow_mut(),
|
||||
);
|
||||
self.check_cancelled()?;
|
||||
if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||
client
|
||||
.bind_non_tunnel(self.args.disable_ipv6, None, &cancellation)
|
||||
.await
|
||||
.map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?;
|
||||
client.update_registered_session(&descriptor, &authentication, &mut self.sessions.borrow_mut());
|
||||
}
|
||||
return Ok(GatewayLoginSession {
|
||||
cookie,
|
||||
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
|
||||
authentication,
|
||||
extension_auth: SessionExtensionAuth::new(cred.clone(), client),
|
||||
});
|
||||
}
|
||||
GatewayLogin::Mfa(message, input_str) => {
|
||||
let otp = Text::new(&message).prompt()?;
|
||||
gp_params.set_input_str(&input_str);
|
||||
gp_params.set_otp(&otp);
|
||||
client.respond_mfa(&input_str, &otp);
|
||||
|
||||
info!("Retrying gateway login with MFA...");
|
||||
}
|
||||
@@ -333,14 +388,15 @@ impl ConnectHandler<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_gateway(
|
||||
pub(super) async fn connect_gateway(
|
||||
&self,
|
||||
portal: &str,
|
||||
gateway: &str,
|
||||
cookie: &str,
|
||||
authentication: &GatewayAuthentication,
|
||||
allow_extend_session: bool,
|
||||
extension_auth: SessionExtensionAuth,
|
||||
) -> Result<(), GatewayConnectError> {
|
||||
let cookie = authentication.cookie();
|
||||
// --cookie-only: print the gateway cookie and exit without opening a tunnel.
|
||||
// No tun device is allocated, no root is required, and no logout is issued
|
||||
// against the gateway — the cookie remains valid for subsequent use.
|
||||
@@ -351,20 +407,39 @@ impl ConnectHandler<'_> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if authentication.mode() != SessionMode::Tunnel {
|
||||
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||
"Non-tunnel authentication requires fresh internal portal discovery"
|
||||
)));
|
||||
}
|
||||
self
|
||||
.check_cancelled()
|
||||
.map_err(GatewayConnectError::after_establishment)?;
|
||||
let identity_files = extension_auth
|
||||
.client_identity()
|
||||
.map(|identity| identity.write_files(None))
|
||||
.transpose()
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
let certificate = identity_files.as_ref().map(|files| files.certificate().to_owned());
|
||||
let sslkey = identity_files.as_ref().and_then(|files| files.key().map(str::to_owned));
|
||||
let key_password = extension_auth
|
||||
.client_identity()
|
||||
.and_then(|identity| identity.key_password())
|
||||
.map(str::to_owned);
|
||||
let mtu = self.args.mtu.unwrap_or(0);
|
||||
let (hip, csd_wrapper) = self.determine_hip_script();
|
||||
let hip_user = self.determine_hip_user();
|
||||
let csd_uid = get_uid(&hip_user).map_err(GatewayConnectError::before_tunnel)?;
|
||||
let os_profile = self.os_profile.borrow().clone();
|
||||
let hip_source = self
|
||||
.hip_source(os_profile.clone())
|
||||
.map_err(GatewayConnectError::before_establishment)?;
|
||||
|
||||
let session_ctx = build_session_context(SessionContextInput {
|
||||
portal: portal.to_string(),
|
||||
gateway: gateway.to_string(),
|
||||
cookie: cookie.to_string(),
|
||||
os_profile: os_profile.clone(),
|
||||
certificate: self.args.certificate.clone(),
|
||||
sslkey: self.args.sslkey.clone(),
|
||||
key_password: self.latest_key_password.borrow().clone(),
|
||||
certificate: certificate.clone(),
|
||||
sslkey: sslkey.clone(),
|
||||
key_password: key_password.clone(),
|
||||
disable_ipv6: self.args.disable_ipv6,
|
||||
extension_auth: Some(extension_auth),
|
||||
});
|
||||
@@ -372,12 +447,10 @@ impl ConnectHandler<'_> {
|
||||
.script(self.args.script.clone())
|
||||
.interface(self.args.interface.clone())
|
||||
.script_tun(self.args.script_tun)
|
||||
.certificate(self.args.certificate.clone())
|
||||
.sslkey(self.args.sslkey.clone())
|
||||
.key_password(self.latest_key_password.borrow().clone())
|
||||
.hip(hip)
|
||||
.csd_uid(csd_uid)
|
||||
.csd_wrapper(csd_wrapper)
|
||||
.certificate(certificate)
|
||||
.sslkey(sslkey)
|
||||
.key_password(key_password)
|
||||
.hip_source(hip_source)
|
||||
.reconnect_timeout(self.args.reconnect_timeout)
|
||||
.mtu(mtu)
|
||||
.disable_ipv6(self.args.disable_ipv6)
|
||||
@@ -385,9 +458,18 @@ impl ConnectHandler<'_> {
|
||||
.local_hostname(self.args.local_hostname.clone())
|
||||
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
|
||||
.no_xmlpost(self.args.no_xmlpost);
|
||||
#[cfg(target_os = "macos")]
|
||||
let vpn_builder = if self.args.script.is_none()
|
||||
&& std::env::var_os("GP_VPNC_SCRIPT").is_none_or(|value| value.is_empty())
|
||||
&& let Some(script) = common::binary_paths::bundled_vpnc_script()
|
||||
{
|
||||
vpn_builder.script_path(script.to_string_lossy().into_owned())
|
||||
} else {
|
||||
vpn_builder
|
||||
};
|
||||
let vpn = apply_os_profile(vpn_builder, &os_profile)
|
||||
.build()
|
||||
.map_err(|err| GatewayConnectError::before_tunnel(err.into()))?;
|
||||
.map_err(|err| GatewayConnectError::before_establishment(err.into()))?;
|
||||
|
||||
let vpn = Arc::new(vpn);
|
||||
let vpn_clone = vpn.clone();
|
||||
@@ -400,55 +482,97 @@ impl ConnectHandler<'_> {
|
||||
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
|
||||
let disconnect_requested = Arc::new(AtomicBool::new(false));
|
||||
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
|
||||
let cancellation = self.cancellation.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
shutdown_signal().await;
|
||||
let disconnect_task = tokio::spawn(async move {
|
||||
cancellation.cancelled().await;
|
||||
info!("Received the interrupt signal, disconnecting...");
|
||||
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
|
||||
vpn_clone.disconnect();
|
||||
});
|
||||
|
||||
let lock_file = self.shared_args.lock_file.to_path_buf();
|
||||
let lock_file_on_connect = lock_file.clone();
|
||||
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
|
||||
let pid_written = self.pid_written.clone();
|
||||
let log_format = self.shared_args.log_format;
|
||||
let connect_result = vpn.connect(move |vpn_session_info| {
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
write_pid_file(&lock_file_on_connect);
|
||||
let session_cancellation = self.cancellation.clone();
|
||||
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
|
||||
self.sessions.borrow_mut().relinquish_gateway(gateway);
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
vpn.connect(move |vpn_session_info| {
|
||||
if session_cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
|
||||
let _ = established_tx.send(());
|
||||
|
||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||
info!("VPN session info: {}", session_info.log_summary());
|
||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||
return;
|
||||
};
|
||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||
info!("VPN session info: {}", session_info.log_summary());
|
||||
|
||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||
session_task_on_connect.lock().unwrap().replace(task);
|
||||
})
|
||||
});
|
||||
tokio::pin!(worker);
|
||||
let connect_result = tokio::select! {
|
||||
result = &mut worker => result,
|
||||
established = established_rx => {
|
||||
if established.is_ok() {
|
||||
let unused = self.sessions.borrow().members().iter()
|
||||
.filter(|session| session.gateway.server() != gateway)
|
||||
.map(|session| session.gateway.server().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
for server in unused {
|
||||
self.logout_gateway(&server).await;
|
||||
}
|
||||
}
|
||||
(&mut worker).await
|
||||
}
|
||||
};
|
||||
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
||||
disconnect_task.abort();
|
||||
let _ = disconnect_task.await;
|
||||
|
||||
if let Some(task) = session_task.lock().unwrap().take() {
|
||||
let session_task = { session_task.lock().unwrap().take() };
|
||||
if let Some(task) = session_task {
|
||||
task.abort();
|
||||
}
|
||||
|
||||
if fs::metadata(&lock_file).is_ok() {
|
||||
info!("Removing PID file");
|
||||
fs::remove_file(&lock_file).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
||||
let _ = task.await;
|
||||
}
|
||||
|
||||
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
||||
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
|
||||
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
|
||||
}
|
||||
|
||||
fn determine_hip_script(&self) -> (bool, Option<String>) {
|
||||
if let Some(hip) = &self.args.hip {
|
||||
return if hip.is_empty() {
|
||||
(true, None)
|
||||
} else {
|
||||
(true, Some(hip.clone()))
|
||||
};
|
||||
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
|
||||
let user = self.determine_hip_user();
|
||||
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
|
||||
match script {
|
||||
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
|
||||
Some(_) => {
|
||||
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
|
||||
Ok(HipSource::Generator(Arc::new(move |request, control| {
|
||||
let input = gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
};
|
||||
gphip::generate_report_with_control(&input, &|| control.check())
|
||||
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
|
||||
})))
|
||||
}
|
||||
None => {
|
||||
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
|
||||
Ok(HipSource::Disabled)
|
||||
}
|
||||
}
|
||||
|
||||
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
|
||||
}
|
||||
|
||||
fn determine_hip_user(&self) -> Option<String> {
|
||||
@@ -475,9 +599,9 @@ fn classify_openconnect_result(
|
||||
|
||||
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
|
||||
if tunnel_established {
|
||||
Err(GatewayConnectError::after_tunnel(error))
|
||||
Err(GatewayConnectError::after_establishment(error))
|
||||
} else {
|
||||
Err(GatewayConnectError::before_tunnel(error))
|
||||
Err(GatewayConnectError::before_establishment(error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,22 +609,23 @@ fn direct_gateway_command(gateway: &str) -> String {
|
||||
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
||||
}
|
||||
|
||||
fn write_pid_file(lock_file: &Path) {
|
||||
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
|
||||
let pid = std::process::id();
|
||||
|
||||
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
||||
warn!("Failed to write PID file: {}", err);
|
||||
false
|
||||
} else {
|
||||
info!("Wrote PID {} to {}", pid, lock_file.display());
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
|
||||
if let Some(user) = user {
|
||||
get_user_by_name(user).map(|user| user.uid())
|
||||
} else {
|
||||
Ok(uzers::get_effective_uid())
|
||||
}
|
||||
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
|
||||
user
|
||||
.as_ref()
|
||||
.map(|user| get_user_by_name(user).map(|user| user.uid()))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
|
||||
@@ -517,8 +642,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hip_script_defaults_to_process_effective_uid() {
|
||||
assert_eq!(get_uid(&None).unwrap(), uzers::get_effective_uid());
|
||||
fn hip_script_defaults_to_inherited_process_identity() {
|
||||
assert_eq!(get_uid(&None).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -530,7 +655,7 @@ mod tests {
|
||||
fn explicit_hip_user_resolves_to_the_selected_account() {
|
||||
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
|
||||
let name = current.name().to_string_lossy().into_owned();
|
||||
assert_eq!(get_uid(&Some(name)).unwrap(), current.uid());
|
||||
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -543,14 +668,14 @@ mod tests {
|
||||
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
|
||||
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
|
||||
|
||||
assert!(err.is_before_tunnel());
|
||||
assert!(err.is_before_establishment());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
|
||||
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
|
||||
|
||||
assert!(!err.is_before_tunnel());
|
||||
assert!(!err.is_before_establishment());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -563,7 +688,7 @@ mod tests {
|
||||
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
|
||||
.expect_err("unexpected interrupt should fail");
|
||||
|
||||
assert!(!err.is_before_tunnel());
|
||||
assert!(!err.is_before_establishment());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::{
|
||||
credential::AuthCookieCredential,
|
||||
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||
portal::PortalConfig,
|
||||
process::collection::CollectionControl,
|
||||
session::{
|
||||
MaintenanceState, SessionEndReason, SessionMode,
|
||||
network::PhysicalNetwork,
|
||||
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||
},
|
||||
};
|
||||
use log::{info, warn};
|
||||
|
||||
use super::ConnectHandler;
|
||||
|
||||
impl ConnectHandler<'_> {
|
||||
pub(super) async fn connect_internal_gateways(
|
||||
&self,
|
||||
portal: &str,
|
||||
config: &PortalConfig,
|
||||
credential: &AuthCookieCredential,
|
||||
first_gateway: &Gateway,
|
||||
first_session: super::gateway::GatewayLoginSession,
|
||||
remaining: &[&Gateway],
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(remaining.len() < 64, "Too many internal non-tunnel candidates");
|
||||
let mut hosts = std::collections::HashSet::new();
|
||||
for gateway in std::iter::once(first_gateway).chain(remaining.iter().copied()) {
|
||||
ensure!(
|
||||
gateway.kind() == gpapi::gateway::GatewayKind::Internal,
|
||||
"Non-tunnel candidates must be internal"
|
||||
);
|
||||
ensure!(
|
||||
hosts.insert(gpapi::utils::normalize_server(gateway.server())?),
|
||||
"Duplicate internal gateway"
|
||||
);
|
||||
}
|
||||
let mut authenticated = vec![(first_gateway, first_session)];
|
||||
for gateway in remaining.iter().copied() {
|
||||
self.check_cancelled()?;
|
||||
let context =
|
||||
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(config.connect_method());
|
||||
match self
|
||||
.authenticate_gateway(
|
||||
portal,
|
||||
gateway.server(),
|
||||
credential,
|
||||
config.default_browser().unwrap_or(false),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(session) => authenticated.push((gateway, session)),
|
||||
Err(error) => {
|
||||
self.logout_gateway(gateway.server()).await;
|
||||
self.check_cancelled()?;
|
||||
if self.auth_recovery.borrow().dmabuf_disabled() {
|
||||
return Err(self.auth_recovery.borrow().terminal(error));
|
||||
}
|
||||
warn!("Internal gateway {gateway} authentication failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
self.check_cancelled()?;
|
||||
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
|
||||
ensure!(
|
||||
internal_session_mode(modes)? == SessionMode::NonTunnel,
|
||||
"Expected non-tunnel authentication"
|
||||
);
|
||||
self.run_internal_session(config, &authenticated).await
|
||||
}
|
||||
|
||||
async fn run_internal_session(
|
||||
&self,
|
||||
config: &PortalConfig,
|
||||
authenticated: &[(&gpapi::gateway::Gateway, super::gateway::GatewayLoginSession)],
|
||||
) -> anyhow::Result<()> {
|
||||
let cancellation = self.cancellation.clone();
|
||||
let network = Arc::new(PhysicalNetwork::capture_controlled(&cancellation).await?);
|
||||
let detection = config.internal_detection().cloned();
|
||||
let bindings = authenticated
|
||||
.iter()
|
||||
.map(|(_, session)| {
|
||||
session
|
||||
.extension_auth
|
||||
.binding()
|
||||
.cloned()
|
||||
.context("Non-tunnel binding is missing")
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
for binding in &bindings {
|
||||
network
|
||||
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||
.await?;
|
||||
}
|
||||
let policy = config
|
||||
.internal_session_policy()
|
||||
.context("Invalid internal session policy")?;
|
||||
let profile = self.os_profile.borrow().clone();
|
||||
let source = if policy.collect_hip_data() {
|
||||
self.hip_source(profile.clone())?
|
||||
} else {
|
||||
openconnect::HipSource::Disabled
|
||||
};
|
||||
let source = Arc::new(source);
|
||||
let validate_network = network.clone();
|
||||
let validate_detection = detection.clone();
|
||||
let callbacks = SessionCallbacks {
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context: gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
},
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
&openconnect::HipRequest {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
client_version: profile.client_version().into(),
|
||||
client_os: profile.client_os().as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: Some(profile.host_id().into()),
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
},
|
||||
&|| control.check(),
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(|_, _| {}),
|
||||
status_changed: Arc::new(|member| match member.maintenance {
|
||||
MaintenanceState::Healthy => info!(
|
||||
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
|
||||
member.gateway, member.client_ip, member.client_ipv6
|
||||
),
|
||||
state => info!("Internal gateway {}: {state:?}", member.gateway),
|
||||
}),
|
||||
validate_network: Arc::new(move |cancellation| {
|
||||
let network = validate_network.clone();
|
||||
let detection = validate_detection.clone();
|
||||
let bindings = bindings.clone();
|
||||
Box::pin(async move {
|
||||
for binding in &bindings {
|
||||
network
|
||||
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}),
|
||||
};
|
||||
let monitor_cancel = cancellation.child_token();
|
||||
let monitor_token = monitor_cancel.clone();
|
||||
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||
let monitor = tokio::spawn(async move {
|
||||
match network.wait_for_change(detection, monitor_token).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) | Err(_) => {
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// The PID spans maintenance and cleanup, including initialization before the
|
||||
// first successful HIP exchange. The outer handler owns final session logout.
|
||||
self.pid_written.store(
|
||||
super::gateway::write_pid_file(self.shared_args.lock_file),
|
||||
std::sync::atomic::Ordering::SeqCst,
|
||||
);
|
||||
let mut sessions = self.sessions.take();
|
||||
let result = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
|
||||
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
|
||||
})
|
||||
.await;
|
||||
self.sessions.replace(sessions);
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Internal network monitor failed")?;
|
||||
match result? {
|
||||
SessionExit::Disconnected => Ok(()),
|
||||
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn logout_gateway(&self, gateway: &str) {
|
||||
let mut sessions = self.sessions.take();
|
||||
sessions.logout_gateway(gateway).await;
|
||||
self.sessions.replace(sessions);
|
||||
}
|
||||
}
|
||||
|
||||
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
|
||||
let mut modes = modes;
|
||||
let mode = modes.next().context("No internal gateway authenticated successfully")?;
|
||||
ensure!(
|
||||
modes.all(|candidate| candidate == mode),
|
||||
"Mixed tunnel and non-tunnel internal gateways are unsupported; select a gateway explicitly"
|
||||
);
|
||||
Ok(mode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn internal_modes_reject_mixed_and_empty_sets() {
|
||||
assert!(internal_session_mode([].into_iter()).is_err());
|
||||
assert!(internal_session_mode([SessionMode::Tunnel, SessionMode::NonTunnel].into_iter()).is_err());
|
||||
assert_eq!(
|
||||
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
|
||||
SessionMode::NonTunnel
|
||||
);
|
||||
assert_eq!(
|
||||
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
|
||||
SessionMode::Tunnel
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,25 @@
|
||||
mod args;
|
||||
mod credential;
|
||||
#[cfg(test)]
|
||||
mod flow_tests;
|
||||
mod gateway;
|
||||
mod internal;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use gpapi::{
|
||||
clap::report,
|
||||
error::PortalError,
|
||||
gateway::{GatewayLoginContext, GatewaySelection},
|
||||
gateway::GatewaySelection,
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
portal::{PreloginOptions, prelogin, retrieve_config},
|
||||
session::GatewaySessions,
|
||||
utils::request::RequestIdentityError,
|
||||
};
|
||||
use inquire::{Password, PasswordDisplayMode, Select};
|
||||
@@ -25,6 +33,7 @@ use credential::CleanAuthState;
|
||||
use gateway::GatewayConnectError;
|
||||
|
||||
pub(crate) struct ConnectHandler<'a> {
|
||||
cancellation: tokio_util::sync::CancellationToken,
|
||||
args: &'a ConnectArgs,
|
||||
shared_args: &'a SharedArgs<'a>,
|
||||
os_profile: RefCell<OsProfile>,
|
||||
@@ -32,6 +41,11 @@ pub(crate) struct ConnectHandler<'a> {
|
||||
password_from_stdin: RefCell<Option<String>>,
|
||||
cookie_from_stdin: RefCell<Option<String>>,
|
||||
clean_auth_state: RefCell<CleanAuthState>,
|
||||
#[cfg(test)]
|
||||
auth_attempt_fixture: RefCell<credential::AuthAttemptFixture>,
|
||||
auth_recovery: RefCell<gpapi::process::rendering_recovery::RecoveryState>,
|
||||
sessions: RefCell<GatewaySessions>,
|
||||
pid_written: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl<'a> ConnectHandler<'a> {
|
||||
@@ -44,6 +58,7 @@ impl<'a> ConnectHandler<'a> {
|
||||
let clean_auth = false;
|
||||
|
||||
Self {
|
||||
cancellation: tokio_util::sync::CancellationToken::new(),
|
||||
args,
|
||||
shared_args,
|
||||
os_profile: RefCell::new(build_os_profile(args)),
|
||||
@@ -51,6 +66,11 @@ impl<'a> ConnectHandler<'a> {
|
||||
password_from_stdin: Default::default(),
|
||||
cookie_from_stdin: Default::default(),
|
||||
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
|
||||
#[cfg(test)]
|
||||
auth_attempt_fixture: Default::default(),
|
||||
auth_recovery: RefCell::default(),
|
||||
sessions: RefCell::default(),
|
||||
pid_written: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +113,38 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
let cancellation = self.cancellation.clone();
|
||||
let signal = tokio::spawn(async move {
|
||||
gpapi::utils::shutdown_signal().await;
|
||||
cancellation.cancel();
|
||||
});
|
||||
self.auth_recovery.replace(Default::default());
|
||||
let result = self.handle_attempt().await;
|
||||
let sessions = self.sessions.take();
|
||||
if self.args.cookie_only && result.is_ok() {
|
||||
sessions.relinquish();
|
||||
} else {
|
||||
sessions.logout().await;
|
||||
}
|
||||
if self.pid_written.load(Ordering::SeqCst) {
|
||||
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
|
||||
warn!("Failed to remove PID file: {error}");
|
||||
}
|
||||
}
|
||||
signal.abort();
|
||||
let _ = signal.await;
|
||||
result
|
||||
}
|
||||
|
||||
fn check_cancelled(&self) -> anyhow::Result<()> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
Err(gpapi::auth::AuthenticationCancelled.into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_attempt(&self) -> anyhow::Result<()> {
|
||||
if self.args.browser_listen.is_some()
|
||||
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
@@ -107,10 +159,18 @@ impl<'a> ConnectHandler<'a> {
|
||||
self.latest_key_password.replace(self.args.key_password.clone());
|
||||
|
||||
loop {
|
||||
let Err(err) = self.handle_impl().await else {
|
||||
self.check_cancelled()?;
|
||||
let result = self.handle_impl().await;
|
||||
let Err(err) = self.auth_recovery.borrow().finish(result) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if err
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
|
||||
return Err(err);
|
||||
};
|
||||
@@ -144,6 +204,7 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
||||
self.check_cancelled()?;
|
||||
let server = self.args.server.as_str();
|
||||
let as_gateway = self.args.as_gateway;
|
||||
|
||||
@@ -155,15 +216,23 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
|
||||
if !self.args.cookie_on_stdin {
|
||||
if let Some(()) = self.try_cached_cookie(server).await {
|
||||
return Ok(());
|
||||
if let Some(result) = self.try_cached_cookie(server).await {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
self.check_cancelled()?;
|
||||
|
||||
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let err = self.auth_recovery.borrow().terminal(err);
|
||||
if err
|
||||
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
|
||||
.is_some()
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
warn!("Failed to connect portal with prelogin: {}", err);
|
||||
if err.root_cause().downcast_ref::<PortalError>().is_some() {
|
||||
info!("Trying the gateway authentication workflow...");
|
||||
@@ -190,10 +259,38 @@ impl<'a> ConnectHandler<'a> {
|
||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||
let gp_params = self.build_gp_params();
|
||||
|
||||
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
|
||||
let mut prelogin = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||
result = prelogin(portal, &gp_params, self.prelogin_options(false)) => result?,
|
||||
};
|
||||
|
||||
let cred = self.obtain_credential(&prelogin, portal, false).await?;
|
||||
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
|
||||
let cached = self.cached_portal_credential(portal);
|
||||
let cached_config = match cached {
|
||||
Some(cred) => match retrieve_config(portal, &cred, &gp_params, &self.cancellation).await {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let (cred, mut portal_config) = match cached_config {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
let (replacement, cred) = self
|
||||
.obtain_credential_with_recovery(prelogin.clone(), portal, false)
|
||||
.await?;
|
||||
prelogin = replacement;
|
||||
self.check_cancelled()?;
|
||||
let config = retrieve_config(portal, &cred, &gp_params, &self.cancellation).await?;
|
||||
(cred, config)
|
||||
}
|
||||
};
|
||||
self.check_cancelled()?;
|
||||
|
||||
portal_config.sort_gateways(prelogin.region());
|
||||
|
||||
@@ -201,7 +298,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
Some(password) => portal_config.auth_cookie().clone().with_password(password),
|
||||
None => portal_config.auth_cookie().clone(),
|
||||
};
|
||||
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
|
||||
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
|
||||
info!("Portal config default-browser: {}", portal_config_default_browser);
|
||||
|
||||
@@ -217,29 +313,27 @@ impl<'a> ConnectHandler<'a> {
|
||||
);
|
||||
|
||||
let mut last_err: Option<anyhow::Error> = None;
|
||||
for gateway in &gateways {
|
||||
for (index, gateway) in gateways.iter().enumerate() {
|
||||
info!("Auto-gateway: attempting gateway {}", gateway);
|
||||
let gateway_context =
|
||||
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(portal_config.connect_method());
|
||||
|
||||
match self
|
||||
.connect_gateway_with_fallback(
|
||||
portal,
|
||||
gateway.server(),
|
||||
gateway,
|
||||
&auth_cookie,
|
||||
allow_extend_session,
|
||||
portal_config_default_browser,
|
||||
gateway_context,
|
||||
&portal_config,
|
||||
GatewaySelection::Auto,
|
||||
&gateways[index + 1..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
if !err.is_before_tunnel() {
|
||||
return Err(err.into_error());
|
||||
self.logout_gateway(gateway.server()).await;
|
||||
if self.auth_recovery.borrow().dmabuf_disabled() || !err.is_before_establishment() {
|
||||
return Err(self.auth_recovery.borrow().terminal(err.into_error()));
|
||||
}
|
||||
warn!(
|
||||
"Auto-gateway: gateway {} failed before tunnel setup: {}",
|
||||
"Auto-gateway: gateway {} failed before session establishment: {}",
|
||||
gateway,
|
||||
err.as_error()
|
||||
);
|
||||
@@ -270,6 +364,9 @@ impl<'a> ConnectHandler<'a> {
|
||||
None => {
|
||||
let gateways = portal_config.gateways();
|
||||
|
||||
if gateways.is_empty() {
|
||||
bail!("No gateways available in portal configuration");
|
||||
}
|
||||
if gateways.len() > 1 {
|
||||
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
||||
.with_vim_mode(true)
|
||||
@@ -283,18 +380,14 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
};
|
||||
|
||||
let gateway = selected_gateway.server();
|
||||
let gateway_context =
|
||||
GatewayLoginContext::new(selected_gateway, gateway_selection).with_connect_method(portal_config.connect_method());
|
||||
|
||||
self
|
||||
.connect_gateway_with_fallback(
|
||||
portal,
|
||||
gateway,
|
||||
selected_gateway,
|
||||
&auth_cookie,
|
||||
allow_extend_session,
|
||||
portal_config_default_browser,
|
||||
gateway_context,
|
||||
&portal_config,
|
||||
gateway_selection,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.map_err(GatewayConnectError::into_error)
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
use std::{
|
||||
collections::BTreeMap, fs::OpenOptions, io::Write, os::unix::fs::OpenOptionsExt, path::PathBuf, process::Stdio,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use clap::Args;
|
||||
use common::binary_paths;
|
||||
use serde::Serialize;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
const COLLECTOR: &str = include_str!("../../../scripts/collect-diagnostics.sh");
|
||||
const MAX_REPORT_BYTES: usize = 64 * 1024;
|
||||
const FIELDS: &[&str] = &[
|
||||
"os",
|
||||
"os_version",
|
||||
"kernel",
|
||||
"architecture",
|
||||
"execution_user",
|
||||
"ssh_session",
|
||||
"virtualization",
|
||||
"gpclient_path",
|
||||
"gpclient_version",
|
||||
"gpauth_path",
|
||||
"gpauth_version",
|
||||
"gpgui_path",
|
||||
"gpgui_version",
|
||||
"display_protocol",
|
||||
"graphics",
|
||||
"graphics_packages",
|
||||
"desktop_version",
|
||||
"env.XDG_CURRENT_DESKTOP",
|
||||
"env.XDG_SESSION_DESKTOP",
|
||||
"env.XDG_SESSION_TYPE",
|
||||
"env.DESKTOP_SESSION",
|
||||
"env.WEBKIT_DISABLE_DMABUF_RENDERER",
|
||||
"env.WEBKIT_DISABLE_COMPOSITING_MODE",
|
||||
"env.LIBGL_ALWAYS_SOFTWARE",
|
||||
"env.__NV_DISABLE_EXPLICIT_SYNC",
|
||||
"env.GDK_BACKEND",
|
||||
"env.GDK_GL",
|
||||
];
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct DiagnosticsArgs {
|
||||
/// Print the report as JSON instead of text
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
/// Save the report to a new file instead of stdout (existing files are preserved)
|
||||
#[arg(long, value_name = "PATH")]
|
||||
output: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum ProbeStatus {
|
||||
Ok,
|
||||
Unset,
|
||||
Unavailable,
|
||||
Failed,
|
||||
TimedOut,
|
||||
NotApplicable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct DiagnosticField {
|
||||
status: ProbeStatus,
|
||||
value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct DiagnosticsReport {
|
||||
schema_version: u32,
|
||||
fields: BTreeMap<String, DiagnosticField>,
|
||||
}
|
||||
|
||||
impl DiagnosticsReport {
|
||||
fn parse(bytes: &[u8]) -> anyhow::Result<Self> {
|
||||
ensure!(
|
||||
bytes.len() <= MAX_REPORT_BYTES,
|
||||
"Diagnostics report exceeds its size limit"
|
||||
);
|
||||
let mut fields = BTreeMap::new();
|
||||
let mut schema_version = None;
|
||||
for raw_line in bytes.split(|byte| *byte == b'\n').filter(|line| !line.is_empty()) {
|
||||
let line = String::from_utf8_lossy(raw_line);
|
||||
let (name, rest) = line.split_once(": ").context("Invalid diagnostics record")?;
|
||||
let (status, value) = rest.split_once(": ").context("Invalid diagnostics status")?;
|
||||
let raw_value_length = raw_line
|
||||
.len()
|
||||
.checked_sub(name.len() + status.len() + 4)
|
||||
.context("Invalid diagnostics framing")?;
|
||||
ensure!(raw_value_length <= 512, "Diagnostics field exceeds its size limit");
|
||||
ensure!(
|
||||
!value.chars().any(|c| c.is_ascii_control()),
|
||||
"Invalid diagnostics value"
|
||||
);
|
||||
let status = match status {
|
||||
"ok" => ProbeStatus::Ok,
|
||||
"unset" => ProbeStatus::Unset,
|
||||
"unavailable" => ProbeStatus::Unavailable,
|
||||
"failed" => ProbeStatus::Failed,
|
||||
"timed_out" => ProbeStatus::TimedOut,
|
||||
"not_applicable" => ProbeStatus::NotApplicable,
|
||||
_ => anyhow::bail!("Unknown diagnostics status"),
|
||||
};
|
||||
if name == "schema_version" {
|
||||
ensure!(schema_version.is_none(), "Duplicate diagnostics schema version");
|
||||
ensure!(
|
||||
matches!(status, ProbeStatus::Ok) && value == "1",
|
||||
"Unsupported diagnostics schema"
|
||||
);
|
||||
schema_version = Some(1);
|
||||
continue;
|
||||
}
|
||||
ensure!(FIELDS.contains(&name), "Unknown diagnostics field");
|
||||
let value = if matches!(status, ProbeStatus::Ok) {
|
||||
let mut normalized = String::new();
|
||||
for character in value.chars() {
|
||||
let character = if character.is_control() { ' ' } else { character };
|
||||
if normalized.len() + character.len_utf8() > 512 {
|
||||
break;
|
||||
}
|
||||
normalized.push(character);
|
||||
}
|
||||
Some(normalized)
|
||||
} else {
|
||||
ensure!(value.is_empty(), "Unexpected value for unavailable diagnostics field");
|
||||
None
|
||||
};
|
||||
ensure!(
|
||||
fields
|
||||
.insert(name.to_owned(), DiagnosticField { status, value })
|
||||
.is_none(),
|
||||
"Duplicate diagnostics field"
|
||||
);
|
||||
}
|
||||
ensure!(fields.len() == FIELDS.len(), "Incomplete diagnostics report");
|
||||
Ok(Self {
|
||||
schema_version: schema_version.context("Missing diagnostics schema version")?,
|
||||
fields,
|
||||
})
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let mut text = format!("schema_version: ok: {}\n", self.schema_version);
|
||||
for name in FIELDS {
|
||||
let field = &self.fields[*name];
|
||||
let status = match field.status {
|
||||
ProbeStatus::Ok => "ok",
|
||||
ProbeStatus::Unset => "unset",
|
||||
ProbeStatus::Unavailable => "unavailable",
|
||||
ProbeStatus::Failed => "failed",
|
||||
ProbeStatus::TimedOut => "timed_out",
|
||||
ProbeStatus::NotApplicable => "not_applicable",
|
||||
};
|
||||
text.push_str(&format!(
|
||||
"{name}: {status}: {}\n",
|
||||
field.value.as_deref().unwrap_or_default()
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
impl DiagnosticsArgs {
|
||||
pub(crate) async fn run(&self, version: &str) -> anyhow::Result<()> {
|
||||
let mut child = Command::new("/bin/sh")
|
||||
.args(["-s", "--", "--client-version", version, "--client-path"])
|
||||
.arg(std::env::current_exe().context("Cannot locate gpclient")?)
|
||||
.arg("--auth-path")
|
||||
.arg(binary_paths::gpauth())
|
||||
.arg("--gui-path")
|
||||
.arg(binary_paths::gpgui())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.context("Cannot start diagnostics collector")?;
|
||||
let mut input = child.stdin.take().context("Collector input is unavailable")?;
|
||||
let (_, output) = tokio::try_join!(
|
||||
async move {
|
||||
input.write_all(COLLECTOR.as_bytes()).await?;
|
||||
drop(input);
|
||||
Ok::<_, std::io::Error>(())
|
||||
},
|
||||
child.wait_with_output(),
|
||||
)
|
||||
.context("Diagnostics collection failed")?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"Diagnostics collector exited with {}",
|
||||
output.status
|
||||
);
|
||||
let report = DiagnosticsReport::parse(&output.stdout)?;
|
||||
let content = if self.json {
|
||||
format!("{}\n", serde_json::to_string_pretty(&report)?)
|
||||
} else {
|
||||
report.text()
|
||||
};
|
||||
if let Some(path) = &self.output {
|
||||
save_report(path, &content)?;
|
||||
} else {
|
||||
std::io::stdout().lock().write_all(content.as_bytes())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn save_report(path: &std::path::Path, content: &str) -> anyhow::Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.context("Cannot create diagnostics file; use a new path")?;
|
||||
file
|
||||
.write_all(content.as_bytes())
|
||||
.context("Cannot save diagnostics report")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_report() -> String {
|
||||
let mut text = String::from("schema_version: ok: 1\n");
|
||||
for name in FIELDS {
|
||||
text.push_str(&format!("{name}: unavailable: \n"));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_preserves_collected_values_and_distinguishes_missing_probes() {
|
||||
let text = sample_report().replace("os: unavailable: ", "os: ok: FreeBSD");
|
||||
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
|
||||
let json = serde_json::to_value(report).unwrap();
|
||||
assert_eq!(json["schema_version"], 1);
|
||||
assert_eq!(json["fields"]["os"]["value"], "FreeBSD");
|
||||
assert_eq!(json["fields"]["graphics"]["status"], "unavailable");
|
||||
assert!(json["fields"]["graphics"]["value"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_injected_records_are_rejected() {
|
||||
let good = sample_report();
|
||||
for bad in [
|
||||
good.replace("os: unavailable: ", "os: mystery: "),
|
||||
good.replace("os: unavailable: ", "os: ok: text\u{1b}[31m"),
|
||||
good.replace("os: unavailable: ", "os: ok: value\nsecret: ok: token"),
|
||||
format!("{good}os: ok: duplicate\n"),
|
||||
good.replace("schema_version: ok: 1", "schema_version: ok: 2"),
|
||||
good.replace("os: unavailable: \n", ""),
|
||||
] {
|
||||
assert!(DiagnosticsReport::parse(bad.as_bytes()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_and_unicode_controls_produce_a_bounded_readable_value() {
|
||||
let mut bytes = sample_report()
|
||||
.replace("os: unavailable: ", "os: ok: REPLACE")
|
||||
.into_bytes();
|
||||
let start = bytes.windows(7).position(|value| value == b"REPLACE").unwrap();
|
||||
bytes.splice(start..start + 7, [0xff; 500]);
|
||||
let report = DiagnosticsReport::parse(&bytes).unwrap();
|
||||
let value = report.fields["os"].value.as_ref().unwrap();
|
||||
assert!(value.len() <= 512);
|
||||
assert!(value.starts_with('\u{fffd}'));
|
||||
let text = sample_report().replace("os: unavailable: ", "os: ok: Test\u{85}OS");
|
||||
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
|
||||
assert_eq!(report.fields["os"].value.as_deref(), Some("Test OS"));
|
||||
assert!(report.text().contains("os: ok: Test OS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_report_does_not_overwrite_existing_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("diagnostics.txt");
|
||||
save_report(&path, "first").unwrap();
|
||||
assert!(save_report(&path, "second").is_err());
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "first");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Args;
|
||||
use gpapi::{
|
||||
clap::args::Os,
|
||||
os_profile::{ClientOs, OsProfileBuilder},
|
||||
process::collection::CollectionBudget,
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput, generate_report};
|
||||
use gphip::{ReportContext, ReportInput, generate_report_with_control};
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct HipArgs {
|
||||
@@ -42,13 +45,17 @@ impl<'a> HipHandler<'a> {
|
||||
}
|
||||
|
||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let client_os = ClientOs::from(self.args.client_os);
|
||||
let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone());
|
||||
if let Some(os_version) = self.args.os_version.as_deref() {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
if let Some(host_id) = self.args.host_id.as_deref() {
|
||||
builder = builder.host_id_override(host_id);
|
||||
}
|
||||
let input = ReportInput {
|
||||
profile: builder.build(),
|
||||
profile: builder.build_with_control(&budget)?,
|
||||
context: ReportContext::Connected {
|
||||
cookie: self.args.cookie.clone(),
|
||||
client_ip: self.args.client_ip.clone(),
|
||||
@@ -56,7 +63,7 @@ impl<'a> HipHandler<'a> {
|
||||
md5: self.args.md5.clone(),
|
||||
},
|
||||
};
|
||||
println!("{}", generate_report(&input)?);
|
||||
println!("{}", generate_report_with_control(&input, &budget)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{collections::HashMap, fs, path::PathBuf};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use std::process::{Command, ExitStatus};
|
||||
@@ -11,10 +11,7 @@ use clap::Args;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use common::binary_paths;
|
||||
use directories::ProjectDirs;
|
||||
use gpapi::{
|
||||
process::service_launcher::ServiceLauncher,
|
||||
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
|
||||
};
|
||||
use gpapi::{process::desktop_launcher::DesktopLauncher, utils::endpoint::http_endpoint};
|
||||
use log::info;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -69,27 +66,13 @@ impl<'a> LaunchGuiHandler<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tokio::spawn(async move {
|
||||
shutdown_signal().await;
|
||||
info!("Shutting down...");
|
||||
});
|
||||
|
||||
let log_file = get_log_file()?;
|
||||
let log_file_path = log_file.to_string_lossy().to_string();
|
||||
|
||||
info!("Log file: {}", log_file_path);
|
||||
|
||||
let mut extra_envs = HashMap::<String, String>::new();
|
||||
extra_envs.insert("GP_LOG_FILE".into(), log_file_path.clone());
|
||||
|
||||
// Persist the environment variables to a file
|
||||
let env_file = env_utils::persist_env_vars(Some(extra_envs))?;
|
||||
let env_file = env_file.into_temp_path();
|
||||
let env_file_path = env_file.to_string_lossy().to_string();
|
||||
|
||||
let exit_status = ServiceLauncher::new()
|
||||
let exit_status = DesktopLauncher::new(env!("CARGO_PKG_VERSION"))
|
||||
.minimized(self.args.minimized)
|
||||
.env_file(&env_file_path)
|
||||
.log_file(&log_file_path)
|
||||
.launch()
|
||||
.await?;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod cli;
|
||||
mod connect;
|
||||
mod diagnostics;
|
||||
mod disconnect;
|
||||
mod hip;
|
||||
mod launch_gui;
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
use std::{os::unix::fs::PermissionsExt, process::Stdio, time::Duration};
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
fn executable(dir: &std::path::Path, name: &str, body: &str) {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedded_collector_finishes_without_recursing_or_exposing_private_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("bin");
|
||||
std::fs::create_dir(&bin).unwrap();
|
||||
executable(
|
||||
&bin,
|
||||
"uname",
|
||||
"case \"$1\" in -s) echo Linux ;; -m) echo aarch64 ;; *) echo test-kernel ;; esac",
|
||||
);
|
||||
executable(&bin, "gpclient", "echo unexpected-recursion >&2; exit 99");
|
||||
executable(&bin, "systemd-detect-virt", "echo kvm");
|
||||
executable(
|
||||
&bin,
|
||||
"lspci",
|
||||
"echo '00:02.0 VGA compatible controller: Test GPU'; echo ' Kernel driver in use: test'",
|
||||
);
|
||||
executable(&bin, "pacman", "echo 'gtk3 test-version'");
|
||||
let report_file = dir.path().join("report.json");
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(30),
|
||||
Command::new(env!("CARGO_BIN_EXE_gpclient"))
|
||||
.args(["--fix-openssl", "diagnostics", "--json", "--output"])
|
||||
.arg(&report_file)
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
|
||||
.env("GP_DIAGNOSTICS_PRIVATE_TOKEN", "secret-value-must-not-appear")
|
||||
.env("XDG_CURRENT_DESKTOP", "TestDesktop\nInjected: secret")
|
||||
.stdin(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.expect("collector must close stdin and terminate")
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(output.stdout.is_empty());
|
||||
let text = std::fs::read_to_string(&report_file).unwrap();
|
||||
assert!(!text.contains("secret-value-must-not-appear"));
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("unexpected-recursion"));
|
||||
let report: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(report["schema_version"], 1);
|
||||
assert_eq!(report["fields"]["os"]["value"], "Linux");
|
||||
assert!(
|
||||
report["fields"]["gpclient_version"]["value"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with(env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
assert_eq!(
|
||||
report["fields"]["env.XDG_CURRENT_DESKTOP"]["value"],
|
||||
"TestDesktop Injected: secret"
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("Using 'UnsafeLegacyServerConnect'"));
|
||||
}
|
||||
@@ -9,25 +9,25 @@
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/api": "^2.12.1",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.12.0",
|
||||
"@types/node": "^26.6.3",
|
||||
"@tauri-apps/cli": "^2.12.1",
|
||||
"@types/node": "^26.6.4",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.71.0",
|
||||
"@typescript-eslint/parser": "^8.71.0",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.71.1",
|
||||
"@typescript-eslint/parser": "^8.71.1",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"prettier": "3.9.9",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.3.1"
|
||||
"vite": "^8.3.3"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
Generated
+241
-241
@@ -9,8 +9,8 @@ importers:
|
||||
.:
|
||||
dependencies:
|
||||
'@tauri-apps/api':
|
||||
specifier: ^2.12.0
|
||||
version: 2.12.0
|
||||
specifier: ^2.12.1
|
||||
version: 2.12.1
|
||||
react:
|
||||
specifier: ^19.3.0
|
||||
version: 19.3.0
|
||||
@@ -19,11 +19,11 @@ importers:
|
||||
version: 19.3.0([email protected])
|
||||
devDependencies:
|
||||
'@tauri-apps/cli':
|
||||
specifier: ^2.12.0
|
||||
version: 2.12.0
|
||||
specifier: ^2.12.1
|
||||
version: 2.12.1
|
||||
'@types/node':
|
||||
specifier: ^26.6.3
|
||||
version: 26.6.3
|
||||
specifier: ^26.6.4
|
||||
version: 26.6.4
|
||||
'@types/react':
|
||||
specifier: ^19.3.0
|
||||
version: 19.3.0
|
||||
@@ -31,14 +31,14 @@ importers:
|
||||
specifier: ^19.3.0
|
||||
version: 19.3.0(@types/[email protected])
|
||||
'@typescript-eslint/eslint-plugin':
|
||||
specifier: ^8.71.0
|
||||
version: 8.71.0(@typescript-eslint/[email protected].0([email protected])([email protected]))([email protected])([email protected])
|
||||
specifier: ^8.71.1
|
||||
version: 8.71.1(@typescript-eslint/[email protected].1([email protected])([email protected]))([email protected])([email protected])
|
||||
'@typescript-eslint/parser':
|
||||
specifier: ^8.71.0
|
||||
version: 8.71.0([email protected])([email protected])
|
||||
specifier: ^8.71.1
|
||||
version: 8.71.1([email protected])([email protected])
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^6.1.1
|
||||
version: 6.1.1([email protected].1(@types/[email protected].3)([email protected]))
|
||||
specifier: ^6.1.2
|
||||
version: 6.1.2([email protected].3(@types/[email protected].4)([email protected]))
|
||||
eslint:
|
||||
specifier: ^9.39.5
|
||||
version: 9.39.5
|
||||
@@ -58,8 +58,8 @@ importers:
|
||||
specifier: ^6.0.3
|
||||
version: 6.0.3
|
||||
vite:
|
||||
specifier: ^8.3.1
|
||||
version: 8.3.1(@types/[email protected].3)([email protected])
|
||||
specifier: ^8.3.3
|
||||
version: 8.3.3(@types/[email protected].4)([email protected])
|
||||
|
||||
packages:
|
||||
|
||||
@@ -360,95 +360,95 @@ packages:
|
||||
'@jridgewell/[email protected]':
|
||||
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||
|
||||
'@oxc-project/[email protected]1.0':
|
||||
resolution: {integrity: sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==}
|
||||
'@oxc-project/[email protected]2.0':
|
||||
resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==}
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [openharmony]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
resolution: {integrity: sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==}
|
||||
'@rolldown/[email protected]2':
|
||||
resolution: {integrity: sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
@@ -456,77 +456,77 @@ packages:
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-fUSxFX8VABYe9W9K5ROdEaKVkNUFRcMSRofjruvaxztXA+I0XnQHcYHF8m/a6iExRUxsUf0HsFWhPBuH9IgzJw==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==}
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-v5J+jISihLGtih1+3yWagbsL+5dbLZORu4vaSI0vhY0Heb+MAW+T/1s1RyKxrQrwEPGBG5kqwfDDTnSbmVkuqA==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-g27I07pfW/dMS8vcNqB9lamgKF0TqLlcy8e7t9qDGsB1iaeyjJWb2TgBF4tM9ZwLqPAZUXbsz28oXljO12WC4g==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-gXyQ710fNc99YuxFxNyeX9PLSrIpbtgBBj7GQo9tSeRT6fIK40q3/gm7X5jqZo7mWLR2m0R/2ALd3vAWo0Z32Q==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-H9cyXuq9WgxoHh2NZ+R+oN+W78x5UwaBDEp0/fmqUUkaBoioCuOZErM9xKiIV6bpNAhmw1RoWZ49u37q/vaiAg==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-5tFuk3JKMBa1M/iN4gN32OYlSfhY3aqb5PO3zCugxaT+sfecyMKpc3EM9VDbhmwWBE9QD4Tfj7wGhlqx2yy2pQ==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-LOrMyV+nb7pKq8P0BZtTBQuyzm1ORjn16R9MlupmxuT5LqxtuYJlw3VMwbaeXCToJ8jbP5u9JnkfmbqDlvETXw==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-aMIkI+X9qvD2+k80QZB3tuOYT41/cEheikC510CwAIZ31KLXORsRASYYzM4mi1/58ICmtzSLFhCC08keir7COw==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-9gl3NhUbfuGhSKjeGCypKSdtoezOQRcDUrkhTWtLQEjnajets6peO6NadgI2DF0OzbiiFOzrnnIGMwBS+Ap6Iw==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-1W+v86wsYLuyBDN0iDessD4CD9o+yNyO0m8Dp3+/vfjiZrJ/v7R7/aTRBeikaq2tLGgxeag0gxnFggBNBGw91A==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-SsBjvq4f7YaBGqcWoE3cycoItPf0SrQeqFqWWgfxoeZWAIz01E31LDSeZ2p/etJiIY0R9oi045chkFfb0O7WGw==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-9zzDKYUH4TKKBgRdDdVQX8fiRO5gJ8hD1nGsHU9DOHG5Jpm3arjbu9Xg1frR20EusG3Sl8X0dppoO/4EoUXUGg==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
resolution: {integrity: sha512-GIShnAR4C16kSTA8NO02fo8fOw/I5z5sAUEB5S2HlPHFnBkbihL4c9a/MpkxOm1+q5S+tFd3X4QUjHWxfyGzpQ==}
|
||||
'@tauri-apps/[email protected].1':
|
||||
resolution: {integrity: sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg==}
|
||||
engines: {node: '>= 10'}
|
||||
hasBin: true
|
||||
|
||||
@@ -536,8 +536,8 @@ packages:
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
|
||||
|
||||
'@types/[email protected].3':
|
||||
resolution: {integrity: sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg==}
|
||||
'@types/[email protected].4':
|
||||
resolution: {integrity: sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
|
||||
@@ -547,72 +547,72 @@ packages:
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-pqcS9c1HxZTHt7End4nXqd0s5lJrrFzrgCkKFJrsbUnaL6M3+6oBFZaslg6Gjsl3argl2DDRFROnXARaZ2e4Nw==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-nNlBf6HuotqMgZvSkWD5hNdemiBIxQ2NmrlgfcUIeZRs+BbakjscCQRq/Hb74EFVnFiSWWdL12JruqwBy3ERDw==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
'@typescript-eslint/parser': ^8.71.0
|
||||
'@typescript-eslint/parser': ^8.71.1
|
||||
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-CG4nPk1f2zc8yw4pALqHsFYH2hdo+h1T9daSp21+Hnxi9LOE3GT9hAfTKJCBXVNM2GmYs1eMEP615wPoeOgk3A==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-oM/5sAqz/l1v/zYK1qTOPrn2+JIrBGC1V6uNYucRO5gh6eT9vWJ/RhPbGE59byvZEUQ4VP6XkLBaS5Jti5jpvw==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-aABjw5rjBacYONVPaPiWOCjJu0vEF4a25iQuodlmQYL1trtLZ0X/y+2Vzl3BKI1odM4LnwLE1oUDXYp1wzx1TQ==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-Oijc9RUsohHjncg6iGi7gCtjnEjYt9FWv9u6ygK8uKcHK5eLjLAkqERQ9BaytbpceOFdk6kifPCS/zAZE+A99g==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-gWF0BhUcnjZxSpLE8ngS/59n2SB0J3YqRxvX1+2aoRJk9hNtHSLOV+TcarFiOr5ipXm3yc1QrI4c9YZc8zyCxw==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-1YUDZXdTnXLlob03SFHBipdyMBsDVm7zoSz0ytTJ39dk5J1TgsTK03VlR/dLXG/RLLUrPcYbD4rp23BmHxHP0w==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-Z1UlWHADEK2Mlb9NpWfDeSjqoZ5EyrOv4R3eQpbkzqn/EwaIdOpXXupEA1+0ZIOSJSZZDBHG0BrQyN8zUG6Pwg==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-oTvkml5SxXhgg+WWKhod5qWQICDXtOB+/Hi9VdPKFAANJ2b7YOgMffgvzXuqog7R6A/JtrzRf128dsxummyWhg==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-i8uO1qbdxeKgRnS5sCRt6On3/nfo2d2DwQe3Yvjx543zLy7r8ySqRuPPiIIXAhS03U0v5NfAFx+rUgxFzKKwNw==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-kH3t3jZCYv2PZSBEWPKTariLrCaoF1CLoPitYFBJOhAGEwWnSRAtGEifrfrpBa4K9JlwWNZotgA5w3/wLSk/FQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-cJ4OoxPGWvFnBTnSZyaU+qJzGTqPTGJY+gDchj6cRyLRdmIdt4rcsE4twj+zPfrNiWuVi38wijHzShL++Z9atQ==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-ybYnPTUwg3VQQOFEiBPLs8Jxl1ry2vXdn1kVKguomBbvxpetdu3MKTNDqFNUrlG8ylP9MpZosmXMFYlGQHk1oQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-PEEF4G5sLLWAS5BpPrUvms4ySZkiBQQZM4z+3ReI46axK5Vqr/vXBQatJQIZZOYdGyPUAKTtsrWzpqKuU+3DEw==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-pSKSEK1JJpHs6KiKVtABCE4iJK5d7FLFzDXQNBQ2oRY7LEd3UwOt3TZemTgu9syTIf56dJWlTn/pdmrO9oKUXQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-pKR/tEMVrXZG23UFKUn5BQf3zfmfk7KQceI2cGzywZ5nxM5Eu3hEJU1utjWzydtzBbcJAQhHN8iPCxobHpPcZQ==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-CBjT6gfAz3DW2j9Q4moFnqt208Aq+506sVGXfpRcyAeqn0EpayL0mjdWoCO2t3RC7GewNrFxdeehuEaPg6DMzQ==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
peerDependencies:
|
||||
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
|
||||
typescript: '>=4.8.4 <6.1.0'
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
resolution: {integrity: sha512-8eQ9R218XORK+KLosnf4bu/QsUXvUyVwTbArg7/0NMB1Pu87OJKvj4nhFblkYE8gQV73mW1dx1ptlPCkwRGa7A==}
|
||||
'@typescript-eslint/[email protected].1':
|
||||
resolution: {integrity: sha512-0GxiUGqMU0qXJt58cBsiG3DP8lUmBaFo2vChtUX+CT7PnR3v/VGLLrzVP4K9r1lNiZXjHYefMBbPunplr09v6w==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
|
||||
'@vitejs/[email protected].1':
|
||||
resolution: {integrity: sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==}
|
||||
'@vitejs/[email protected].2':
|
||||
resolution: {integrity: sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
peerDependencies:
|
||||
'@rolldown/plugin-babel': ^0.1.7 || ^0.2.0
|
||||
babel-plugin-react-compiler: ^1.0.0
|
||||
oxc-transform-react: ^0.145.0
|
||||
oxc-transform-react: ^0.152.0
|
||||
vite: ^8.0.0
|
||||
peerDependenciesMeta:
|
||||
'@rolldown/plugin-babel':
|
||||
@@ -627,8 +627,8 @@ packages:
|
||||
peerDependencies:
|
||||
acorn: ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
|
||||
[email protected]8.0:
|
||||
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
|
||||
[email protected]9.0:
|
||||
resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==}
|
||||
engines: {node: '>=0.4.0'}
|
||||
hasBin: true
|
||||
|
||||
@@ -685,8 +685,8 @@ packages:
|
||||
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
|
||||
engines: {node: 18 || 20 || >=22}
|
||||
|
||||
[email protected]6:
|
||||
resolution: {integrity: sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==}
|
||||
[email protected]7:
|
||||
resolution: {integrity: sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==}
|
||||
engines: {node: '>=6.0.0'}
|
||||
hasBin: true
|
||||
|
||||
@@ -697,8 +697,8 @@ packages:
|
||||
resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}
|
||||
engines: {node: 20 || >=22}
|
||||
|
||||
[email protected].2:
|
||||
resolution: {integrity: sha512-/u9r8k8ue4ZhHCw9ovDtltpWdXeXzjhdxCGj6vm1RGLPXb8lu33EMdoCHF5Sx8oYBS+Q/FYYNmAqlHncxR3RmA==}
|
||||
[email protected].3:
|
||||
resolution: {integrity: sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==}
|
||||
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
||||
hasBin: true
|
||||
|
||||
@@ -718,8 +718,8 @@ packages:
|
||||
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
[email protected]3:
|
||||
resolution: {integrity: sha512-zfjJo4rM0+fUomGDBW/xcDjhIwz/210DGvip2MAMDZ8KHcRPnOHmEgHPZP0UHlZoxr8fYKVJOqcORhYQcG4FKQ==}
|
||||
[email protected]4:
|
||||
resolution: {integrity: sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
|
||||
@@ -789,8 +789,8 @@ packages:
|
||||
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected]0:
|
||||
resolution: {integrity: sha512-SghDzqdJokdz8zP8YNlvS74+CwLRoUPDGvP/gFA+HrKVw+pOshUAgx8pXR37xl/u16zGae746rFNWvZ/22kU2Q==}
|
||||
[email protected]9:
|
||||
resolution: {integrity: sha512-dKeYk/3SFQz+nXi5whp3OuJzeWABEG4zCtkWJ9+Vby1E1iFM2y0gElRtQvNXRPJTsj8WAF4HMP7hvP790QtJ9g==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==}
|
||||
@@ -1031,8 +1031,8 @@ packages:
|
||||
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
|
||||
engines: {node: '>= 4'}
|
||||
|
||||
[email protected]0:
|
||||
resolution: {integrity: sha512-HpbUakT7xp5miBUywCHf36ZEuAJNklBJDDsGpUIjMzOSmM8ELSfA9Sa/QDPeNeqeoN31u+UTCkL4klCOVvRm4Q==}
|
||||
[email protected]2:
|
||||
resolution: {integrity: sha512-/8UvqAPU9DGTI9k4mxtf49U37Isfwr8Uts96+SBHIkFxPJnHS0Ew4f00sM4Scd8V8EjM0jUNtVDdv1kPdt35lg==}
|
||||
engines: {node: '>= 4'}
|
||||
|
||||
[email protected]:
|
||||
@@ -1292,8 +1292,8 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
[email protected].19:
|
||||
resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==}
|
||||
[email protected].20:
|
||||
resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
|
||||
@@ -1378,8 +1378,8 @@ packages:
|
||||
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected]8:
|
||||
resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}
|
||||
[email protected]9:
|
||||
resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
[email protected]:
|
||||
@@ -1427,8 +1427,8 @@ packages:
|
||||
engines: {node: '>= 0.4'}
|
||||
hasBin: true
|
||||
|
||||
[email protected]1:
|
||||
resolution: {integrity: sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==}
|
||||
[email protected]2:
|
||||
resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
|
||||
@@ -1492,8 +1492,8 @@ packages:
|
||||
resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
[email protected].2:
|
||||
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
[email protected]:
|
||||
@@ -1582,8 +1582,8 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
|
||||
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==}
|
||||
[email protected].3:
|
||||
resolution: {integrity: sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
@@ -1708,7 +1708,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@babel/compat-data': 7.29.7
|
||||
'@babel/helper-validator-option': 7.29.7
|
||||
browserslist: 4.29.2
|
||||
browserslist: 4.29.3
|
||||
lru-cache: 5.1.1
|
||||
semver: 6.3.1
|
||||
|
||||
@@ -1927,109 +1927,109 @@ snapshots:
|
||||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
'@oxc-project/[email protected]1.0': {}
|
||||
'@oxc-project/[email protected]2.0': {}
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]1':
|
||||
'@rolldown/[email protected]2':
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]': {}
|
||||
|
||||
'@tauri-apps/[email protected].0': {}
|
||||
'@tauri-apps/[email protected].1': {}
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/[email protected].0':
|
||||
'@tauri-apps/[email protected].1':
|
||||
optionalDependencies:
|
||||
'@tauri-apps/cli-darwin-arm64': 2.12.0
|
||||
'@tauri-apps/cli-darwin-x64': 2.12.0
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.0
|
||||
'@tauri-apps/cli-linux-arm64-gnu': 2.12.0
|
||||
'@tauri-apps/cli-linux-arm64-musl': 2.12.0
|
||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.0
|
||||
'@tauri-apps/cli-linux-x64-gnu': 2.12.0
|
||||
'@tauri-apps/cli-linux-x64-musl': 2.12.0
|
||||
'@tauri-apps/cli-win32-arm64-msvc': 2.12.0
|
||||
'@tauri-apps/cli-win32-ia32-msvc': 2.12.0
|
||||
'@tauri-apps/cli-win32-x64-msvc': 2.12.0
|
||||
'@tauri-apps/cli-darwin-arm64': 2.12.1
|
||||
'@tauri-apps/cli-darwin-x64': 2.12.1
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.1
|
||||
'@tauri-apps/cli-linux-arm64-gnu': 2.12.1
|
||||
'@tauri-apps/cli-linux-arm64-musl': 2.12.1
|
||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.1
|
||||
'@tauri-apps/cli-linux-x64-gnu': 2.12.1
|
||||
'@tauri-apps/cli-linux-x64-musl': 2.12.1
|
||||
'@tauri-apps/cli-win32-arm64-msvc': 2.12.1
|
||||
'@tauri-apps/cli-win32-ia32-msvc': 2.12.1
|
||||
'@tauri-apps/cli-win32-x64-msvc': 2.12.1
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected].3':
|
||||
'@types/[email protected].4':
|
||||
dependencies:
|
||||
undici-types: 8.9.0
|
||||
|
||||
@@ -2041,57 +2041,57 @@ snapshots:
|
||||
dependencies:
|
||||
csstype: 3.2.3
|
||||
|
||||
'@typescript-eslint/[email protected].0(@typescript-eslint/[email protected].0([email protected])([email protected]))([email protected])([email protected])':
|
||||
'@typescript-eslint/[email protected].1(@typescript-eslint/[email protected].1([email protected])([email protected]))([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@eslint-community/regexpp': 4.12.2
|
||||
'@typescript-eslint/parser': 8.71.0([email protected])([email protected])
|
||||
'@typescript-eslint/scope-manager': 8.71.0
|
||||
'@typescript-eslint/type-utils': 8.71.0([email protected])([email protected])
|
||||
'@typescript-eslint/utils': 8.71.0([email protected])([email protected])
|
||||
'@typescript-eslint/visitor-keys': 8.71.0
|
||||
'@typescript-eslint/parser': 8.71.1([email protected])([email protected])
|
||||
'@typescript-eslint/scope-manager': 8.71.1
|
||||
'@typescript-eslint/type-utils': 8.71.1([email protected])([email protected])
|
||||
'@typescript-eslint/utils': 8.71.1([email protected])([email protected])
|
||||
'@typescript-eslint/visitor-keys': 8.71.1
|
||||
eslint: 9.39.5
|
||||
ignore: 7.0.10
|
||||
ignore: 7.0.12
|
||||
natural-compare: 1.4.0
|
||||
ts-api-utils: 2.5.0([email protected])
|
||||
typescript: 6.0.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/[email protected].0([email protected])([email protected])':
|
||||
'@typescript-eslint/[email protected].1([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 8.71.0
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/typescript-estree': 8.71.0([email protected])
|
||||
'@typescript-eslint/visitor-keys': 8.71.0
|
||||
'@typescript-eslint/scope-manager': 8.71.1
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
'@typescript-eslint/typescript-estree': 8.71.1([email protected])
|
||||
'@typescript-eslint/visitor-keys': 8.71.1
|
||||
debug: 4.4.3
|
||||
eslint: 9.39.5
|
||||
typescript: 6.0.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/[email protected].0([email protected])':
|
||||
'@typescript-eslint/[email protected].1([email protected])':
|
||||
dependencies:
|
||||
'@typescript-eslint/tsconfig-utils': 8.71.0([email protected])
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/tsconfig-utils': 8.71.1([email protected])
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
debug: 4.4.3
|
||||
typescript: 6.0.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
'@typescript-eslint/[email protected].1':
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/visitor-keys': 8.71.0
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
'@typescript-eslint/visitor-keys': 8.71.1
|
||||
|
||||
'@typescript-eslint/[email protected].0([email protected])':
|
||||
'@typescript-eslint/[email protected].1([email protected])':
|
||||
dependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
'@typescript-eslint/[email protected].0([email protected])([email protected])':
|
||||
'@typescript-eslint/[email protected].1([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/typescript-estree': 8.71.0([email protected])
|
||||
'@typescript-eslint/utils': 8.71.0([email protected])([email protected])
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
'@typescript-eslint/typescript-estree': 8.71.1([email protected])
|
||||
'@typescript-eslint/utils': 8.71.1([email protected])([email protected])
|
||||
debug: 4.4.3
|
||||
eslint: 9.39.5
|
||||
ts-api-utils: 2.5.0([email protected])
|
||||
@@ -2099,14 +2099,14 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/[email protected].0': {}
|
||||
'@typescript-eslint/[email protected].1': {}
|
||||
|
||||
'@typescript-eslint/[email protected].0([email protected])':
|
||||
'@typescript-eslint/[email protected].1([email protected])':
|
||||
dependencies:
|
||||
'@typescript-eslint/project-service': 8.71.0([email protected])
|
||||
'@typescript-eslint/tsconfig-utils': 8.71.0([email protected])
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/visitor-keys': 8.71.0
|
||||
'@typescript-eslint/project-service': 8.71.1([email protected])
|
||||
'@typescript-eslint/tsconfig-utils': 8.71.1([email protected])
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
'@typescript-eslint/visitor-keys': 8.71.1
|
||||
debug: 4.4.3
|
||||
minimatch: 10.2.6
|
||||
semver: 7.8.5
|
||||
@@ -2116,32 +2116,32 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/[email protected].0([email protected])([email protected])':
|
||||
'@typescript-eslint/[email protected].1([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@eslint-community/eslint-utils': 4.10.1([email protected])
|
||||
'@typescript-eslint/scope-manager': 8.71.0
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/typescript-estree': 8.71.0([email protected])
|
||||
'@typescript-eslint/scope-manager': 8.71.1
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
'@typescript-eslint/typescript-estree': 8.71.1([email protected])
|
||||
eslint: 9.39.5
|
||||
typescript: 6.0.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@typescript-eslint/[email protected].0':
|
||||
'@typescript-eslint/[email protected].1':
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 8.71.0
|
||||
'@typescript-eslint/types': 8.71.1
|
||||
eslint-visitor-keys: 5.0.1
|
||||
|
||||
'@vitejs/[email protected].1([email protected].1(@types/[email protected].3)([email protected]))':
|
||||
'@vitejs/[email protected].2([email protected].3(@types/[email protected].4)([email protected]))':
|
||||
dependencies:
|
||||
'@rolldown/pluginutils': 1.0.1
|
||||
vite: 8.3.1(@types/[email protected].3)([email protected])
|
||||
vite: 8.3.3(@types/[email protected].4)([email protected])
|
||||
|
||||
[email protected]([email protected]8.0):
|
||||
[email protected]([email protected]9.0):
|
||||
dependencies:
|
||||
acorn: 8.18.0
|
||||
acorn: 8.19.0
|
||||
|
||||
[email protected]8.0: {}
|
||||
[email protected]9.0: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2223,7 +2223,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]6: {}
|
||||
[email protected]7: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2234,13 +2234,13 @@ snapshots:
|
||||
dependencies:
|
||||
balanced-match: 4.0.4
|
||||
|
||||
[email protected].2:
|
||||
[email protected].3:
|
||||
dependencies:
|
||||
baseline-browser-mapping: 2.11.26
|
||||
caniuse-lite: 1.0.30001813
|
||||
electron-to-chromium: 1.5.440
|
||||
baseline-browser-mapping: 2.11.27
|
||||
caniuse-lite: 1.0.30001814
|
||||
electron-to-chromium: 1.5.449
|
||||
node-releases: 2.0.57
|
||||
update-browserslist-db: 1.3.3([email protected].2)
|
||||
update-browserslist-db: 1.3.3([email protected].3)
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2261,7 +2261,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]3: {}
|
||||
[email protected]4: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2334,7 +2334,7 @@ snapshots:
|
||||
es-errors: 1.3.0
|
||||
gopd: 1.2.0
|
||||
|
||||
[email protected]0: {}
|
||||
[email protected]9: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2570,8 +2570,8 @@ snapshots:
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
acorn: 8.18.0
|
||||
acorn-jsx: 5.3.2([email protected]8.0)
|
||||
acorn: 8.19.0
|
||||
acorn-jsx: 5.3.2([email protected]9.0)
|
||||
eslint-visitor-keys: 4.2.1
|
||||
|
||||
[email protected]:
|
||||
@@ -2706,7 +2706,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]0: {}
|
||||
[email protected]2: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -2951,7 +2951,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected].19: {}
|
||||
[email protected].20: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -3040,11 +3040,11 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]8:
|
||||
[email protected]9:
|
||||
dependencies:
|
||||
nanoid: 3.3.19
|
||||
nanoid: 3.3.20
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
source-map-js: 1.2.2
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -3098,26 +3098,26 @@ snapshots:
|
||||
path-parse: 1.0.7
|
||||
supports-preserve-symlinks-flag: 1.0.0
|
||||
|
||||
[email protected]1:
|
||||
[email protected]2:
|
||||
dependencies:
|
||||
'@oxc-project/types': 0.151.0
|
||||
'@oxc-project/types': 0.152.0
|
||||
'@rolldown/pluginutils': 1.0.1
|
||||
optionalDependencies:
|
||||
'@rolldown/binding-android-arm-eabi': 1.2.11
|
||||
'@rolldown/binding-android-arm64': 1.2.11
|
||||
'@rolldown/binding-darwin-arm64': 1.2.11
|
||||
'@rolldown/binding-darwin-x64': 1.2.11
|
||||
'@rolldown/binding-freebsd-x64': 1.2.11
|
||||
'@rolldown/binding-linux-arm-gnueabihf': 1.2.11
|
||||
'@rolldown/binding-linux-arm64-gnu': 1.2.11
|
||||
'@rolldown/binding-linux-arm64-musl': 1.2.11
|
||||
'@rolldown/binding-linux-ppc64-gnu': 1.2.11
|
||||
'@rolldown/binding-linux-s390x-gnu': 1.2.11
|
||||
'@rolldown/binding-linux-x64-gnu': 1.2.11
|
||||
'@rolldown/binding-linux-x64-musl': 1.2.11
|
||||
'@rolldown/binding-openharmony-arm64': 1.2.11
|
||||
'@rolldown/binding-win32-arm64-msvc': 1.2.11
|
||||
'@rolldown/binding-win32-x64-msvc': 1.2.11
|
||||
'@rolldown/binding-android-arm-eabi': 1.2.12
|
||||
'@rolldown/binding-android-arm64': 1.2.12
|
||||
'@rolldown/binding-darwin-arm64': 1.2.12
|
||||
'@rolldown/binding-darwin-x64': 1.2.12
|
||||
'@rolldown/binding-freebsd-x64': 1.2.12
|
||||
'@rolldown/binding-linux-arm-gnueabihf': 1.2.12
|
||||
'@rolldown/binding-linux-arm64-gnu': 1.2.12
|
||||
'@rolldown/binding-linux-arm64-musl': 1.2.12
|
||||
'@rolldown/binding-linux-ppc64-gnu': 1.2.12
|
||||
'@rolldown/binding-linux-s390x-gnu': 1.2.12
|
||||
'@rolldown/binding-linux-x64-gnu': 1.2.12
|
||||
'@rolldown/binding-linux-x64-musl': 1.2.12
|
||||
'@rolldown/binding-openharmony-arm64': 1.2.12
|
||||
'@rolldown/binding-win32-arm64-msvc': 1.2.12
|
||||
'@rolldown/binding-win32-x64-msvc': 1.2.12
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -3200,7 +3200,7 @@ snapshots:
|
||||
side-channel-map: 1.0.1
|
||||
side-channel-weakmap: 1.0.2
|
||||
|
||||
[email protected].1: {}
|
||||
[email protected].2: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -3316,9 +3316,9 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]([email protected].2):
|
||||
[email protected]([email protected].3):
|
||||
dependencies:
|
||||
browserslist: 4.29.2
|
||||
browserslist: 4.29.3
|
||||
escalade: 3.2.0
|
||||
picocolors: 1.1.1
|
||||
|
||||
@@ -3326,15 +3326,15 @@ snapshots:
|
||||
dependencies:
|
||||
punycode: 2.3.1
|
||||
|
||||
[email protected].1(@types/[email protected].3)([email protected]):
|
||||
[email protected].3(@types/[email protected].4)([email protected]):
|
||||
dependencies:
|
||||
lightningcss: 1.33.0
|
||||
picomatch: 4.0.7
|
||||
postcss: 8.5.28
|
||||
rolldown: 1.2.11
|
||||
postcss: 8.5.29
|
||||
rolldown: 1.2.12
|
||||
tinyglobby: 0.2.17
|
||||
optionalDependencies:
|
||||
'@types/node': 26.6.3
|
||||
'@types/node': 26.6.4
|
||||
esbuild: 0.27.2
|
||||
fsevents: 2.3.3
|
||||
|
||||
|
||||
@@ -35,4 +35,5 @@ mac_address = "1"
|
||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
tokio-tungstenite = "0.29"
|
||||
@@ -1,137 +0,0 @@
|
||||
use std::{
|
||||
env, fs,
|
||||
io::{self, Write},
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use clap::Parser;
|
||||
use gpapi::{
|
||||
clap::args::Os,
|
||||
os_profile::{ClientOs, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput, generate_report, refresh_edited_report};
|
||||
use gpservice::hip_runner_state::{MAX_STATE_BYTES, RunnerReport, STATE_NAME, validate_root_owned_path};
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Args {
|
||||
#[arg(long)]
|
||||
client_version: String,
|
||||
#[arg(long, value_enum)]
|
||||
client_os: Os,
|
||||
#[arg(long)]
|
||||
os_version: Option<String>,
|
||||
#[arg(long)]
|
||||
host_id: Option<String>,
|
||||
#[arg(long)]
|
||||
cookie: Option<String>,
|
||||
#[arg(long)]
|
||||
client_ip: Option<String>,
|
||||
#[arg(long)]
|
||||
client_ipv6: Option<String>,
|
||||
#[arg(long)]
|
||||
md5: Option<String>,
|
||||
#[arg(long)]
|
||||
preview: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(err) = run() {
|
||||
eprintln!("HIP report generation failed: {err:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> anyhow::Result<()> {
|
||||
let args = Args::parse();
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let original_args: Vec<_> = env::args_os().skip(1).collect();
|
||||
let executable = env::current_exe().context("Cannot locate HIP runner")?;
|
||||
validate_root_owned_path(&executable, true)?;
|
||||
let state = executable
|
||||
.parent()
|
||||
.context("HIP runner has no parent")?
|
||||
.join(STATE_NAME);
|
||||
let metadata = fs::symlink_metadata(&state).context("Cannot inspect HIP report state")?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink(),
|
||||
"Invalid HIP report state"
|
||||
);
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
ensure!(
|
||||
metadata.uid() == 0 && metadata.permissions().mode() & 0o077 == 0,
|
||||
"HIP report state is not private"
|
||||
);
|
||||
ensure!(
|
||||
metadata.len() <= MAX_STATE_BYTES as u64,
|
||||
"HIP report state is too large"
|
||||
);
|
||||
let bytes = fs::read(&state).context("Cannot read HIP report state")?;
|
||||
ensure!(bytes.len() <= MAX_STATE_BYTES, "HIP report state is too large");
|
||||
let report: RunnerReport = serde_json::from_slice(&bytes).context("Invalid HIP report state")?;
|
||||
|
||||
// This binary is single-threaded. Clear the VPN and desktop environment
|
||||
// before host collectors invoke any external system utilities.
|
||||
for (key, _) in env::vars_os() {
|
||||
unsafe { env::remove_var(key) };
|
||||
}
|
||||
unsafe {
|
||||
env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
|
||||
env::set_var("LC_ALL", "C");
|
||||
env::set_var(
|
||||
"HOME",
|
||||
if cfg!(target_os = "macos") {
|
||||
"/var/root"
|
||||
} else {
|
||||
"/root"
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let report = match report {
|
||||
RunnerReport::ApprovedRootScript { approval_id, owner_uid } => {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
let approved = gpservice::hip_approval::resolve(&approval_id, owner_uid)?;
|
||||
let script_args = original_args.into_iter().filter(|arg| arg != "--preview");
|
||||
let status = std::process::Command::new(approved.path)
|
||||
.args(script_args)
|
||||
.status()
|
||||
.context("Approved HIP script did not start")?;
|
||||
ensure!(status.success(), "Approved HIP script failed");
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
let _ = (approval_id, owner_uid);
|
||||
anyhow::bail!("Root HIP script approvals are unavailable on this platform");
|
||||
}
|
||||
}
|
||||
report => report,
|
||||
};
|
||||
|
||||
let mut builder = OsProfileBuilder::new(ClientOs::from(args.client_os)).client_version(args.client_version);
|
||||
if let Some(host_id) = args.host_id {
|
||||
builder = builder.host_id_override(host_id);
|
||||
}
|
||||
let context = if args.preview {
|
||||
ReportContext::Preview
|
||||
} else {
|
||||
ReportContext::Connected {
|
||||
cookie: args.cookie.context("Missing HIP cookie")?,
|
||||
client_ip: args.client_ip,
|
||||
client_ipv6: args.client_ipv6,
|
||||
md5: args.md5.context("Missing HIP digest")?,
|
||||
}
|
||||
};
|
||||
let input = ReportInput {
|
||||
profile: builder.build(),
|
||||
context,
|
||||
};
|
||||
let xml = match report {
|
||||
RunnerReport::Generated => generate_report(&input)?,
|
||||
RunnerReport::Edited { xml } => refresh_edited_report(&xml, &input)?,
|
||||
RunnerReport::ApprovedRootScript { .. } => unreachable!("approved script returned before report generation"),
|
||||
};
|
||||
io::stdout().write_all(xml.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
+49
-66
@@ -1,11 +1,8 @@
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
use std::{collections::HashMap, io::Write};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use clap::Parser;
|
||||
@@ -15,9 +12,8 @@ use gpapi::logger;
|
||||
#[cfg(debug_assertions)]
|
||||
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
||||
use gpapi::{
|
||||
process::gui_launcher::GuiLauncher,
|
||||
service::vpn_state::VpnState,
|
||||
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
utils::{lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use log::{Log, Metadata, Record};
|
||||
@@ -64,9 +60,9 @@ impl Log for RedactingMacosLogger {
|
||||
#[command(version = VERSION)]
|
||||
struct Cli {
|
||||
#[clap(long)]
|
||||
minimized: bool,
|
||||
#[clap(long)]
|
||||
env_file: Option<String>,
|
||||
#[cfg_attr(debug_assertions, clap(conflicts_with = "dev_standalone"))]
|
||||
#[cfg_attr(target_os = "macos", clap(conflicts_with = "macos_brokered"))]
|
||||
desktop_credentials: bool,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
||||
dev_standalone: bool,
|
||||
@@ -100,7 +96,29 @@ impl Cli {
|
||||
let gui_restart_requested = Arc::new(AtomicBool::new(false));
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let externally_brokered = self.externally_brokered();
|
||||
let desktop_uid = crate::runtime_user::desktop_uid();
|
||||
let desktop_uid = if self.desktop_credentials {
|
||||
anyhow::ensure!(
|
||||
nix::unistd::Uid::effective().is_root(),
|
||||
"Desktop credentials require a privileged service"
|
||||
);
|
||||
let uid: u32 = std::env::var("PKEXEC_UID")
|
||||
.context("Desktop credentials require a pkexec-authenticated user")?
|
||||
.parse()
|
||||
.context("Invalid pkexec user")?;
|
||||
anyhow::ensure!(uid != 0, "Desktop credentials require a non-root user");
|
||||
anyhow::ensure!(
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.is_some(),
|
||||
"Desktop user is unavailable"
|
||||
);
|
||||
Some(uid)
|
||||
} else {
|
||||
crate::runtime_user::desktop_uid()
|
||||
};
|
||||
let desktop_channel = if self.desktop_credentials {
|
||||
Some(crate::desktop_client::DesktopClient::from_stdio()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let brokered_scripts_dir = if externally_brokered {
|
||||
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
||||
let contents_dir = executable
|
||||
@@ -182,26 +200,28 @@ impl Cli {
|
||||
tokio::spawn(async move { signals::handle_signals(lifecycle, ws_ctx).await });
|
||||
}
|
||||
|
||||
let desktop_cancel = server_token.clone();
|
||||
let shutdown_token = server_token.clone();
|
||||
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
|
||||
let (ws_ready_tx, ws_ready_rx) = tokio::sync::oneshot::channel();
|
||||
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
let launch_managed_gui = !self.dev_standalone && !externally_brokered;
|
||||
#[cfg(not(debug_assertions))]
|
||||
let launch_managed_gui = !externally_brokered;
|
||||
|
||||
if launch_managed_gui {
|
||||
let desktop_client_handle = if let Some(channel) = desktop_channel {
|
||||
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
||||
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
||||
let minimized = self.minimized;
|
||||
tokio::spawn(async move {
|
||||
launch_gui(envs, registry, desktop_uid, minimized, gui_restart_requested).await;
|
||||
let desktop_uid = desktop_uid.context("Desktop user is unavailable")?;
|
||||
Some(tokio::spawn(async move {
|
||||
if let Err(err) = channel
|
||||
.serve(registry, desktop_uid, gui_restart_requested, desktop_cancel)
|
||||
.await
|
||||
{
|
||||
warn!("Desktop credential channel ended: {err}");
|
||||
}
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
});
|
||||
}))
|
||||
} else {
|
||||
info!("Running with a separately started debug GUI");
|
||||
}
|
||||
info!("Running with an externally launched GUI");
|
||||
None
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown_signal() => {
|
||||
@@ -213,7 +233,11 @@ impl Cli {
|
||||
}
|
||||
|
||||
vpn_task_cancel_token.cancel();
|
||||
shutdown_token.cancel();
|
||||
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
|
||||
if let Some(handle) = desktop_client_handle {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
lock_file.unlock()?;
|
||||
|
||||
@@ -301,7 +325,7 @@ async fn wait_for_brokered_idle(
|
||||
_ = interval.tick() => {},
|
||||
}
|
||||
|
||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected) && registry.is_empty();
|
||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected | VpnState::Failed(_)) && registry.is_empty();
|
||||
if !idle {
|
||||
idle_since = None;
|
||||
continue;
|
||||
@@ -363,47 +387,6 @@ mod signals {
|
||||
}
|
||||
}
|
||||
|
||||
async fn launch_gui(
|
||||
envs: Option<HashMap<String, String>>,
|
||||
registry: Arc<SessionRegistry>,
|
||||
desktop_uid: Option<u32>,
|
||||
mut minimized: bool,
|
||||
restart_requested: Arc<AtomicBool>,
|
||||
) {
|
||||
loop {
|
||||
let credential = match registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid) {
|
||||
Ok(credential) => credential,
|
||||
Err(err) => {
|
||||
warn!("Failed to issue GUI credential: {err}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let session_id = credential.session_id();
|
||||
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), credential)
|
||||
.envs(envs.clone())
|
||||
.minimized(minimized);
|
||||
|
||||
match gui_launcher.launch().await {
|
||||
Ok(exit_status) => {
|
||||
registry.revoke(session_id);
|
||||
let should_restart = restart_requested.swap(false, Ordering::SeqCst);
|
||||
if !should_restart {
|
||||
info!("GUI exited with code {:?}", exit_status.code());
|
||||
break;
|
||||
}
|
||||
|
||||
info!("GUI restart requested, restarting");
|
||||
minimized = false;
|
||||
}
|
||||
Err(err) => {
|
||||
registry.revoke(session_id);
|
||||
warn!("Failed to launch GUI: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run() {
|
||||
let mut cli = Cli::parse();
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
use std::{
|
||||
io,
|
||||
os::fd::OwnedFd,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
|
||||
sys::stat::{SFlag, fstat},
|
||||
unistd::{dup, read, write},
|
||||
};
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::session_registry::SessionRegistry;
|
||||
use gpapi::service::transport::{DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY};
|
||||
|
||||
/// Private parent/service pipes; credentials never pass through argv, environment or files.
|
||||
pub(crate) struct DesktopClient {
|
||||
input: AsyncFd<OwnedFd>,
|
||||
output: AsyncFd<OwnedFd>,
|
||||
}
|
||||
|
||||
impl DesktopClient {
|
||||
pub(crate) fn from_stdio() -> anyhow::Result<Self> {
|
||||
let channel = Self::new(dup(std::io::stdin())?, dup(std::io::stdout())?)?;
|
||||
// Only the owned CLOEXEC descriptors carry credentials. VPN subprocesses inherit /dev/null.
|
||||
let null = std::fs::OpenOptions::new().read(true).write(true).open("/dev/null")?;
|
||||
nix::unistd::dup2_stdin(&null)?;
|
||||
nix::unistd::dup2_stdout(&null)?;
|
||||
Ok(channel)
|
||||
}
|
||||
|
||||
fn new(input: OwnedFd, output: OwnedFd) -> anyhow::Result<Self> {
|
||||
fn pipe(fd: OwnedFd) -> anyhow::Result<AsyncFd<OwnedFd>> {
|
||||
ensure!(
|
||||
SFlag::from_bits_truncate(fstat(&fd)?.st_mode).contains(SFlag::S_IFIFO),
|
||||
"Desktop credentials require private pipes"
|
||||
);
|
||||
fcntl(&fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
|
||||
let flags = OFlag::from_bits_truncate(fcntl(&fd, FcntlArg::F_GETFL)?);
|
||||
fcntl(&fd, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))?;
|
||||
Ok(AsyncFd::new(fd)?)
|
||||
}
|
||||
Ok(Self {
|
||||
input: pipe(input)?,
|
||||
output: pipe(output)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn serve(
|
||||
self,
|
||||
registry: Arc<SessionRegistry>,
|
||||
uid: u32,
|
||||
restart: Arc<AtomicBool>,
|
||||
cancel: CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut rendering_renewed = false;
|
||||
loop {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), Some(uid))?;
|
||||
let session_id = credential.session_id();
|
||||
let result = tokio::select! {
|
||||
_ = cancel.cancelled() => Ok(None),
|
||||
result = async {
|
||||
self.write_frame(&credential.encode_frame()?).await?;
|
||||
self.gui_exited().await
|
||||
} => result,
|
||||
};
|
||||
registry.revoke(session_id);
|
||||
let requested = restart.swap(false, Ordering::SeqCst);
|
||||
match result? {
|
||||
None => return Ok(()),
|
||||
Some(DESKTOP_GUI_EXITED) if requested => {}
|
||||
Some(DESKTOP_GUI_EXITED) => return Ok(()),
|
||||
Some(DESKTOP_RENDERING_RETRY) => {
|
||||
ensure!(!rendering_renewed, "Rendering recovery already requested");
|
||||
rendering_renewed = true;
|
||||
}
|
||||
Some(_) => anyhow::bail!("Invalid desktop control message"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_frame(&self, mut bytes: &[u8]) -> anyhow::Result<()> {
|
||||
while !bytes.is_empty() {
|
||||
let mut ready = self.output.writable().await?;
|
||||
match ready.try_io(|fd| write(fd.get_ref(), bytes).map_err(io::Error::from)) {
|
||||
Ok(result) => {
|
||||
let length = result?;
|
||||
ensure!(length != 0, "Desktop credential pipe closed");
|
||||
bytes = &bytes[length..];
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn gui_exited(&self) -> anyhow::Result<Option<u8>> {
|
||||
loop {
|
||||
let mut ready = self.input.readable().await?;
|
||||
let mut byte = [0];
|
||||
match ready.try_io(|fd| read(fd.get_ref(), &mut byte).map_err(io::Error::from)) {
|
||||
Ok(result) => {
|
||||
if result.context("Desktop control pipe failed")? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
return Ok(Some(byte[0]));
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_stdio_is_not_inherited_by_subprocesses() {
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--ignored", "--exact", "desktop_client::tests::stdio_child"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(text.contains("PRIVATE_FRAME"));
|
||||
assert!(!text.contains("CHILD_OUTPUT"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "subprocess fixture for credential_stdio_is_not_inherited_by_subprocesses"]
|
||||
async fn stdio_child() {
|
||||
let channel = DesktopClient::from_stdio().unwrap();
|
||||
assert!(
|
||||
std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "printf CHILD_OUTPUT"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
channel.write_frame(b"PRIVATE_FRAME").await.unwrap();
|
||||
}
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use nix::unistd::pipe;
|
||||
use std::{fs::File, io::Read, time::Duration};
|
||||
|
||||
fn pipes() -> (DesktopClient, OwnedFd, File) {
|
||||
let (input, control) = pipe().unwrap();
|
||||
let (credentials, output) = pipe().unwrap();
|
||||
(DesktopClient::new(input, output).unwrap(), control, credentials.into())
|
||||
}
|
||||
|
||||
async fn credential(mut reader: File) -> (File, SessionCredential) {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut header = [0; 2];
|
||||
reader.read_exact(&mut header).unwrap();
|
||||
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header)) + 2]);
|
||||
frame[..2].copy_from_slice(&header);
|
||||
reader.read_exact(&mut frame[2..]).unwrap();
|
||||
let credential = SessionCredential::decode_frame(&frame).unwrap();
|
||||
(reader, credential)
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_revokes_and_reissues_on_restart_then_closes_on_parent_exit() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let restart = Arc::new(AtomicBool::new(false));
|
||||
let task = tokio::spawn(channel.serve(registry.clone(), 1000, restart.clone(), CancellationToken::new()));
|
||||
let (reader, first) = credential(reader).await;
|
||||
restart.store(true, Ordering::SeqCst);
|
||||
write(&control, &[0]).unwrap();
|
||||
let (_, second) = credential(reader).await;
|
||||
assert_ne!(first.session_id(), second.session_id());
|
||||
assert!(registry.last_successful_hip_report(first.session_id()).is_err());
|
||||
drop(control);
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rendering_renewal_revokes_credentials_and_consumes_old_restart_intent() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let restart = Arc::new(AtomicBool::new(true));
|
||||
let task = tokio::spawn(channel.serve(registry.clone(), 1000, restart.clone(), CancellationToken::new()));
|
||||
let (reader, first) = credential(reader).await;
|
||||
write(&control, &[DESKTOP_RENDERING_RETRY]).unwrap();
|
||||
let (_, second) = credential(reader).await;
|
||||
assert_ne!(first.session_id(), second.session_id());
|
||||
assert!(registry.last_successful_hip_report(first.session_id()).is_err());
|
||||
assert!(!restart.load(Ordering::SeqCst));
|
||||
write(&control, &[DESKTOP_GUI_EXITED]).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_rendering_renewal_fails_closed() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let task = tokio::spawn(channel.serve(
|
||||
registry.clone(),
|
||||
1000,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
CancellationToken::new(),
|
||||
));
|
||||
let (reader, _) = credential(reader).await;
|
||||
write(&control, &[DESKTOP_RENDERING_RETRY]).unwrap();
|
||||
let (_, second) = credential(reader).await;
|
||||
write(&control, &[DESKTOP_RENDERING_RETRY]).unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_shutdown_cancels_pipe_wait_and_revokes_credential() {
|
||||
let (channel, _control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let cancel = CancellationToken::new();
|
||||
let task = tokio::spawn(channel.serve(registry.clone(), 1000, Arc::new(AtomicBool::new(false)), cancel.clone()));
|
||||
let (_, issued) = credential(reader).await;
|
||||
cancel.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_rejects_invalid_control_messages_and_revokes() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let task = tokio::spawn(channel.serve(
|
||||
registry.clone(),
|
||||
1000,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
CancellationToken::new(),
|
||||
));
|
||||
let (_, issued) = credential(reader).await;
|
||||
write(&control, &[255]).unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -186,7 +186,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn anchor_eof_revokes_issued_credential() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let (service, mut client) = UnixStream::pair().unwrap();
|
||||
let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry), Some(1234)));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::Write,
|
||||
io::{Read, Write},
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
@@ -12,8 +12,6 @@ use serde::{Deserialize, Serialize};
|
||||
use tempfile::Builder;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::hip_runner_state::validate_root_owned_path;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const APPROVAL_DIRECTORY: &str = "/var/lib/gpclient/hip-approvals";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
@@ -83,22 +81,32 @@ pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result<Ap
|
||||
let contents = request.contents()?;
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
fs::create_dir_all(base).context("Cannot create HIP approval directory")?;
|
||||
validate_root_owned_path(base, false)?;
|
||||
validate_approval_ancestors(base)?;
|
||||
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
|
||||
install_at(base, &contents, request.original_path, approving_uid, 0)
|
||||
}
|
||||
|
||||
pub fn resolve(approval_id: &str, desktop_uid: u32) -> anyhow::Result<ApprovedScript> {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
|
||||
resolve_with_control(approval_id, desktop_uid, &budget)
|
||||
}
|
||||
|
||||
pub fn resolve_with_control(
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> anyhow::Result<ApprovedScript> {
|
||||
control.check()?;
|
||||
ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner");
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
validate_root_owned_path(base, false)?;
|
||||
resolve_at(base, approval_id, desktop_uid, 0)
|
||||
validate_approval_ancestors(base)?;
|
||||
resolve_at_with_control(base, approval_id, desktop_uid, 0, control)
|
||||
}
|
||||
|
||||
pub fn revoke(approval_id: &str, approving_uid: u32) -> anyhow::Result<()> {
|
||||
ensure!(approving_uid != 0, "Root cannot revoke another user's HIP approval");
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
validate_root_owned_path(base, false)?;
|
||||
validate_approval_ancestors(base)?;
|
||||
revoke_at(base, approval_id, approving_uid, 0)
|
||||
}
|
||||
|
||||
@@ -127,7 +135,7 @@ fn status_at(
|
||||
}
|
||||
}
|
||||
if validate_private_dir(base, file_owner).is_err()
|
||||
|| (validate_root_ancestors && validate_root_owned_path(base, false).is_err())
|
||||
|| (validate_root_ancestors && validate_approval_ancestors(base).is_err())
|
||||
{
|
||||
return Ok(HipApprovalStatus::Corrupt);
|
||||
}
|
||||
@@ -191,15 +199,43 @@ fn install_at(
|
||||
}
|
||||
|
||||
fn resolve_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result<ApprovedScript> {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
|
||||
resolve_at_with_control(base, approval_id, desktop_uid, file_owner, &budget)
|
||||
}
|
||||
|
||||
fn resolve_at_with_control(
|
||||
base: &Path,
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
file_owner: u32,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> anyhow::Result<ApprovedScript> {
|
||||
control.check()?;
|
||||
let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?;
|
||||
control.check()?;
|
||||
let script = base.join(approval_id).join(SCRIPT_NAME);
|
||||
validate_file(&script, file_owner, 0o500, MAX_SCRIPT_SIZE as u64)?;
|
||||
let contents = fs::read(&script)?;
|
||||
let mut file = File::open(&script)?;
|
||||
let mut contents = Vec::new();
|
||||
let mut chunk = [0_u8; 8192];
|
||||
loop {
|
||||
control.check()?;
|
||||
let read = file.read(&mut chunk)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
contents.len() + read <= MAX_SCRIPT_SIZE,
|
||||
"Approved HIP script is too large"
|
||||
);
|
||||
contents.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
ensure!(!contents.is_empty(), "Approved HIP script is empty");
|
||||
ensure!(
|
||||
sha256::digest(&contents) == info.sha256,
|
||||
"Approved HIP script digest mismatch"
|
||||
);
|
||||
control.check()?;
|
||||
Ok(ApprovedScript { info, path: script })
|
||||
}
|
||||
|
||||
@@ -294,6 +330,27 @@ fn validate_file(path: &Path, owner_uid: u32, mode: u32, max_size: u64) -> anyho
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check every component because a trusted file below a writable parent can
|
||||
/// be replaced before a later HIP refresh.
|
||||
fn validate_approval_ancestors(path: &Path) -> anyhow::Result<()> {
|
||||
ensure!(path.is_absolute(), "HIP approval path must be absolute");
|
||||
for component in path.ancestors().take_while(|part| part.as_os_str() != "/") {
|
||||
let metadata =
|
||||
fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?;
|
||||
ensure!(
|
||||
!metadata.file_type().is_symlink(),
|
||||
"HIP approval path contains a symlink"
|
||||
);
|
||||
ensure!(metadata.uid() == 0, "HIP approval path is not root-owned");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o022 == 0,
|
||||
"HIP approval path is writable by another user"
|
||||
);
|
||||
ensure!(metadata.is_dir(), "HIP approval parent is not a directory");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+281
-247
@@ -1,275 +1,309 @@
|
||||
use std::{os::unix::process::CommandExt, process::Stdio, sync::Arc, time::Duration};
|
||||
use std::{collections::HashMap, io, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::{hip::HipSource, service::request::PreviewHipReportRequest};
|
||||
use tokio::{io::AsyncReadExt, process::Command};
|
||||
use gpapi::{
|
||||
hip::HipSource,
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
request::PreviewHipReportRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
};
|
||||
use openconnect::HipRequest;
|
||||
use tokio::{
|
||||
sync::{Mutex, Semaphore},
|
||||
task::JoinHandle,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{session_registry::SessionRegistry, ws_connection::ConnectionControl};
|
||||
|
||||
const MAX_PREVIEW_BYTES: u64 = 1024 * 1024;
|
||||
const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const PREVIEW_COOKIE: &str = "user=preview&domain=preview&computer=preview";
|
||||
const PREVIEW_IP: &str = "192.0.2.1";
|
||||
const PREVIEW_MD5: &str = "00000000000000000000000000000000";
|
||||
const MAX_ACTIVE_PREVIEWS: usize = 4;
|
||||
|
||||
pub(crate) async fn generate(
|
||||
struct PreviewTask {
|
||||
connection_id: Uuid,
|
||||
cancellation: CancellationToken,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
pub(crate) struct PreviewJob {
|
||||
pub session_id: Uuid,
|
||||
pub request_id: Uuid,
|
||||
pub request: PreviewHipReportRequest,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub identity: HostIdentity,
|
||||
pub registry: Arc<SessionRegistry>,
|
||||
pub connection: ConnectionControl,
|
||||
}
|
||||
|
||||
pub(crate) struct HipPreviews {
|
||||
tasks: Mutex<HashMap<Uuid, PreviewTask>>,
|
||||
slots: Arc<Semaphore>,
|
||||
shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
impl HipPreviews {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
slots: Arc::new(Semaphore::new(MAX_ACTIVE_PREVIEWS)),
|
||||
shutdown: CancellationToken::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self, job: PreviewJob) -> bool {
|
||||
let PreviewJob {
|
||||
session_id,
|
||||
request_id,
|
||||
request,
|
||||
edited_report,
|
||||
desktop_uid,
|
||||
identity,
|
||||
registry,
|
||||
connection,
|
||||
} = job;
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
if self.shutdown.is_cancelled() || tasks.get(&session_id).is_some_and(|task| !task.worker.is_finished()) {
|
||||
return false;
|
||||
}
|
||||
if let Some(completed) = tasks.remove(&session_id) {
|
||||
let _ = completed.worker.await;
|
||||
}
|
||||
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
|
||||
return false;
|
||||
};
|
||||
let cancellation = self.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let connection_id = connection.connection_id();
|
||||
let worker = tokio::spawn(async move {
|
||||
let _slot = slot;
|
||||
let generated = tokio::task::spawn_blocking(move || {
|
||||
generate(request, edited_report, desktop_uid, identity, worker_cancellation)
|
||||
})
|
||||
.await;
|
||||
let result = match generated {
|
||||
Ok(Ok(xml)) => preview_result(®istry, session_id, xml),
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("HIP preview failed: {error:#}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("HIP preview worker failed: {error}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
};
|
||||
// A bounded connection queue must not prevent preview teardown.
|
||||
let _ = connection.send(crate::ws_connection::ConnectionCommand::Reply { id: request_id, result });
|
||||
});
|
||||
tasks.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) async fn cancel_connection(&self, session_id: Uuid, connection_id: Uuid) {
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
if !tasks
|
||||
.get(&session_id)
|
||||
.is_some_and(|task| task.connection_id == connection_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(task) = tasks.remove(&session_id) {
|
||||
task.cancellation.cancel();
|
||||
let _ = task.worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.shutdown.cancel();
|
||||
let tasks = std::mem::take(&mut *self.tasks.lock().await);
|
||||
for task in tasks.into_values() {
|
||||
let _ = task.worker.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
|
||||
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
});
|
||||
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
||||
}
|
||||
|
||||
fn generate(
|
||||
request: PreviewHipReportRequest,
|
||||
edited_report: Option<Arc<str>>,
|
||||
desktop_uid: Option<u32>,
|
||||
identity: HostIdentity,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<String> {
|
||||
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
|
||||
ensure!(
|
||||
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
|
||||
"Invalid HIP host ID"
|
||||
);
|
||||
|
||||
let source = &request.source;
|
||||
let execution = match source {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(PREVIEW_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "HIP preview cancelled"));
|
||||
}
|
||||
gpapi::process::collection::CollectionControl::check(&budget)
|
||||
};
|
||||
check()?;
|
||||
let profile = crate::hip_source::profile(
|
||||
&identity,
|
||||
request.client_os,
|
||||
Some(request.client_version.clone()),
|
||||
None,
|
||||
request.host_id.clone(),
|
||||
None,
|
||||
&check,
|
||||
)?;
|
||||
let input = HipRequest {
|
||||
cookie: "user=preview&domain=preview&computer=preview".into(),
|
||||
client_ip: Some("192.0.2.1".into()),
|
||||
client_ipv6: None,
|
||||
md5: "00000000000000000000000000000000".into(),
|
||||
client_version: request.client_version,
|
||||
client_os: request.client_os.as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: request.host_id,
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
};
|
||||
let xml = match &request.source {
|
||||
HipSource::Disabled => bail!("HIP is disabled"),
|
||||
HipSource::Generated | HipSource::Edited { .. } => crate::hip_source::preview_runner(edited_report)?,
|
||||
HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. } => {
|
||||
crate::hip_source::resolve(source, desktop_uid, false, None)?
|
||||
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
||||
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
||||
}
|
||||
source => {
|
||||
let execution = crate::hip_source::resolve(source, desktop_uid, false, None, Some(profile))?;
|
||||
let openconnect::HipSource::Script(script) = execution.source else {
|
||||
bail!("HIP preview executable is unavailable");
|
||||
};
|
||||
let xml = script.collect(&input, &check)?;
|
||||
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
||||
xml
|
||||
}
|
||||
};
|
||||
let script = execution
|
||||
.wrapper
|
||||
.as_deref()
|
||||
.context("HIP preview script is unavailable")?;
|
||||
let is_runner = !matches!(source, HipSource::UserScript { .. });
|
||||
let mut command = Command::new(script);
|
||||
command
|
||||
.arg("--client-version")
|
||||
.arg(&request.client_version)
|
||||
.arg("--client-os")
|
||||
.arg(request.client_os.as_str())
|
||||
.arg("--os-version")
|
||||
.arg(request.client_os.default_os_version());
|
||||
if let Some(host_id) = request.host_id {
|
||||
command.arg("--host-id").arg(host_id);
|
||||
}
|
||||
if is_runner {
|
||||
command.arg("--preview");
|
||||
}
|
||||
command
|
||||
.arg("--cookie")
|
||||
.arg(PREVIEW_COOKIE)
|
||||
.arg("--client-ip")
|
||||
.arg(PREVIEW_IP)
|
||||
.arg("--md5")
|
||||
.arg(PREVIEW_MD5)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
command.as_std_mut().process_group(0);
|
||||
configure_identity(&mut command, execution.uid, &request.client_version)?;
|
||||
command.kill_on_drop(true);
|
||||
|
||||
let mut child = command.spawn().context("Failed to launch HIP preview")?;
|
||||
let mut process_group = ProcessGroupGuard::new(child.id());
|
||||
let mut stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.context("HIP preview has no output stream")?
|
||||
.take(MAX_PREVIEW_BYTES + 1);
|
||||
let output = tokio::time::timeout(PREVIEW_TIMEOUT, async {
|
||||
let mut bytes = Vec::new();
|
||||
stdout.read_to_end(&mut bytes).await?;
|
||||
ensure!(bytes.len() as u64 <= MAX_PREVIEW_BYTES, "HIP preview exceeds 1 MiB");
|
||||
let status = child.wait().await?;
|
||||
process_group.disarm();
|
||||
ensure!(status.success(), "HIP preview generator failed");
|
||||
Ok::<_, anyhow::Error>(String::from_utf8(bytes)?)
|
||||
})
|
||||
.await;
|
||||
match output {
|
||||
Ok(Ok(xml)) => {
|
||||
if matches!(
|
||||
source,
|
||||
HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. }
|
||||
) {
|
||||
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
||||
}
|
||||
Ok(xml)
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
terminate_group(&mut child, &mut process_group).await;
|
||||
Err(error)
|
||||
}
|
||||
Err(_) => {
|
||||
terminate_group(&mut child, &mut process_group).await;
|
||||
anyhow::bail!("HIP preview timed out")
|
||||
}
|
||||
}
|
||||
check()?;
|
||||
Ok(xml)
|
||||
}
|
||||
|
||||
fn configure_identity(command: &mut Command, uid: u32, app_version: &str) -> anyhow::Result<()> {
|
||||
command
|
||||
.as_std_mut()
|
||||
.env_clear()
|
||||
.env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
|
||||
.env("LC_ALL", "C")
|
||||
.env("APP_VERSION", app_version);
|
||||
if uid == 0 {
|
||||
command.as_std_mut().env("HOME", "/root");
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
use nix::unistd::{Uid, User};
|
||||
let user = User::from_uid(Uid::from_raw(uid))?.context("Desktop user is unavailable")?;
|
||||
command
|
||||
.as_std_mut()
|
||||
.env("HOME", &user.dir)
|
||||
.env("USER", &user.name)
|
||||
.env("LOGNAME", &user.name)
|
||||
.current_dir(&user.dir);
|
||||
if Uid::effective().as_raw() == uid {
|
||||
return Ok(());
|
||||
}
|
||||
// Match OpenConnect's CSD child: a single primary group, then the desktop UID.
|
||||
unsafe {
|
||||
command.as_std_mut().pre_exec(move || {
|
||||
nix::unistd::setgid(user.gid).map_err(std::io::Error::from)?;
|
||||
nix::unistd::setgroups(&[user.gid]).map_err(std::io::Error::from)?;
|
||||
nix::unistd::setuid(Uid::from_raw(uid)).map_err(std::io::Error::from)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
bail!("Custom HIP previews are unavailable on this platform")
|
||||
}
|
||||
}
|
||||
|
||||
struct ProcessGroupGuard(Option<u32>);
|
||||
|
||||
impl ProcessGroupGuard {
|
||||
fn new(pid: Option<u32>) -> Self {
|
||||
Self(pid)
|
||||
}
|
||||
|
||||
fn kill(&mut self) {
|
||||
if let Some(pid) = self.0.take() {
|
||||
unsafe { nix::libc::kill(-(pid as i32), nix::libc::SIGKILL) };
|
||||
}
|
||||
}
|
||||
|
||||
fn disarm(&mut self) {
|
||||
self.0 = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ProcessGroupGuard {
|
||||
fn drop(&mut self) {
|
||||
self.kill();
|
||||
}
|
||||
}
|
||||
|
||||
async fn terminate_group(child: &mut tokio::process::Child, process_group: &mut ProcessGroupGuard) {
|
||||
process_group.kill();
|
||||
let _ = child.start_kill();
|
||||
let _ = child.wait().await;
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::ClientOs;
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
fn request(path: &std::path::Path) -> PreviewHipReportRequest {
|
||||
PreviewHipReportRequest {
|
||||
source: HipSource::UserScript {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
fn job(session_id: Uuid) -> PreviewJob {
|
||||
let (tx, _) = tokio::sync::mpsc::channel(1);
|
||||
let (connection, _) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
PreviewJob {
|
||||
session_id,
|
||||
request_id: Uuid::new_v4(),
|
||||
request: PreviewHipReportRequest {
|
||||
source: HipSource::Generated,
|
||||
client_os: ClientOs::Linux,
|
||||
client_version: "6.3.3".into(),
|
||||
host_id: None,
|
||||
},
|
||||
client_os: ClientOs::Linux,
|
||||
client_version: "6.3.3".into(),
|
||||
host_id: Some("host-test".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn script(path: &std::path::Path, body: &str) {
|
||||
fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_script_preview_receives_placeholders_and_validates_output() {
|
||||
let uid = nix::unistd::Uid::effective().as_raw();
|
||||
if uid == 0 {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("hip.sh");
|
||||
script(
|
||||
&path,
|
||||
r#"
|
||||
test "$1" = --client-version && test "$2" = 6.3.3 || exit 2
|
||||
test "$3" = --client-os && test "$4" = Linux || exit 2
|
||||
test "$5" = --os-version || exit 2
|
||||
test "$7" = --host-id && test "$8" = host-test || exit 2
|
||||
test "$9" = --cookie && test "${10}" = 'user=preview&domain=preview&computer=preview' || exit 2
|
||||
test "${11}" = --client-ip && test "${12}" = 192.0.2.1 || exit 2
|
||||
test "${13}" = --md5 && test "${14}" = 00000000000000000000000000000000 || exit 2
|
||||
test "$#" = 14 || exit 2
|
||||
test "$APP_VERSION" = 6.3.3 || exit 2
|
||||
printf '%s' '<hip-report><md5-sum/><user-name/><domain/><host-name/><host-id/><ip-address/><ipv6-address/><generate-time/><hip-report-version/><categories><entry name="host-info"><client-version/><os/><os-vendor/><domain/><host-name/><host-id/></entry></categories></hip-report>'
|
||||
"#,
|
||||
);
|
||||
let xml = generate(request(&path), None, Some(uid)).await.unwrap();
|
||||
assert!(xml.starts_with("<hip-report>"));
|
||||
|
||||
script(&path, "printf '%s' '<not-hip/>'");
|
||||
assert!(generate(request(&path), None, Some(uid)).await.is_err());
|
||||
|
||||
script(&path, "head -c 1048577 /dev/zero");
|
||||
let err = generate(request(&path), None, Some(uid)).await.unwrap_err();
|
||||
assert!(err.to_string().contains("exceeds 1 MiB"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[tokio::test]
|
||||
async fn cancelling_preview_stops_its_process_group() {
|
||||
let uid = nix::unistd::Uid::effective().as_raw();
|
||||
if uid == 0 {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("hip.sh");
|
||||
let pid_file = dir.path().join("pids");
|
||||
script(
|
||||
&path,
|
||||
&format!(
|
||||
"sleep 30 & child=$!; echo \"$$ $child\" > \"{}\"; wait",
|
||||
pid_file.display()
|
||||
edited_report: None,
|
||||
desktop_uid: None,
|
||||
identity: HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
registry: Arc::new(SessionRegistry::for_tests(Uuid::new_v4())),
|
||||
connection,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preview_admission_rejects_duplicate_session_and_global_capacity() {
|
||||
let previews = HipPreviews::new();
|
||||
let session_id = Uuid::new_v4();
|
||||
let cancellation = previews.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let worker = tokio::spawn(async move { worker_cancellation.cancelled().await });
|
||||
let connection_id = Uuid::new_v4();
|
||||
previews.tasks.lock().await.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
assert!(!previews.start(job(session_id)).await);
|
||||
previews.cancel_connection(session_id, connection_id).await;
|
||||
let _all_slots = Arc::clone(&previews.slots)
|
||||
.acquire_many_owned(MAX_ACTIVE_PREVIEWS as u32)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!previews.start(job(Uuid::new_v4())).await);
|
||||
previews.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_preview_owner_waits_for_worker_teardown() {
|
||||
let previews = HipPreviews::new();
|
||||
let session_id = Uuid::new_v4();
|
||||
let connection_id = Uuid::new_v4();
|
||||
let cancellation = previews.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let worker_stopped = Arc::clone(&stopped);
|
||||
let worker = tokio::spawn(async move {
|
||||
worker_cancellation.cancelled().await;
|
||||
tokio::task::yield_now().await;
|
||||
worker_stopped.store(true, Ordering::SeqCst);
|
||||
});
|
||||
previews.tasks.lock().await.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
previews.cancel_connection(session_id, Uuid::new_v4()).await;
|
||||
assert!(!stopped.load(Ordering::SeqCst));
|
||||
previews.cancel_connection(session_id, connection_id).await;
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert!(previews.tasks.lock().await.is_empty());
|
||||
previews.shutdown().await;
|
||||
assert!(!previews.start(job(session_id)).await);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_preview_does_not_start_collection() {
|
||||
let preview = job(Uuid::new_v4());
|
||||
let cancelled = CancellationToken::new();
|
||||
cancelled.cancel();
|
||||
let error = generate(preview.request, None, None, preview.identity, cancelled).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
let preview = tokio::spawn(generate(request(&path), None, Some(uid)));
|
||||
let pids = tokio::time::timeout(Duration::from_secs(3), async {
|
||||
loop {
|
||||
if let Ok(pids) = fs::read_to_string(&pid_file) {
|
||||
break pids;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let child_pid = pids.split_whitespace().nth(1).unwrap().parse::<u32>().unwrap();
|
||||
preview.abort();
|
||||
assert!(preview.await.unwrap_err().is_cancelled());
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
loop {
|
||||
let state = fs::read_to_string(format!("/proc/{child_pid}/stat"))
|
||||
.ok()
|
||||
.and_then(|stat| stat.rsplit_once(") ").and_then(|(_, fields)| fields.chars().next()));
|
||||
if state.is_none_or(|state| state == 'Z') {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const RUNNER_NAME: &str = "gp-hip-runner";
|
||||
pub const STATE_NAME: &str = "report.json";
|
||||
pub const MAX_STATE_BYTES: usize = 512 * 1024;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(tag = "source", rename_all = "camelCase")]
|
||||
pub enum RunnerReport {
|
||||
Generated,
|
||||
Edited { xml: String },
|
||||
ApprovedRootScript { approval_id: String, owner_uid: u32 },
|
||||
}
|
||||
|
||||
/// Check every component because a trusted file below a writable parent can
|
||||
/// be replaced before a later HIP refresh.
|
||||
pub fn validate_root_owned_path(path: &Path, file: bool) -> anyhow::Result<()> {
|
||||
ensure!(path.is_absolute(), "HIP runner path must be absolute");
|
||||
for component in path.ancestors().take_while(|part| part.as_os_str() != "/") {
|
||||
let metadata =
|
||||
fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?;
|
||||
ensure!(!metadata.file_type().is_symlink(), "HIP runner path contains a symlink");
|
||||
ensure!(metadata.uid() == 0, "HIP runner path is not root-owned");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o022 == 0,
|
||||
"HIP runner path is writable by another user"
|
||||
);
|
||||
if component == path && file {
|
||||
ensure!(metadata.is_file(), "HIP runner is not a regular file");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o111 != 0,
|
||||
"HIP runner is not executable"
|
||||
);
|
||||
} else {
|
||||
ensure!(metadata.is_dir(), "HIP runner parent is not a directory");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_user_owned_runner_directory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
if unsafe { nix::libc::geteuid() } != 0 {
|
||||
assert!(validate_root_owned_path(temp.path(), false).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
+206
-220
@@ -1,55 +1,35 @@
|
||||
use std::{
|
||||
fs::{self, OpenOptions},
|
||||
io::Write,
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::hip::HipSource;
|
||||
use gpservice::hip_runner_state::{MAX_STATE_BYTES, RUNNER_NAME, RunnerReport, STATE_NAME, validate_root_owned_path};
|
||||
use tempfile::{Builder, TempDir};
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
hip::HipSource,
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput};
|
||||
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
|
||||
|
||||
pub(crate) struct HipExecution {
|
||||
pub enabled: bool,
|
||||
pub uid: u32,
|
||||
pub wrapper: Option<String>,
|
||||
_state_dir: Option<TempDir>,
|
||||
approval: Option<(String, u32)>,
|
||||
pub source: openconnect::HipSource,
|
||||
approval: HipApproval,
|
||||
}
|
||||
|
||||
impl HipExecution {
|
||||
fn disabled() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
uid: 0,
|
||||
wrapper: None,
|
||||
_state_dir: None,
|
||||
approval: None,
|
||||
}
|
||||
pub(crate) fn into_parts(self) -> (openconnect::HipSource, HipApproval) {
|
||||
(self.source, self.approval)
|
||||
}
|
||||
}
|
||||
|
||||
fn script(uid: u32, wrapper: PathBuf, state_dir: Option<TempDir>) -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
uid,
|
||||
wrapper: Some(wrapper.to_string_lossy().into_owned()),
|
||||
_state_dir: state_dir,
|
||||
approval: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn approval_id(&self) -> Option<&str> {
|
||||
self.approval.as_ref().map(|(id, _)| id.as_str())
|
||||
}
|
||||
pub(crate) struct HipApproval {
|
||||
identity: Option<(String, u32)>,
|
||||
}
|
||||
|
||||
impl HipApproval {
|
||||
pub(crate) fn approval_is_valid(&self) -> bool {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some((id, uid)) = &self.approval {
|
||||
if let Some((id, uid)) = &self.identity {
|
||||
return gpservice::hip_approval::resolve(id, *uid).is_ok();
|
||||
}
|
||||
true
|
||||
self.identity.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,234 +38,240 @@ pub(crate) fn resolve(
|
||||
desktop_uid: Option<u32>,
|
||||
brokered_macos: bool,
|
||||
edited_report: Option<Arc<str>>,
|
||||
profile: Option<OsProfile>,
|
||||
) -> anyhow::Result<HipExecution> {
|
||||
match source {
|
||||
HipSource::Disabled => Ok(HipExecution::disabled()),
|
||||
HipSource::Generated => stage_runner(RunnerReport::Generated),
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
|
||||
gphip::validate_edited_report(&xml)?;
|
||||
stage_runner(RunnerReport::Edited { xml: xml.to_string() })
|
||||
let approval;
|
||||
let source = match source {
|
||||
HipSource::Disabled => {
|
||||
approval = None;
|
||||
openconnect::HipSource::Disabled
|
||||
}
|
||||
HipSource::Generated | HipSource::Edited { .. } => {
|
||||
let profile = profile.context("HIP generator identity is unavailable")?;
|
||||
approval = None;
|
||||
let xml = match source {
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
|
||||
gphip::validate_edited_report(&xml)?;
|
||||
Some(xml)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
openconnect::HipSource::Generator(Arc::new(move |request, control| {
|
||||
generate(&profile, xml.as_deref(), request, &|| control.check(), false).map_err(generation_error)
|
||||
}))
|
||||
}
|
||||
HipSource::UserScript { path } => {
|
||||
if cfg!(target_os = "macos") || brokered_macos {
|
||||
bail!("Custom HIP scripts are unavailable on macOS");
|
||||
}
|
||||
approval = None;
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
|
||||
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
|
||||
let path = PathBuf::from(path);
|
||||
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
|
||||
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
|
||||
"HIP custom script must be an executable regular file"
|
||||
);
|
||||
Ok(HipExecution::script(uid, path, None))
|
||||
let script =
|
||||
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
HipSource::ApprovedRootScript { approval_id } => {
|
||||
if cfg!(target_os = "macos") || brokered_macos {
|
||||
bail!("Custom HIP scripts are unavailable on macOS");
|
||||
}
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
|
||||
gpservice::hip_approval::resolve(approval_id, owner_uid)?;
|
||||
let mut execution = stage_runner(RunnerReport::ApprovedRootScript {
|
||||
approval_id: approval_id.clone(),
|
||||
owner_uid,
|
||||
})?;
|
||||
execution.approval = Some((approval_id.clone(), owner_uid));
|
||||
Ok(execution)
|
||||
let approved = gpservice::hip_approval::resolve(approval_id, owner_uid)?;
|
||||
let id = approval_id.clone();
|
||||
let path = approved.path;
|
||||
let expected = path.clone();
|
||||
let script = HipScript::new(path.to_string_lossy().into_owned(), Some(0))?
|
||||
.with_environment(script_environment(0)?)?
|
||||
.with_validator(move |control| {
|
||||
control.check()?;
|
||||
let current = gpservice::hip_approval::resolve_with_control(&id, owner_uid, &|| control.check())
|
||||
.map_err(generation_error)?;
|
||||
if current.path != expected {
|
||||
return Err(io::Error::other("Approved HIP executable changed"));
|
||||
}
|
||||
control.check()
|
||||
});
|
||||
approval = Some((approval_id.clone(), owner_uid));
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
let _ = (approval_id, desktop_uid);
|
||||
bail!("Root HIP script approvals are unavailable on this platform")
|
||||
anyhow::bail!("Root HIP script approvals are unavailable on this platform")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn preview_runner(edited_report: Option<Arc<str>>) -> anyhow::Result<HipExecution> {
|
||||
let report = if let Some(xml) = edited_report {
|
||||
gphip::validate_edited_report(&xml)?;
|
||||
RunnerReport::Edited { xml: xml.to_string() }
|
||||
} else {
|
||||
RunnerReport::Generated
|
||||
};
|
||||
stage_runner(report)
|
||||
Ok(HipExecution {
|
||||
source,
|
||||
approval: HipApproval { identity: approval },
|
||||
})
|
||||
}
|
||||
|
||||
fn stage_runner(report: RunnerReport) -> anyhow::Result<HipExecution> {
|
||||
let source = packaged_runner()?;
|
||||
let base = runner_state_base();
|
||||
fs::create_dir_all(base).context("Cannot create HIP runtime directory")?;
|
||||
validate_root_owned_path(base, false)?;
|
||||
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
|
||||
let state_dir = Builder::new().prefix("session-").tempdir_in(base)?;
|
||||
fs::set_permissions(state_dir.path(), fs::Permissions::from_mode(0o700))?;
|
||||
validate_root_owned_path(state_dir.path(), false)?;
|
||||
|
||||
let runner = state_dir.path().join(RUNNER_NAME);
|
||||
fs::copy(&source, &runner).context("Cannot stage HIP runner")?;
|
||||
fs::set_permissions(&runner, fs::Permissions::from_mode(0o500))?;
|
||||
validate_root_owned_path(&runner, true)?;
|
||||
verify_staged_runner(&runner)?;
|
||||
|
||||
let encoded_state = serde_json::to_vec(&report)?;
|
||||
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
encoded_state.len() <= MAX_STATE_BYTES,
|
||||
"HIP runner state exceeds its size limit"
|
||||
!cfg!(target_os = "macos") && !brokered_macos,
|
||||
"Custom HIP scripts are unavailable on macOS"
|
||||
);
|
||||
let state = state_dir.path().join(STATE_NAME);
|
||||
let mut state_file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&state)?;
|
||||
state_file.write_all(&encoded_state)?;
|
||||
state_file.flush()?;
|
||||
Ok(HipExecution::script(0, runner, Some(state_dir)))
|
||||
}
|
||||
|
||||
fn runner_state_base() -> &'static Path {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
Path::new("/private/var/db/gpclient/hip")
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
Path::new("/var/lib/gpclient/hip")
|
||||
}
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
Path::new("/var/db/gpclient/hip")
|
||||
}
|
||||
}
|
||||
|
||||
fn packaged_runner() -> anyhow::Result<PathBuf> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let path = std::env::current_exe()
|
||||
.context("Cannot locate HIP runner")?
|
||||
.with_file_name(RUNNER_NAME);
|
||||
#[cfg(target_os = "linux")]
|
||||
let path = PathBuf::from("/usr/libexec/gpclient/gp-hip-runner");
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
let path = PathBuf::from("/usr/local/libexec/gpclient/gp-hip-runner");
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
validate_root_owned_path(&path, true)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
verify_packaged_macos_runner(&path)?;
|
||||
ensure!(path.is_file(), "Bundled HIP runner is missing");
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn verify_packaged_macos_runner(path: &Path) -> anyhow::Result<()> {
|
||||
use std::process::Command;
|
||||
let service = std::env::current_exe()?;
|
||||
let app = service
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.and_then(Path::parent)
|
||||
.context("gpservice is not in an app bundle")?;
|
||||
ensure!(
|
||||
path.parent() == service.parent(),
|
||||
"HIP runner is outside the app Helpers directory"
|
||||
);
|
||||
let status = Command::new("/usr/bin/codesign")
|
||||
.args(["--verify", "--deep", "--strict"])
|
||||
.arg(app)
|
||||
.status()?;
|
||||
ensure!(status.success(), "HIP application bundle signature is invalid");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn verify_staged_runner(path: &Path) -> anyhow::Result<()> {
|
||||
use std::process::Command;
|
||||
let status = Command::new("/usr/bin/codesign")
|
||||
.args(["--verify", "--strict"])
|
||||
.arg(path)
|
||||
.status()?;
|
||||
ensure!(status.success(), "Staged HIP runner signature is invalid");
|
||||
let service = std::env::current_exe()?;
|
||||
ensure!(
|
||||
signing_team(path)? == signing_team(&service)?,
|
||||
"HIP runner and service have different signing teams"
|
||||
);
|
||||
|
||||
// The staged runner has no app Frameworks directory. Reject any library
|
||||
// reference that could resolve through a writable bundle or search path.
|
||||
let output = Command::new("/usr/bin/otool").arg("-L").arg(path).output()?;
|
||||
ensure!(output.status.success(), "Cannot inspect HIP runner libraries");
|
||||
for library in String::from_utf8(output.stdout)?
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| line.trim().split_whitespace().next())
|
||||
{
|
||||
ensure!(
|
||||
library.starts_with("/usr/lib/") || library.starts_with("/System/Library/"),
|
||||
"HIP runner loads a library outside the trusted system paths"
|
||||
);
|
||||
pub(crate) fn generate(
|
||||
profile: &OsProfile,
|
||||
edited: Option<&str>,
|
||||
request: &HipRequest,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
preview: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
control.check()?;
|
||||
let context = if preview {
|
||||
ReportContext::Preview
|
||||
} else {
|
||||
ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
}
|
||||
};
|
||||
let input = ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
};
|
||||
match edited {
|
||||
Some(xml) => gphip::refresh_edited_report_with_control(xml, &input, control),
|
||||
None => gphip::generate_report_with_control(&input, control),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn signing_team(path: &Path) -> anyhow::Result<String> {
|
||||
let output = std::process::Command::new("/usr/bin/codesign")
|
||||
.args(["-d", "--verbose=4"])
|
||||
.arg(path)
|
||||
.output()?;
|
||||
ensure!(output.status.success(), "Cannot inspect code signature");
|
||||
let details = String::from_utf8(output.stderr)?;
|
||||
details
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("TeamIdentifier="))
|
||||
.filter(|team| !team.is_empty() && *team != "not set")
|
||||
.map(str::to_owned)
|
||||
.context("Signed HIP binary has no team identifier")
|
||||
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
|
||||
let user =
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
|
||||
let home = user.dir.to_string_lossy().into_owned();
|
||||
Ok(HipScriptEnvironment {
|
||||
variables: vec![
|
||||
(
|
||||
"PATH".into(),
|
||||
gpapi::process::collection::command_path(uid == 0)?
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
|
||||
),
|
||||
("LC_ALL".into(), "C".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), user.name.clone()),
|
||||
("LOGNAME".into(), user.name),
|
||||
],
|
||||
cwd: home,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn verify_staged_runner(_path: &Path) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
pub(crate) fn profile(
|
||||
identity: &HostIdentity,
|
||||
os: ClientOs,
|
||||
version: Option<String>,
|
||||
os_version: Option<String>,
|
||||
host_id: Option<String>,
|
||||
hostname: Option<String>,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> io::Result<OsProfile> {
|
||||
let identity = HostIdentity::from_parts(
|
||||
hostname.unwrap_or_else(|| identity.computer().into()),
|
||||
host_id.unwrap_or_else(|| identity.host_id().into()),
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
);
|
||||
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
|
||||
if let Some(version) = version {
|
||||
builder = builder.client_version(version);
|
||||
}
|
||||
if let Some(os_version) = os_version {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
builder.build_with_control(control)
|
||||
}
|
||||
|
||||
fn generation_error(error: anyhow::Error) -> io::Error {
|
||||
match error.downcast::<io::Error>() {
|
||||
Ok(error) => error,
|
||||
Err(error) => io::Error::other(error),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::ClientOs;
|
||||
|
||||
#[test]
|
||||
fn disabled_has_no_script_on_both_gui_platforms() {
|
||||
for brokered_macos in [false, true] {
|
||||
let execution = resolve(&HipSource::Disabled, None, brokered_macos, None).unwrap();
|
||||
assert!(!execution.enabled);
|
||||
assert!(execution.wrapper.is_none());
|
||||
}
|
||||
fn fixture_profile() -> OsProfile {
|
||||
profile(
|
||||
&HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
ClientOs::Linux,
|
||||
Some("6.3.3".into()),
|
||||
Some("negotiated-version".into()),
|
||||
None,
|
||||
None,
|
||||
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_source_cannot_choose_root_or_run_on_macos() {
|
||||
fn callback_configuration_needs_no_files_or_root_identity() {
|
||||
let generated = resolve(&HipSource::Generated, None, true, None, Some(fixture_profile())).unwrap();
|
||||
assert!(matches!(generated.source, openconnect::HipSource::Generator(_)));
|
||||
let disabled = resolve(&HipSource::Disabled, None, true, None, Some(fixture_profile())).unwrap();
|
||||
assert!(matches!(disabled.source, openconnect::HipSource::Disabled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_retains_negotiated_identity_and_os_version() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"original".into(),
|
||||
"original-id".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = profile(
|
||||
&identity,
|
||||
ClientOs::Mac,
|
||||
Some("6.3.3".into()),
|
||||
Some("negotiated-os".into()),
|
||||
Some("negotiated-host".into()),
|
||||
Some("negotiated-name".into()),
|
||||
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.os_version(), "negotiated-os");
|
||||
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
|
||||
assert_eq!(profile.host_identity().computer(), "negotiated-name");
|
||||
assert_eq!(profile.host_identity().serialno(), "serial");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_errors_preserve_cancellation() {
|
||||
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_source_cannot_run_on_macos_or_choose_root_without_approval() {
|
||||
let source = HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
};
|
||||
assert!(resolve(&source, None, false, None).is_err());
|
||||
assert!(resolve(&source, Some(0), false, None).is_err());
|
||||
assert!(resolve(&source, Some(1000), true, None).is_err());
|
||||
assert!(resolve(&source, None, false, None, None).is_err());
|
||||
assert!(resolve(&source, Some(0), false, None, None).is_err());
|
||||
assert!(resolve(&source, Some(1000), true, None, Some(fixture_profile())).is_err());
|
||||
#[cfg(target_os = "macos")]
|
||||
assert!(resolve(&source, Some(1000), false, None).is_err());
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn root_source_requires_a_bound_user_and_installed_approval() {
|
||||
let source = HipSource::ApprovedRootScript {
|
||||
approval_id: "00000000-0000-4000-8000-000000000000".into(),
|
||||
};
|
||||
assert!(resolve(&source, None, false, None).is_err());
|
||||
assert!(resolve(&source, Some(0), false, None).is_err());
|
||||
assert!(resolve(&source, Some(1000), false, None).is_err());
|
||||
assert!(resolve(&source, Some(1000), false, None, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod hip_approval;
|
||||
pub mod hip_runner_state;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod vpnc_script;
|
||||
@@ -1,6 +1,7 @@
|
||||
mod cli;
|
||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||
mod credential_lease;
|
||||
mod desktop_client;
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev_bootstrap;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||
|
||||
@@ -24,6 +24,54 @@ const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
||||
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
||||
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
||||
|
||||
pub(crate) struct SessionAuthority {
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub session_id: uuid::Uuid,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
pub(crate) enum PendingDispatch {
|
||||
Connect {
|
||||
preparation: ConnectionPreparation,
|
||||
request: Box<gpapi::service::request::ConnectRequest>,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
},
|
||||
Drain(Option<crate::vpn_task::AttemptDrain>),
|
||||
Other(WsRequest),
|
||||
}
|
||||
|
||||
pub(crate) struct ConnectionPreparation {
|
||||
authority: SessionAuthority,
|
||||
non_tunnel: bool,
|
||||
reservation: Option<crate::vpn_task::ConnectReservation>,
|
||||
}
|
||||
|
||||
impl ConnectionPreparation {
|
||||
fn cancellation(&self) -> tokio_util::sync::CancellationToken {
|
||||
self
|
||||
.reservation
|
||||
.as_ref()
|
||||
.expect("preparation retains reservation")
|
||||
.cancellation()
|
||||
}
|
||||
|
||||
fn commit(
|
||||
mut self,
|
||||
connection: crate::vpn_task::PreparedConnection,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
) -> ServiceResult {
|
||||
let reservation = self.reservation.take().expect("preparation retains reservation");
|
||||
self.authority.registry.commit_connection(
|
||||
self.authority.session_id,
|
||||
self.authority.generation,
|
||||
self.non_tunnel,
|
||||
|| reservation.commit(connection, desktop_uid, edited_report, Some(self.authority.session_id)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RequestDispatcher {
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
@@ -56,38 +104,123 @@ impl RequestDispatcher {
|
||||
request: WsRequest,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
session_id: Option<uuid::Uuid>,
|
||||
) -> Result<WsRequest, ServiceResult> {
|
||||
authority: Option<SessionAuthority>,
|
||||
) -> Result<PendingDispatch, ServiceResult> {
|
||||
match request {
|
||||
WsRequest::Connect(request) => {
|
||||
if let Err(message) = self.validate_connect_paths(&request) {
|
||||
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
||||
}
|
||||
if let Err(err) = self
|
||||
.redaction
|
||||
.add_values(&[request.gateway().server(), request.args().cookie()])
|
||||
{
|
||||
let redaction_values = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.flat_map(|member| [member.gateway.server(), member.authentication.cookie()])
|
||||
.collect::<Vec<_>>();
|
||||
if let Err(err) = self.redaction.add_values(&redaction_values) {
|
||||
warn!("Failed to update log redaction: {err}");
|
||||
return Err(ServiceResult::rejected(
|
||||
ServiceErrorCode::Internal,
|
||||
"Request could not be accepted",
|
||||
));
|
||||
}
|
||||
Err(
|
||||
self
|
||||
.lifecycle
|
||||
.submit_connect(*request, desktop_uid, edited_report, session_id),
|
||||
)
|
||||
let authority = authority
|
||||
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||
let non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||
let reservation =
|
||||
authority
|
||||
.registry
|
||||
.reserve_connection(authority.session_id, authority.generation, non_tunnel, || {
|
||||
self.lifecycle.reserve_connect()
|
||||
})?;
|
||||
let preparation = ConnectionPreparation {
|
||||
authority,
|
||||
non_tunnel,
|
||||
reservation: Some(reservation),
|
||||
};
|
||||
let edited_report = if let gpapi::hip::HipSource::Edited { report_id } = request.args().hip_source() {
|
||||
let report_id = uuid::Uuid::parse_str(report_id)
|
||||
.map_err(|_| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"))?;
|
||||
Some(
|
||||
preparation
|
||||
.authority
|
||||
.registry
|
||||
.edited_hip_report(preparation.authority.session_id, report_id)
|
||||
.map_err(|_| {
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"HIP report is unavailable for this session",
|
||||
)
|
||||
})?,
|
||||
)
|
||||
} else {
|
||||
edited_report
|
||||
};
|
||||
Ok(PendingDispatch::Connect {
|
||||
preparation,
|
||||
request,
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
})
|
||||
}
|
||||
WsRequest::StopNonTunnelAttachment { connection_id } => {
|
||||
let authority = authority
|
||||
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||
let drain =
|
||||
authority
|
||||
.registry
|
||||
.stop_non_tunnel_attachment(authority.session_id, authority.generation, connection_id)?;
|
||||
Ok(PendingDispatch::Drain(drain))
|
||||
}
|
||||
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
||||
request => Ok(request),
|
||||
request => Ok(PendingDispatch::Other(request)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
||||
let request = match self.dispatch_lifecycle(request, None, None, None) {
|
||||
Ok(request) => request,
|
||||
Err(result) => return result,
|
||||
match self.dispatch_lifecycle(request, None, None, None) {
|
||||
Ok(request) => self.dispatch_pending(request).await,
|
||||
Err(result) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn dispatch_pending(&self, request: PendingDispatch) -> ServiceResult {
|
||||
let request = match request {
|
||||
PendingDispatch::Connect {
|
||||
preparation,
|
||||
request,
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
} => {
|
||||
let prepared = crate::vpn_task::prepare_connection(
|
||||
*request,
|
||||
self.brokered_scripts_dir.is_some(),
|
||||
preparation.cancellation(),
|
||||
)
|
||||
.await;
|
||||
return match prepared {
|
||||
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||
Err(error) => {
|
||||
warn!("Connection preparation failed: {error:#}");
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Connection resources could not be prepared",
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
PendingDispatch::Drain(drain) => {
|
||||
if let Some(drain) = drain {
|
||||
drain.wait().await;
|
||||
}
|
||||
return ServiceResult::Accepted;
|
||||
}
|
||||
PendingDispatch::Other(request) => request,
|
||||
};
|
||||
|
||||
match request {
|
||||
@@ -132,6 +265,7 @@ impl RequestDispatcher {
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
WsRequest::Connect(_)
|
||||
| WsRequest::StopNonTunnelAttachment { .. }
|
||||
| WsRequest::Disconnect(_)
|
||||
| WsRequest::StoreEditedHipReportChunk(_)
|
||||
| WsRequest::PreviewHipReport(_)
|
||||
@@ -296,14 +430,12 @@ fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<N
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::vpn_task::test_connect_request as test_request;
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::{
|
||||
request::ConnectRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
service::transport::{ServiceErrorCode, ServiceResult},
|
||||
};
|
||||
use tar::{Builder, EntryType, Header};
|
||||
use xz2::write::XzEncoder;
|
||||
@@ -426,7 +558,7 @@ mod tests {
|
||||
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let request = ConnectRequest::new(info, "cookie".into())
|
||||
let request = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_certificate(Some("/Users/example/client.pem".to_string()));
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
|
||||
@@ -446,18 +578,17 @@ mod tests {
|
||||
);
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let bundled = ConnectRequest::new(info.clone(), "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
||||
let bundled =
|
||||
test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
||||
|
||||
let old_layout = ConnectRequest::new(info.clone(), "cookie".into())
|
||||
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
||||
let old_layout = test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&old_layout),
|
||||
Err("macOS VPN script must be the bundled script")
|
||||
);
|
||||
|
||||
let custom = ConnectRequest::new(info, "cookie".into())
|
||||
let custom = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_hip_source(gpapi::hip::HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::{
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use gpapi::service::transport::{ServiceErrorCode, ServiceResult, SessionCredential};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
@@ -62,6 +62,8 @@ enum SessionStatus {
|
||||
}
|
||||
|
||||
struct SessionRecord {
|
||||
non_tunnel: Option<AttachmentAttempt>,
|
||||
closed_attachment: Option<Uuid>,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
desktop_uid: Option<u32>,
|
||||
@@ -72,16 +74,145 @@ struct SessionRecord {
|
||||
status: SessionStatus,
|
||||
}
|
||||
|
||||
/// Only live preparation/execution is retained, never acceptance history.
|
||||
struct AttachmentAttempt {
|
||||
generation: u64,
|
||||
connection_id: Uuid,
|
||||
drain: crate::vpn_task::AttemptDrain,
|
||||
}
|
||||
|
||||
pub struct SessionRegistry {
|
||||
service_instance_id: Uuid,
|
||||
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
resolve_device_anchor: fn() -> anyhow::Result<gpapi::device_anchor::DeviceAnchor>,
|
||||
}
|
||||
|
||||
fn unavailable_connection() -> ServiceResult {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection attachment is unavailable")
|
||||
}
|
||||
|
||||
fn current_connection(record: &SessionRecord, expected: u64) -> Result<Uuid, ServiceResult> {
|
||||
match &record.status {
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
connection: Some(connection),
|
||||
..
|
||||
} if *generation == expected && !connection.is_closed() => Ok(connection.connection_id()),
|
||||
_ => Err(unavailable_connection()),
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionRegistry {
|
||||
pub(crate) fn reserve_connection(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
non_tunnel: bool,
|
||||
reserve: impl FnOnce() -> Result<crate::vpn_task::ConnectReservation, ServiceResult>,
|
||||
) -> Result<crate::vpn_task::ConnectReservation, ServiceResult> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||
let connection_id = current_connection(record, generation)?;
|
||||
if non_tunnel && record.closed_attachment == Some(connection_id) {
|
||||
return Err(ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Non-tunnel attachment is closing",
|
||||
));
|
||||
}
|
||||
if record
|
||||
.non_tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|attempt| attempt.drain.is_complete())
|
||||
{
|
||||
record.non_tunnel = None;
|
||||
}
|
||||
let reservation = reserve()?;
|
||||
if non_tunnel {
|
||||
record.non_tunnel = Some(AttachmentAttempt {
|
||||
generation,
|
||||
connection_id,
|
||||
drain: reservation.drain(),
|
||||
});
|
||||
}
|
||||
Ok(reservation)
|
||||
}
|
||||
|
||||
pub(crate) fn commit_connection(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
non_tunnel: bool,
|
||||
commit: impl FnOnce() -> ServiceResult,
|
||||
) -> ServiceResult {
|
||||
let Ok(sessions) = self.sessions.lock() else {
|
||||
return unavailable_connection();
|
||||
};
|
||||
let Some(record) = sessions.get(&session_id) else {
|
||||
return unavailable_connection();
|
||||
};
|
||||
if non_tunnel {
|
||||
let connection_id = match current_connection(record, generation) {
|
||||
Ok(id) => id,
|
||||
Err(result) => return result,
|
||||
};
|
||||
if record.closed_attachment == Some(connection_id) {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Non-tunnel attachment is closing");
|
||||
}
|
||||
} else if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return unavailable_connection();
|
||||
}
|
||||
// Non-tunnel attachment invalidation takes this same lock. An authorized
|
||||
// tunnel reservation survives attachment loss as before; revoked sessions
|
||||
// cannot commit either mode. Queue insertion transfers cleanup ownership.
|
||||
commit()
|
||||
}
|
||||
|
||||
pub(crate) fn stop_non_tunnel_attachment(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
connection_id: Uuid,
|
||||
) -> Result<Option<crate::vpn_task::AttemptDrain>, ServiceResult> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||
let current_id = current_connection(record, generation)?;
|
||||
if current_id == connection_id {
|
||||
record.closed_attachment = Some(connection_id);
|
||||
}
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
if attempt.connection_id == connection_id {
|
||||
attempt.drain.cancel();
|
||||
return Ok(Some(attempt.drain.clone()));
|
||||
}
|
||||
}
|
||||
// No retained live work belongs to that attachment. Never stop a successor.
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn new(service_instance_id: Uuid) -> Self {
|
||||
Self {
|
||||
service_instance_id,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
resolve_device_anchor: crate::device_anchor::resolve,
|
||||
}
|
||||
}
|
||||
|
||||
/// Session tests use an explicit anchor fixture; persistence and permissions
|
||||
/// are exercised separately by the device_anchor tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_tests(service_instance_id: Uuid) -> Self {
|
||||
Self {
|
||||
service_instance_id,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
resolve_device_anchor: || {
|
||||
Ok(gpapi::device_anchor::DeviceAnchor::derive(
|
||||
gpapi::device_anchor::AnchorSource::UnixRandom,
|
||||
b"session-registry-test-anchor",
|
||||
))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +239,7 @@ impl SessionRegistry {
|
||||
SessionCredential::generate(self.service_instance_id, product_version).map_err(|_| SessionError::Unavailable)?;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let credential = {
|
||||
let anchor = crate::device_anchor::resolve().map_err(|error| {
|
||||
let anchor = (self.resolve_device_anchor)().map_err(|error| {
|
||||
log::warn!("GUI device anchor unavailable: {error:#}");
|
||||
SessionError::Unavailable
|
||||
})?;
|
||||
@@ -120,6 +251,8 @@ impl SessionRegistry {
|
||||
sessions.insert(
|
||||
credential.session_id(),
|
||||
SessionRecord {
|
||||
non_tunnel: None,
|
||||
closed_attachment: None,
|
||||
secret: Zeroizing::new(*credential.secret()),
|
||||
product_version: credential.product_version().to_owned(),
|
||||
desktop_uid,
|
||||
@@ -258,6 +391,10 @@ impl SessionRegistry {
|
||||
connection: current,
|
||||
reconnect_token,
|
||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
record.closed_attachment = None;
|
||||
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
||||
*reconnect_token = None;
|
||||
Ok(current.replace(connection))
|
||||
@@ -418,6 +555,13 @@ impl SessionRegistry {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return;
|
||||
};
|
||||
if let Some(record) = sessions.get_mut(&session_id) {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
if attempt.generation == generation {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(SessionRecord {
|
||||
status: SessionStatus::Active {
|
||||
generation: current,
|
||||
@@ -438,9 +582,14 @@ impl SessionRegistry {
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut sessions| sessions.remove(&session_id))
|
||||
.and_then(|record| match record.status {
|
||||
SessionStatus::Active { connection, .. } => connection,
|
||||
SessionStatus::Pending { .. } => None,
|
||||
.and_then(|record| {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
match record.status {
|
||||
SessionStatus::Active { connection, .. } => connection,
|
||||
SessionStatus::Pending { .. } => None,
|
||||
}
|
||||
});
|
||||
if let Some(connection) = connection {
|
||||
connection.close(gpapi::service::transport::CloseReason::Unauthorized);
|
||||
@@ -468,9 +617,164 @@ mod tests {
|
||||
ConnectionControl::new(Uuid::new_v4(), tx).0
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn unavailable_device_anchor_does_not_issue_a_session() {
|
||||
let mut registry = SessionRegistry::for_tests(Uuid::new_v4());
|
||||
registry.resolve_device_anchor = || anyhow::bail!("fixture anchor unavailable");
|
||||
assert!(matches!(
|
||||
registry.issue("fixture", None),
|
||||
Err(SessionError::Unavailable)
|
||||
));
|
||||
assert!(registry.sessions.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn issued_credential_carries_the_resolved_device_anchor() {
|
||||
let registry = SessionRegistry::for_tests(Uuid::new_v4());
|
||||
let expected = (registry.resolve_device_anchor)().unwrap();
|
||||
let credential = registry.issue("fixture", Some(1000)).unwrap();
|
||||
assert_eq!(credential.device_anchor(), Some(&expected));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_replacement_cancels_preparation_and_retains_drain_until_release() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let first_control = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||
let old_id = first_control.connection_id();
|
||||
registry.commit_attach(&first, first_control).unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
let drain = reservation.drain();
|
||||
let cancel = reservation.cancellation();
|
||||
|
||||
let next = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _next_rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&next, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
assert!(cancel.is_cancelled());
|
||||
assert!(!drain.is_complete());
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.is_err()
|
||||
);
|
||||
assert!(matches!(
|
||||
registry.commit_connection(session, 1, true, || panic!("stale start committed")),
|
||||
ServiceResult::Rejected(_)
|
||||
));
|
||||
drop(reservation);
|
||||
drain.wait().await;
|
||||
|
||||
let next_reservation = registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
assert!(
|
||||
registry
|
||||
.stop_non_tunnel_attachment(session, 2, old_id)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(!next_reservation.cancellation().is_cancelled());
|
||||
registry.disconnect_if_current(session, 1);
|
||||
assert!(!next_reservation.cancellation().is_cancelled());
|
||||
registry.disconnect_if_current(session, 2);
|
||||
assert!(next_reservation.cancellation().is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scoped_stop_closes_attachment_to_delayed_starts_without_receipt_history() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let connection = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||
let id = connection.connection_id();
|
||||
registry.commit_attach(&permit, connection).unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap();
|
||||
assert!(reservation.cancellation().is_cancelled());
|
||||
assert!(matches!(
|
||||
registry.commit_connection(session, 1, true, || panic!("closing start committed")),
|
||||
ServiceResult::Rejected(_)
|
||||
));
|
||||
assert!(!drain.is_complete());
|
||||
drop(reservation);
|
||||
drain.wait().await;
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 1, true, || panic!("closed attachment reserved"))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tunnel_reservation_survives_attachment_loss_but_non_tunnel_revocation_cancels() {
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let tunnel = registry
|
||||
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
registry.disconnect_if_current(session, 1);
|
||||
assert!(!tunnel.cancellation().is_cancelled());
|
||||
assert_eq!(
|
||||
registry.commit_connection(session, 1, false, || ServiceResult::Accepted),
|
||||
ServiceResult::Accepted
|
||||
);
|
||||
drop(tunnel);
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _next_rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
let session_work = registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
registry.revoke(session);
|
||||
assert!(session_work.cancellation().is_cancelled());
|
||||
assert!(!session_work.drain().is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_retains_verified_desktop_user_across_reconnect() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", Some(1000)).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
@@ -507,7 +811,7 @@ mod tests {
|
||||
panic!("upload did not complete")
|
||||
}
|
||||
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let first_credential = registry.issue("2.6.4", Some(1000)).unwrap();
|
||||
let second_credential = registry.issue("2.6.4", Some(1001)).unwrap();
|
||||
for credential in [&first_credential, &second_credential] {
|
||||
@@ -551,7 +855,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn submitted_report_changes_only_after_success_callback_and_is_session_bound() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", Some(1000)).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
@@ -604,7 +908,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn reconnect_uses_generation_compare_and_swap() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
@@ -625,7 +929,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_initial_handshake_only_revokes_its_own_reservation() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
@@ -639,7 +943,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_reconnect_keeps_active_connection_authoritative() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
|
||||
+776
-290
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,192 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
use gpapi::process::collection::CollectionControl;
|
||||
use gpapi::session::{
|
||||
GatewaySessionSummary, MaintenanceState, SessionEndReason,
|
||||
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||
};
|
||||
use log::warn;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
LifecycleEvent,
|
||||
runtime::{AttemptInput, stop_for_revoked_approval},
|
||||
};
|
||||
|
||||
/// Borrow the accepted ledger. The outer attempt owner retains identity/source
|
||||
/// resources and joins this runtime before draining the remaining members.
|
||||
pub(super) async fn run(
|
||||
input: &mut AttemptInput,
|
||||
source: Arc<openconnect::HipSource>,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
let request = &input.connection.request;
|
||||
let args = request.args();
|
||||
let resources = &input.connection.resources;
|
||||
let sessions = &mut input.connection.sessions;
|
||||
let network = resources
|
||||
.network
|
||||
.as_ref()
|
||||
.context("Physical network context is missing")?;
|
||||
let posture_enabled =
|
||||
request.plan().policy().collect_hip_data() && !matches!(args.hip_source(), gpapi::hip::HipSource::Disabled);
|
||||
let profile = resources.profile.clone();
|
||||
let initial = sessions
|
||||
.members()
|
||||
.iter()
|
||||
.map(|session| GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: gpapi::session::SessionMode::NonTunnel,
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
maintenance: MaintenanceState::Authenticated,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let (status, mut changed) = watch::channel(initial);
|
||||
let registry = input.registry.clone();
|
||||
let session_id = input.session_id;
|
||||
let validation_network = network.clone();
|
||||
let validation_detection = request.plan().internal_detection().cloned();
|
||||
let callbacks = SessionCallbacks {
|
||||
validate_network: Arc::new(move |cancel| {
|
||||
let network = validation_network.clone();
|
||||
let detection = validation_detection.clone();
|
||||
Box::pin(async move { network.validate_internal(detection.as_ref(), &cancel).await })
|
||||
}),
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
let context = gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
};
|
||||
if !posture_enabled {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
&openconnect::HipRequest {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
client_version: profile.client_version().into(),
|
||||
client_os: profile.client_os().as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: Some(profile.host_id().into()),
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
},
|
||||
&|| control.check(),
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(move |_, xml| {
|
||||
if let Some(session_id) = session_id {
|
||||
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||
warn!("Could not retain submitted HIP report: {error}");
|
||||
}
|
||||
}
|
||||
}),
|
||||
status_changed: Arc::new(move |summary| {
|
||||
status.send_modify(|members| {
|
||||
if let Some(member) = members
|
||||
.iter_mut()
|
||||
.find(|member| member.gateway.server() == summary.gateway.server())
|
||||
{
|
||||
*member = summary;
|
||||
}
|
||||
});
|
||||
}),
|
||||
};
|
||||
let monitor_cancel = cancellation.child_token();
|
||||
let monitor_token = monitor_cancel.clone();
|
||||
let network = network.clone();
|
||||
let detection = request.plan().internal_detection().cloned();
|
||||
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||
let monitor = tokio::spawn(async move {
|
||||
match network.wait_for_change(detection, monitor_token).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) => {
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Physical network inspection failed: {error}");
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut approval_revoked = false;
|
||||
let result = {
|
||||
let lifecycle_cancel = cancellation.clone();
|
||||
let maintenance = maintain_non_tunnel_sessions(
|
||||
sessions,
|
||||
request.plan().policy(),
|
||||
callbacks,
|
||||
lifecycle_cancel,
|
||||
async move { network_signal.await.unwrap_or(SessionEndReason::NetworkChanged) },
|
||||
);
|
||||
tokio::pin!(maintenance);
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut publish = true;
|
||||
let result = loop {
|
||||
if publish && !cancellation.is_cancelled() {
|
||||
let members = changed.borrow_and_update().clone();
|
||||
let _ = events
|
||||
.send(LifecycleEvent::MembersChanged {
|
||||
attempt: input.attempt,
|
||||
members,
|
||||
failures: request.plan().failures().to_vec(),
|
||||
})
|
||||
.await;
|
||||
publish = false;
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut maintenance => break result,
|
||||
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||
approval_revoked = true;
|
||||
stop_for_revoked_approval(&input.lifecycle, &cancellation);
|
||||
},
|
||||
result = changed.changed() => { if result.is_ok() { publish = true; } },
|
||||
}
|
||||
};
|
||||
// Maintenance can invalidate every member and finish in the same poll.
|
||||
// Forward that last snapshot before monitor/remote cleanup, even when the
|
||||
// completed maintenance branch won over the watch notification.
|
||||
if !cancellation.is_cancelled() {
|
||||
let members = changed.borrow_and_update().clone();
|
||||
let _ = events
|
||||
.send(LifecycleEvent::MembersChanged {
|
||||
attempt: input.attempt,
|
||||
members,
|
||||
failures: request.plan().failures().to_vec(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
result
|
||||
};
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Network monitor worker failed")?;
|
||||
if approval_revoked {
|
||||
let _ = events
|
||||
.send(LifecycleEvent::Failed {
|
||||
attempt: input.attempt,
|
||||
reason: "HIP script approval was revoked".into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
// resources and approval remain owned until maintenance/logout and monitor
|
||||
// inspection are drained. Deliberate disconnect wins throughout cleanup.
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
gp_params::GpParams,
|
||||
service::{
|
||||
transport::ServiceResult,
|
||||
vpn_state::{ConnectInfo, VpnState},
|
||||
},
|
||||
session::{ClientAddresses, GatewayAuthentication, GatewaySession, GatewaySessions, transport::GatewayTransport},
|
||||
};
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Rsa,
|
||||
ssl::{SslAcceptor, SslMethod},
|
||||
x509::{X509, X509NameBuilder},
|
||||
};
|
||||
use tokio::sync::{oneshot, watch};
|
||||
|
||||
use super::{LifecycleEvent, PreparedConnection, VpnTask, test_connect_request};
|
||||
|
||||
fn tls_acceptor() -> SslAcceptor {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "localhost").unwrap();
|
||||
let name = name.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
cert.set_subject_name(&name).unwrap();
|
||||
cert.set_issuer_name(&name).unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
cert.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
acceptor.set_private_key(&key).unwrap();
|
||||
acceptor.set_certificate(&cert.build()).unwrap();
|
||||
acceptor.check_private_key().unwrap();
|
||||
acceptor.build()
|
||||
}
|
||||
|
||||
/// Exercise the real HTTPS logout transport without any production network,
|
||||
/// host collectors, or user identity files. The response gate proves admission
|
||||
/// stays owned until the server request finishes.
|
||||
#[tokio::test]
|
||||
async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let server_name = format!("https://{endpoint}");
|
||||
let mut gateway = serde_json::to_value(Gateway::new("fixture".into(), server_name.clone())).unwrap();
|
||||
gateway["kind"] = serde_json::json!("internal");
|
||||
let gateway: Gateway = serde_json::from_value(gateway).unwrap();
|
||||
let registry = Arc::new(crate::session_registry::SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session_id = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session_id, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(4);
|
||||
let control = crate::ws_connection::ConnectionControl::new(uuid::Uuid::new_v4(), tx).0;
|
||||
let connection_id = control.connection_id();
|
||||
registry.commit_attach(&permit, control).unwrap();
|
||||
let fixture = test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]));
|
||||
let mut member = fixture.plan().members()[0].clone();
|
||||
member.authentication =
|
||||
GatewayAuthentication::new("authcookie=fixture&user=fixture".into(), "internal".into()).unwrap();
|
||||
let plan = gpapi::session::ConnectionPlan::new(vec![member], vec![], fixture.plan().policy()).unwrap();
|
||||
let request = gpapi::service::request::ConnectRequest::new(fixture.info().clone(), plan);
|
||||
let mut prepared = PreparedConnection::lifecycle_fixture(request);
|
||||
let mut params = GpParams::builder(prepared.resources.profile.clone());
|
||||
params.ignore_tls_errors(true);
|
||||
prepared.sessions = GatewaySessions::new(vec![GatewaySession {
|
||||
gateway,
|
||||
transport: GatewayTransport::new(
|
||||
&server_name,
|
||||
prepared.request.plan().members()[0].authentication.clone(),
|
||||
¶ms.build(),
|
||||
prepared.request.plan().members()[0].binding.as_ref(),
|
||||
)
|
||||
.unwrap(),
|
||||
addresses: ClientAddresses::default(),
|
||||
}]);
|
||||
let acceptor = tls_acceptor();
|
||||
let (arrived, arrival) = oneshot::channel();
|
||||
let (release, response_gate) = oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = tokio::time::timeout(Duration::from_secs(3), listener.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let socket = socket.into_std().unwrap();
|
||||
socket.set_nonblocking(false).unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
socket.set_write_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let request = tokio::task::spawn_blocking(move || {
|
||||
let mut stream = acceptor.accept(socket).unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
let (headers_end, body_len) = loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
|
||||
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
key
|
||||
.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse::<usize>().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
break (position + 4, length);
|
||||
}
|
||||
};
|
||||
while bytes.len() < headers_end + body_len {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
arrived.send(()).unwrap();
|
||||
response_gate.blocking_recv().unwrap();
|
||||
let body = "<response status=\"success\"/>";
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
stream.flush().unwrap();
|
||||
String::from_utf8(bytes).unwrap()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// A single accepted authentication must produce a single logout.
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
request
|
||||
});
|
||||
let (state, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.commit_connection(session_id, 1, true, || reservation.commit(
|
||||
prepared,
|
||||
None,
|
||||
None,
|
||||
Some(session_id)
|
||||
)),
|
||||
ServiceResult::Accepted
|
||||
);
|
||||
let drain = registry
|
||||
.stop_non_tunnel_attachment(session_id, 1, connection_id)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let drain_waiter = tokio::spawn(async move {
|
||||
drain.wait().await;
|
||||
});
|
||||
let start = task.events.recv().await.unwrap();
|
||||
assert!(matches!(&start, LifecycleEvent::Start { .. }));
|
||||
task.handle_event(start).await;
|
||||
tokio::time::timeout(Duration::from_secs(3), arrival)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(lifecycle.has_attempt(0));
|
||||
assert!(!drain_waiter.is_finished());
|
||||
assert!(lifecycle.reserve_connect().is_err());
|
||||
assert!(!task.active.as_ref().unwrap().task.is_finished());
|
||||
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||
release.send(()).unwrap();
|
||||
while task.active.is_some() {
|
||||
let event = tokio::time::timeout(Duration::from_secs(3), task.events.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
task.handle_event(event).await;
|
||||
}
|
||||
assert!(!lifecycle.has_attempt(0));
|
||||
drain_waiter.await.unwrap();
|
||||
assert!(lifecycle.reserve_connect().is_ok());
|
||||
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||
let request = server.await.unwrap();
|
||||
assert!(request.starts_with("POST /ssl-vpn/logout.esp "));
|
||||
let form = request.split_once("\r\n\r\n").unwrap().1;
|
||||
let fields = url_form(form);
|
||||
assert_eq!(fields.get("user").map(String::as_str), Some("fixture"));
|
||||
assert_eq!(fields.get("computer").map(String::as_str), Some("fixture"));
|
||||
assert_eq!(fields.get("clientos").map(String::as_str), Some("Linux"));
|
||||
}
|
||||
|
||||
fn url_form(form: &str) -> std::collections::HashMap<String, String> {
|
||||
form
|
||||
.split('&')
|
||||
.map(|field| {
|
||||
let (key, value) = field.split_once('=').unwrap();
|
||||
(key.to_owned(), value.to_owned())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
use gpapi::{
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
process::collection::{CollectionBudget, CollectionControl},
|
||||
service::request::ConnectRequest,
|
||||
session::{GatewaySession, GatewaySessions, network::PhysicalNetwork, transport::GatewayTransport},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) struct PreparedConnection {
|
||||
pub(super) request: ConnectRequest,
|
||||
pub(super) resources: Arc<ConnectionResources>,
|
||||
pub(super) sessions: GatewaySessions,
|
||||
}
|
||||
|
||||
pub(super) struct ConnectionResources {
|
||||
pub profile: OsProfile,
|
||||
pub identity: Option<gpapi::utils::request::ClientIdentity>,
|
||||
pub identity_files: Option<gpapi::utils::request::ClientIdentityFiles>,
|
||||
pub network: Option<PhysicalNetwork>,
|
||||
}
|
||||
|
||||
/// Preparation sends no authenticated gateway requests. Rejection leaves the
|
||||
/// authentication owner responsible for logout; only queued admission transfers
|
||||
/// the complete ledger and its retained identity resources to the service.
|
||||
pub(crate) async fn prepare_connection(
|
||||
request: ConnectRequest,
|
||||
brokered_macos: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<PreparedConnection> {
|
||||
let args = request.args();
|
||||
let non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||
anyhow::ensure!(
|
||||
non_tunnel || request.plan().members().len() == 1,
|
||||
"Only one selected tunnel gateway can execute"
|
||||
);
|
||||
for member in request.plan().members() {
|
||||
if non_tunnel {
|
||||
let binding = member.binding.as_ref().context("Internal gateway binding is missing")?;
|
||||
anyhow::ensure!(
|
||||
!args.disable_ipv6() || (binding.endpoint().is_ipv4() && binding.addresses().ipv6.is_none()),
|
||||
"IPv6 gateway transport or identity is disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
let setup_request = request.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let resources = tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if setup_cancel.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Connection preparation cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
let args = setup_request.args();
|
||||
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
|
||||
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
|
||||
let identity_files = identity
|
||||
.as_ref()
|
||||
.map(|identity| identity.write_files(directory))
|
||||
.transpose()?;
|
||||
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||
let profile = crate::hip_source::profile(
|
||||
host,
|
||||
args.os().context("Authenticated client OS is missing")?,
|
||||
args.client_version(),
|
||||
args.os_version(),
|
||||
args.host_id(),
|
||||
args.local_hostname(),
|
||||
&check,
|
||||
)?;
|
||||
let network = if non_tunnel {
|
||||
Some(PhysicalNetwork::capture(&check)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
check()?;
|
||||
Ok::<_, anyhow::Error>(Arc::new(ConnectionResources {
|
||||
profile,
|
||||
identity,
|
||||
identity_files,
|
||||
network,
|
||||
}))
|
||||
})
|
||||
.await??;
|
||||
let args = request.args();
|
||||
let mut builder = GpParams::builder(resources.profile.clone());
|
||||
builder
|
||||
.ignore_tls_errors(args.ignore_tls_errors())
|
||||
.client_identity(resources.identity.clone());
|
||||
let params = builder.build();
|
||||
let mut sessions = Vec::new();
|
||||
for member in request.plan().members() {
|
||||
let binding = if non_tunnel {
|
||||
Some(member.binding.as_ref().context("Internal gateway binding is missing")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(network) = &resources.network {
|
||||
network
|
||||
.validate_internal_binding(
|
||||
binding.context("Internal gateway binding is missing")?,
|
||||
request.plan().internal_detection(),
|
||||
&cancellation,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let transport = GatewayTransport::new(member.gateway.server(), member.authentication.clone(), ¶ms, binding)?;
|
||||
sessions.push(GatewaySession {
|
||||
gateway: member.gateway.clone(),
|
||||
transport,
|
||||
addresses: binding.map(|binding| binding.addresses()).unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
if let Some(network) = &resources.network {
|
||||
network.ensure_current(&cancellation).await?;
|
||||
}
|
||||
Ok(PreparedConnection {
|
||||
request,
|
||||
resources,
|
||||
sessions: GatewaySessions::new(sessions),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl PreparedConnection {
|
||||
/// Lifecycle-only fixtures own no issued server sessions. Protocol ownership
|
||||
/// checks use actual gateway transports rather than this actor-state fixture.
|
||||
pub(crate) fn lifecycle_fixture(request: ConnectRequest) -> Self {
|
||||
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||
"fixture".into(),
|
||||
"fixture-host".into(),
|
||||
"fixture-serial".into(),
|
||||
"02:00:00:00:00:01".into(),
|
||||
))
|
||||
.build();
|
||||
Self {
|
||||
request,
|
||||
resources: Arc::new(ConnectionResources {
|
||||
profile,
|
||||
identity: None,
|
||||
identity_files: None,
|
||||
network: None,
|
||||
}),
|
||||
sessions: GatewaySessions::new(vec![]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
|
||||
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_certificate(Some("/identity.pem".into()));
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
if non_tunnel {
|
||||
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
}
|
||||
let request = serde_json::from_value(wire).unwrap();
|
||||
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.to_string(), "Client identity must be a protected snapshot");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_ipv6_rejects_ipv6_report_identity_before_setup() {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_disable_ipv6(true);
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["binding"]["addresses"]["ipv6"] = serde_json::json!("2001:db8::5");
|
||||
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||
// The fixture has no host identity or usable physical interface. Policy
|
||||
// rejection must happen before those collectors or transport setup run.
|
||||
let error = prepare_connection(request, false, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.to_string(), "IPv6 gateway transport or identity is disabled");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_preparation_needs_no_physical_binding_or_resolver() {
|
||||
let gateway = Gateway::new("fixture".into(), "does-not-resolve.invalid".into());
|
||||
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||
"fixture".into(),
|
||||
"fixture-host".into(),
|
||||
"fixture-serial".into(),
|
||||
"02:00:00:00:00:01".into(),
|
||||
))
|
||||
.build();
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_os_profile(&profile)
|
||||
.with_disable_ipv6(true);
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
wire["plan"]["members"][0]["binding"] = serde_json::Value::Null;
|
||||
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||
let prepared = prepare_connection(request, false, CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(prepared.resources.network.is_none());
|
||||
assert_eq!(prepared.sessions.members().len(), 1);
|
||||
assert!(prepared.sessions.members()[0].addresses.ipv4.is_none());
|
||||
assert!(prepared.sessions.members()[0].addresses.ipv6.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
process::collection::{CollectionBudget, CollectionControl},
|
||||
service::request::ConnectRequest,
|
||||
session::SessionMode,
|
||||
};
|
||||
use log::warn;
|
||||
use openconnect::Vpn;
|
||||
use tokio::{sync::mpsc, task::JoinHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{LifecycleEvent, LifecycleHandle, PreparedConnection, preparation::ConnectionResources};
|
||||
|
||||
pub(super) struct AttemptInput {
|
||||
pub attempt: u64,
|
||||
pub connection: PreparedConnection,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub session_id: Option<Uuid>,
|
||||
pub brokered_macos: bool,
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub lifecycle: LifecycleHandle,
|
||||
}
|
||||
|
||||
struct TunnelInput {
|
||||
request: ConnectRequest,
|
||||
resources: Arc<ConnectionResources>,
|
||||
source: Arc<openconnect::HipSource>,
|
||||
session_id: Option<Uuid>,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
}
|
||||
|
||||
struct PreparedTunnel {
|
||||
vpn: Arc<Vpn>,
|
||||
}
|
||||
|
||||
/// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers
|
||||
/// borrow that ledger; a native tunnel takes its cleanup ownership when started.
|
||||
/// Cancellation joins execution before draining any remaining issued sessions.
|
||||
pub(super) fn spawn(
|
||||
mut input: AttemptInput,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let attempt = input.attempt;
|
||||
let non_tunnel = input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||
let mut failure = None;
|
||||
let mut approval = None;
|
||||
if !cancellation.is_cancelled() {
|
||||
let request = input.connection.request.clone();
|
||||
let resources = input.connection.resources.clone();
|
||||
let desktop_uid = input.desktop_uid;
|
||||
let brokered = input.brokered_macos;
|
||||
let edited = input.edited_report.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let execution = tokio::task::spawn_blocking(move || {
|
||||
prepare_execution(request, resources, desktop_uid, brokered, edited, &setup_cancel)
|
||||
})
|
||||
.await;
|
||||
match execution {
|
||||
Ok(Ok(execution)) => {
|
||||
let (source, guard) = execution.into_parts();
|
||||
approval = Some(guard);
|
||||
let source = Arc::new(source);
|
||||
let guard = approval.as_ref().expect("execution approval is retained");
|
||||
if input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel)
|
||||
{
|
||||
match super::non_tunnel::run(&mut input, source, guard, cancellation.clone(), events.clone()).await {
|
||||
Ok(gpapi::session::non_tunnel::SessionExit::Disconnected) => {}
|
||||
Ok(gpapi::session::non_tunnel::SessionExit::Failed(reason)) => {
|
||||
let message = match reason {
|
||||
gpapi::session::SessionEndReason::InvalidCookie => {
|
||||
"Internal gateway authentication expired; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::NetworkChanged => {
|
||||
"Physical network changed or could not be verified; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::AllMembersFailed => {
|
||||
"All internal gateway sessions failed; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::AuthorizationRevoked => "HIP execution authorization was revoked",
|
||||
};
|
||||
failure = Some(message.into());
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Non-tunnel maintenance failed: {error:#}");
|
||||
failure = Some("Internal session maintenance failed".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let tunnel_input = TunnelInput {
|
||||
request: input.connection.request.clone(),
|
||||
resources: input.connection.resources.clone(),
|
||||
source,
|
||||
session_id: input.session_id,
|
||||
registry: input.registry.clone(),
|
||||
};
|
||||
let setup_cancel = cancellation.clone();
|
||||
let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await;
|
||||
match prepared {
|
||||
Ok(Ok(prepared)) => {
|
||||
run_tunnel(
|
||||
attempt,
|
||||
&prepared,
|
||||
guard,
|
||||
&input.lifecycle,
|
||||
&mut input.connection.sessions,
|
||||
cancellation.clone(),
|
||||
events.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
Ok(Err(error)) => warn!("Failed to prepare tunnel: {error:#}"),
|
||||
Err(error) => warn!("Tunnel setup worker failed: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
warn!("Failed to prepare HIP execution: {error:#}");
|
||||
failure = Some("HIP execution could not be prepared".into());
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("HIP setup worker failed: {error}");
|
||||
failure = Some("HIP setup worker failed".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
input.connection.sessions.logout().await;
|
||||
// Identity and approval remain alive through worker drain and logout. Ended
|
||||
// only releases admission after the actor also joins this task.
|
||||
drop(approval);
|
||||
if non_tunnel && !cancellation.is_cancelled() {
|
||||
if let Some(reason) = failure {
|
||||
let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await;
|
||||
}
|
||||
}
|
||||
let _ = events.send(LifecycleEvent::Ended { attempt }).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn prepare_execution(
|
||||
request: ConnectRequest,
|
||||
resources: Arc<ConnectionResources>,
|
||||
desktop_uid: Option<u32>,
|
||||
brokered: bool,
|
||||
edited: Option<Arc<str>>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<crate::hip_source::HipExecution> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"HIP setup cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
let args = request.args();
|
||||
let pure_non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||
let disabled = pure_non_tunnel && !request.plan().policy().collect_hip_data();
|
||||
let source = if disabled {
|
||||
&gpapi::hip::HipSource::Disabled
|
||||
} else {
|
||||
args.hip_source()
|
||||
};
|
||||
let execution = crate::hip_source::resolve(source, desktop_uid, brokered, edited, Some(resources.profile.clone()))?;
|
||||
check()?;
|
||||
Ok(execution)
|
||||
}
|
||||
|
||||
fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyhow::Result<PreparedTunnel> {
|
||||
let args = input.request.args();
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Tunnel setup cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
ensure!(
|
||||
input.request.plan().members().len() == 1
|
||||
&& input.request.plan().members()[0].authentication.mode() == SessionMode::Tunnel,
|
||||
"Tunnel execution requires one selected tunnel gateway"
|
||||
);
|
||||
let member = &input.request.plan().members()[0];
|
||||
let identity_files = &input.resources.identity_files;
|
||||
let vpn = Arc::new(
|
||||
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?
|
||||
.user_agent(args.user_agent())
|
||||
.os(args.openconnect_os())
|
||||
.os_version(args.os_version())
|
||||
.client_version(args.client_version())
|
||||
.host_id(args.host_id())
|
||||
.certificate(identity_files.as_ref().map(|files| files.certificate().to_owned()))
|
||||
.sslkey(identity_files.as_ref().and_then(|files| files.key()).map(str::to_owned))
|
||||
.key_password(
|
||||
input
|
||||
.resources
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.key_password())
|
||||
.map(str::to_owned),
|
||||
)
|
||||
.hip_source(input.source)
|
||||
.reconnect_timeout(args.reconnect_timeout())
|
||||
.mtu(args.mtu())
|
||||
.disable_ipv6(args.disable_ipv6())
|
||||
.no_dtls(args.no_dtls())
|
||||
.local_hostname(args.local_hostname())
|
||||
.dpd_interval(args.force_dpd())
|
||||
.no_xmlpost(args.no_xmlpost())
|
||||
.build()
|
||||
.context("Failed to create tunnel worker")?,
|
||||
);
|
||||
check()?;
|
||||
if let Some(session_id) = input.session_id {
|
||||
let registry = input.registry;
|
||||
vpn.set_hip_report_callback(move |xml| {
|
||||
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||
warn!("Could not retain submitted HIP report: {error}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(PreparedTunnel { vpn })
|
||||
}
|
||||
|
||||
async fn run_tunnel(
|
||||
attempt: u64,
|
||||
prepared: &PreparedTunnel,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
lifecycle: &LifecycleHandle,
|
||||
sessions: &mut gpapi::session::GatewaySessions,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) {
|
||||
if cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let vpn = prepared.vpn.clone();
|
||||
// The native tunnel keeps its reconnect endpoint and cookie current and owns
|
||||
// normal logout. The ledger remains responsible only before native execution.
|
||||
// Service admission permits exactly one tunnel member.
|
||||
std::mem::take(sessions).relinquish();
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
vpn.connect(move |session| {
|
||||
let _ = events.blocking_send(LifecycleEvent::Established { attempt, session });
|
||||
})
|
||||
});
|
||||
tokio::pin!(worker);
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => { prepared.vpn.disconnect(); break (&mut worker).await; },
|
||||
result = &mut worker => break result,
|
||||
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||
stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
prepared.vpn.disconnect();
|
||||
break (&mut worker).await;
|
||||
},
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(0 | -4) => {}
|
||||
Ok(code) => warn!("Tunnel worker exited with status {code}"),
|
||||
Err(error) => warn!("Tunnel worker failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stop_for_revoked_approval(lifecycle: &LifecycleHandle, cancellation: &CancellationToken) {
|
||||
let result = lifecycle.request_disconnect();
|
||||
if !matches!(result, gpapi::service::transport::ServiceResult::Accepted) {
|
||||
warn!("Could not enqueue approval revocation stop: {result:?}");
|
||||
}
|
||||
cancellation.cancel();
|
||||
}
|
||||
@@ -58,11 +58,11 @@ impl ConnectionControl {
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.tx.is_closed()
|
||||
self.tx.is_closed() || self.close_tx.borrow().is_some()
|
||||
}
|
||||
|
||||
pub fn close(&self, reason: CloseReason) {
|
||||
let _ = self.close_tx.send(Some(reason));
|
||||
self.close_tx.send_replace(Some(reason));
|
||||
}
|
||||
|
||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||
@@ -187,6 +187,10 @@ impl WsConnection {
|
||||
ctx
|
||||
.remove_connection(control.connection_id(), permit.session_id, generation)
|
||||
.await;
|
||||
ctx
|
||||
.hip_previews
|
||||
.cancel_connection(permit.session_id, control.connection_id())
|
||||
.await;
|
||||
info!("GUI connection {} closed", control.connection_id());
|
||||
}
|
||||
}
|
||||
@@ -459,70 +463,41 @@ async fn handle_client_message(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let registry = Arc::clone(ctx.registry());
|
||||
let control = control.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = match crate::hip_preview::generate(preview, edited_report, desktop_uid).await {
|
||||
Ok(xml) => match registry.store_hip_preview(session_id, xml) {
|
||||
Ok(preview_id) => match registry.hip_preview_chunk(session_id, preview_id, 0) {
|
||||
Ok((xml, complete)) => ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"),
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"),
|
||||
},
|
||||
Err(error) => {
|
||||
warn!("HIP preview failed: {error:#}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
};
|
||||
control.send_reply(id, result).await;
|
||||
});
|
||||
if !ctx
|
||||
.hip_previews
|
||||
.start(crate::hip_preview::PreviewJob {
|
||||
session_id,
|
||||
request_id: id,
|
||||
request: preview,
|
||||
edited_report,
|
||||
desktop_uid,
|
||||
identity: ctx.host_identity().await,
|
||||
registry: Arc::clone(ctx.registry()),
|
||||
connection: control.clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::Busy, "HIP preview is already running"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let edited_report = if let WsRequest::Connect(connect) = &request {
|
||||
if let HipSource::Edited { report_id } = connect.args().hip_source() {
|
||||
let report_id = match Uuid::parse_str(report_id) {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
match ctx.registry().edited_hip_report(session_id, report_id) {
|
||||
Ok(report) => Some(report),
|
||||
Err(_) => {
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"HIP report is unavailable for this session",
|
||||
),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let dispatcher = ctx.dispatcher();
|
||||
let request = match dispatcher.dispatch_lifecycle(request, desktop_uid, edited_report, Some(session_id)) {
|
||||
let request = match dispatcher.dispatch_lifecycle(
|
||||
request,
|
||||
desktop_uid,
|
||||
None,
|
||||
Some(crate::request_dispatcher::SessionAuthority {
|
||||
registry: Arc::clone(ctx.registry()),
|
||||
session_id,
|
||||
generation,
|
||||
}),
|
||||
) {
|
||||
Ok(request) => request,
|
||||
Err(result) => {
|
||||
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
||||
@@ -534,7 +509,7 @@ async fn handle_client_message(
|
||||
};
|
||||
let control = control.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = dispatcher.dispatch(request).await;
|
||||
let result = dispatcher.dispatch_pending(request).await;
|
||||
control.send_reply(id, result).await;
|
||||
});
|
||||
Ok(())
|
||||
@@ -614,7 +589,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticates_attaches_and_replies_to_a_request() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
|
||||
@@ -39,6 +39,7 @@ pub(crate) struct WsServerContext {
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
state: Mutex<ServiceState>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
||||
}
|
||||
|
||||
impl WsServerContext {
|
||||
@@ -58,6 +59,7 @@ impl WsServerContext {
|
||||
connections: HashMap::new(),
|
||||
}),
|
||||
handshake_slots: Arc::new(Semaphore::new(16)),
|
||||
hip_previews: crate::hip_preview::HipPreviews::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +67,10 @@ impl WsServerContext {
|
||||
self.product_version
|
||||
}
|
||||
|
||||
pub async fn host_identity(&self) -> HostIdentity {
|
||||
self.state.lock().await.snapshot.host_info.host_identity.clone()
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Arc<SessionRegistry> {
|
||||
&self.registry
|
||||
}
|
||||
@@ -145,8 +151,8 @@ impl WsServerContext {
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: WsEvent) {
|
||||
@@ -243,6 +249,7 @@ impl WsServer {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
self.ctx.hip_previews.shutdown().await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
@@ -258,7 +265,7 @@ impl WsServer {
|
||||
fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
VpnEnv {
|
||||
vpn_state,
|
||||
vpnc_script: find_vpnc_script().map(ToOwned::to_owned),
|
||||
vpnc_script: find_vpnc_script(),
|
||||
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
@@ -280,7 +287,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn resync_snapshot_is_ordered_with_state_events() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(
|
||||
@@ -337,7 +344,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let registry = Arc::new(SessionRegistry::for_tests(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
|
||||
@@ -1,5 +1,52 @@
|
||||
# Changelog
|
||||
|
||||
## 3.0.2
|
||||
|
||||
### Added
|
||||
|
||||
- Added `gpclient diagnostics` to collect system and client information for troubleshooting.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Recognized WebKit Wayland rendering crashes now trigger one retry with DMABUF disabled when opening the GUI, first-time setup, or embedded browser sign-in.
|
||||
- Improved desktop rendering with opaque windows to reduce transparency-related flickering on Linux and BSD.
|
||||
- Browser sign-in retries refresh authentication data, and repeated failures report both attempts instead of leaving the client waiting.
|
||||
- Cancelling startup or sign-in now stops pending desktop child processes and version checks.
|
||||
|
||||
## 3.0.1
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed the bundled macOS CLI when launched through Homebrew.
|
||||
- Fixed browser sign-in failures leaving the CLI waiting without an error.
|
||||
- Fixed first-time startup on Linux and BSD when no system keyring is available.
|
||||
- Improved tray menu behavior on Linux and BSD.
|
||||
- Added clearer results when manually checking for updates.
|
||||
- Improved desktop dialogs, settings, keyboard focus, and Linux window controls.
|
||||
|
||||
## 3.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- GP Connect for Apple silicon Macs running macOS 13 or later.
|
||||
- Support for internal gateways that authenticate your device without creating a VPN tunnel.
|
||||
- More control over device compliance reports (HIP), including generated reports and custom scripts.
|
||||
- Desktop update notifications, with in-app updates on macOS and links to new releases on Linux and BSD.
|
||||
- JSON log output for CLI integrations and automation.
|
||||
|
||||
### Changed
|
||||
|
||||
- Refreshed the desktop connection view, gateway selection, and session details.
|
||||
- Improved browser sign-in, including opening your normal user's browser when the CLI runs with elevated privileges.
|
||||
- Improved session expiry warnings and session extension when allowed by your VPN administrator.
|
||||
- Updated license activation and recovery. Start the seven-day desktop trial by verifying your email address in the app.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Improved cancellation, disconnect, and cached sign-in handling.
|
||||
- Improved desktop window and tray behavior across macOS, Linux, FreeBSD, and OpenBSD.
|
||||
- Improved package installation and desktop integration on Linux and BSD.
|
||||
|
||||
## 2.6.5
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{UnixListener, UnixStream},
|
||||
@@ -27,6 +27,7 @@ const PROTOCOL_VERSION: u8 = 1;
|
||||
const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
// Acceptance acknowledges delivery, including an authentication failure.
|
||||
const STATUS_ACCEPTED: u8 = 0;
|
||||
const STATUS_INVALID_CALLBACK: u8 = 1;
|
||||
const STATUS_UNSUPPORTED_VERSION: u8 = 2;
|
||||
@@ -70,6 +71,10 @@ impl AuthCallbackReceiver {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
return Ok(auth_data);
|
||||
}
|
||||
Err(error @ AuthDataParseError::AuthenticationFailed(_)) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
return Err(error.into());
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
}
|
||||
@@ -419,6 +424,24 @@ mod tests {
|
||||
assert!(!socket_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reports_authentication_failure_to_waiting_receiver() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
let failure = gpapi::utils::base64::encode(b"<html><saml-auth-status>0</saml-auth-status></html>");
|
||||
let callback = format!("globalprotectcallback:{failure}");
|
||||
let sender = tokio::spawn(async move { forward_auth_callback_to(&callback, &socket_path).await });
|
||||
|
||||
let error = timeout(Duration::from_millis(500), receiver.receive())
|
||||
.await
|
||||
.expect("Failure callback must finish the waiting authentication")
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("Authentication failed"));
|
||||
sender.await.unwrap().expect("Failure callback was delivered");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_bad_requests_and_keeps_waiting() {
|
||||
let directory = tempdir().unwrap();
|
||||
@@ -430,6 +453,10 @@ mod tests {
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION, "https://example.com").await,
|
||||
STATUS_INVALID_CALLBACK
|
||||
);
|
||||
assert_eq!(
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION, "globalprotectcallback:not-base64").await,
|
||||
STATUS_INVALID_CALLBACK
|
||||
);
|
||||
assert_eq!(
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION + 1, VALID_CALLBACK).await,
|
||||
STATUS_UNSUPPORTED_VERSION
|
||||
|
||||
@@ -150,8 +150,8 @@ impl AuthMessenger {
|
||||
|
||||
match auth_result {
|
||||
Ok(data) => self.send_auth_data(data, AuthDataLocation::Body),
|
||||
Err(AuthDataParseError::Invalid(err)) => self.send_auth_error(AuthError::invalid_from_body(err)),
|
||||
Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()),
|
||||
Err(err) => self.send_auth_error(AuthError::invalid_from_body(err.into())),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use std::process::{Command, Stdio};
|
||||
use std::{
|
||||
os::unix::process::CommandExt,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use log::{debug, info, warn};
|
||||
@@ -139,6 +142,7 @@ fn open_with_launcher(url: &str, launcher: &BrowserLauncher) -> anyhow::Result<(
|
||||
info!("Launching Flatpak browser: {app_id}");
|
||||
Command::new(executable)
|
||||
.args(["run", app_id, url])
|
||||
.process_group(0)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
|
||||
@@ -6,3 +6,6 @@ authors.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -3,6 +3,9 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
#[cfg(all(
|
||||
not(debug_assertions),
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
|
||||
@@ -33,10 +36,11 @@ pub fn gp_vpnc_script_installer() -> PathBuf {
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn gp_hip_script_installer() -> PathBuf {
|
||||
env::var_os("GP_HIP_SCRIPT_INSTALLER_BINARY")
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(GP_HIP_SCRIPT_INSTALLER_BINARY))
|
||||
resolve(
|
||||
"GP_HIP_SCRIPT_INSTALLER_BINARY",
|
||||
"gp-hip-script-installer",
|
||||
GP_HIP_SCRIPT_INSTALLER_BINARY,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gpauth() -> PathBuf {
|
||||
@@ -79,10 +83,34 @@ fn resolve(env_key: &str, binary_name: &str, default_path: &str) -> PathBuf {
|
||||
|
||||
fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
|
||||
let current_exe = env::current_exe().ok()?;
|
||||
let bin_dir = current_exe.parent()?;
|
||||
let binary = bin_dir.join(binary_name);
|
||||
sibling_binary_for_executable(¤t_exe, binary_name)
|
||||
}
|
||||
|
||||
is_file(&binary).then_some(binary)
|
||||
fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||
let executable = executable.canonicalize().ok()?;
|
||||
let bin_dir = executable.parent()?;
|
||||
let binary = bin_dir.join(binary_name);
|
||||
if is_file(&binary) {
|
||||
return Some(binary);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(binary) = macos::helper_path(&executable, binary_name)
|
||||
&& is_file(&binary)
|
||||
{
|
||||
return Some(binary);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn bundled_vpnc_script() -> Option<PathBuf> {
|
||||
bundled_vpnc_script_for_executable(&env::current_exe().ok()?)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn bundled_vpnc_script_for_executable(executable: &Path) -> Option<PathBuf> {
|
||||
let executable = executable.canonicalize().ok()?;
|
||||
macos::vpnc_script_path(&executable)
|
||||
}
|
||||
|
||||
fn is_file(path: &Path) -> bool {
|
||||
@@ -93,6 +121,50 @@ fn is_file(path: &Path) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn desktop_resolves_helpers_in_the_actual_app_bundle_layout() {
|
||||
assert_eq!(
|
||||
macos::helper_path(
|
||||
Path::new("/Applications/GP Connect.app/Contents/MacOS/gpgui"),
|
||||
"gpclient"
|
||||
),
|
||||
Some(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers/gpclient"))
|
||||
);
|
||||
assert!(macos::helper_path(Path::new("/usr/local/bin/gpgui"), "gpclient").is_none());
|
||||
assert!(macos::helper_path(Path::new("/tmp/Contents/MacOS/gpgui"), "gpclient").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn symlinked_executable_resolves_its_bundle_paths() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let helpers = directory.path().join("GP Connect.app/Contents/Helpers");
|
||||
let bin = directory.path().join("bin");
|
||||
std::fs::create_dir_all(&helpers).unwrap();
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(helpers.join("gpclient"), "").unwrap();
|
||||
std::fs::write(helpers.join("gpauth"), "").unwrap();
|
||||
std::os::unix::fs::symlink(helpers.join("gpclient"), bin.join("gpclient")).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
sibling_binary_for_executable(&bin.join("gpclient"), "gpauth"),
|
||||
Some(helpers.canonicalize().unwrap().join("gpauth"))
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
assert_eq!(
|
||||
bundled_vpnc_script_for_executable(&bin.join("gpclient")),
|
||||
Some(
|
||||
helpers
|
||||
.canonicalize()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("Resources/Scripts/vpnc-script")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_path_is_used_when_no_sibling_exists() {
|
||||
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn contents_dir(executable: &Path) -> Option<&Path> {
|
||||
let bin_dir = executable.parent()?;
|
||||
let contents = bin_dir.parent()?;
|
||||
let bundle = contents.parent()?;
|
||||
let directory_name = bin_dir.file_name()?;
|
||||
if (directory_name != "MacOS" && directory_name != "Helpers")
|
||||
|| contents.file_name()? != "Contents"
|
||||
|| bundle.extension()? != "app"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(contents)
|
||||
}
|
||||
|
||||
pub(super) fn helper_path(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||
Some(contents_dir(executable)?.join("Helpers").join(binary_name))
|
||||
}
|
||||
|
||||
pub(super) fn vpnc_script_path(executable: &Path) -> Option<PathBuf> {
|
||||
Some(contents_dir(executable)?.join("Resources/Scripts/vpnc-script"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bundle_entry_points_use_their_own_vpnc_script() {
|
||||
for executable in [
|
||||
"/Applications/GP Connect.app/Contents/Helpers/gpclient",
|
||||
"/Applications/GP Connect.app/Contents/MacOS/gpgui",
|
||||
] {
|
||||
assert_eq!(
|
||||
vpnc_script_path(Path::new(executable)),
|
||||
Some(PathBuf::from(
|
||||
"/Applications/GP Connect.app/Contents/Resources/Scripts/vpnc-script"
|
||||
))
|
||||
);
|
||||
}
|
||||
assert!(vpnc_script_path(Path::new("/opt/homebrew/bin/gpclient")).is_none());
|
||||
assert!(vpnc_script_path(Path::new("/tmp/Contents/Helpers/gpclient")).is_none());
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"] }
|
||||
common = { path = "../common" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
@@ -17,9 +18,10 @@ version-compare = "0.2"
|
||||
pem.workspace = true
|
||||
xmltree.workspace = true
|
||||
serde.workspace = true
|
||||
specta = { workspace = true, features = ["derive"] }
|
||||
specta = { workspace = true, features = ["derive", "uuid"] }
|
||||
urlencoding.workspace = true
|
||||
tokio = { workspace = true, features = ["process", "signal", "macros"] }
|
||||
tokio-util.workspace = true
|
||||
serde_json.workspace = true
|
||||
whoami.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -36,6 +38,7 @@ uuid = { workspace = true, features = ["v4", "v5", "serde"] }
|
||||
chrono.workspace = true
|
||||
humantime.workspace = true
|
||||
netdev.workspace = true
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
os_info = { version = "3", default-features = false }
|
||||
snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
@@ -58,6 +61,7 @@ gtk = { version = "0.18", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[features]
|
||||
tauri = ["dep:tauri", "dep:gtk"]
|
||||
|
||||
@@ -130,10 +130,7 @@ impl SamlAuthData {
|
||||
|
||||
Ok(auth_data)
|
||||
}
|
||||
Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!(
|
||||
"SAML auth status: {}",
|
||||
status
|
||||
))),
|
||||
Some(status) => Err(AuthDataParseError::AuthenticationFailed(status)),
|
||||
None => Err(AuthDataParseError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,12 +29,17 @@ impl PortalError {
|
||||
pub enum AuthDataParseError {
|
||||
#[error("No auth data found")]
|
||||
NotFound,
|
||||
#[error("Authentication failed (SAML status: {0})")]
|
||||
AuthenticationFailed(String),
|
||||
#[error(transparent)]
|
||||
Invalid(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl AuthDataParseError {
|
||||
pub fn is_invalid(&self) -> bool {
|
||||
matches!(self, AuthDataParseError::Invalid(_))
|
||||
matches!(
|
||||
self,
|
||||
AuthDataParseError::Invalid(_) | AuthDataParseError::AuthenticationFailed(_)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
use std::{borrow::Cow, net::UdpSocket};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
net::{SocketAddr, UdpSocket},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::Client;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use urlencoding::{decode, encode};
|
||||
use xmltree::Element;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{
|
||||
credential::Credential,
|
||||
@@ -12,68 +17,238 @@ use crate::{
|
||||
gateway::GatewayLoginContext,
|
||||
gp_params::GpParams,
|
||||
params::gateway_login::{self, GatewayLoginInput},
|
||||
session::{
|
||||
GatewayAuthentication,
|
||||
network::GatewayBinding,
|
||||
transport::{bound_client, gateway_origin},
|
||||
},
|
||||
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
pub enum GatewayLogin {
|
||||
Cookie(String),
|
||||
Authenticated(GatewayAuthentication),
|
||||
Mfa(String, String),
|
||||
}
|
||||
|
||||
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, None, false).await
|
||||
/// Protocol failures cannot be repaired by repeating login with different
|
||||
/// credentials. Issued credentials, when identifiable, are cleaned up first.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Gateway login returned invalid session configuration")]
|
||||
pub struct GatewayLoginProtocolError;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GatewayLoginClient {
|
||||
origin: reqwest::Url,
|
||||
client: Client,
|
||||
params: GpParams,
|
||||
binding: Option<GatewayBinding>,
|
||||
login_endpoint: Option<SocketAddr>,
|
||||
login_url: Option<reqwest::Url>,
|
||||
maintenance_client: Option<Client>,
|
||||
}
|
||||
|
||||
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
|
||||
impl GatewayLoginClient {
|
||||
pub fn register_session(
|
||||
&self,
|
||||
gateway: crate::gateway::Gateway,
|
||||
authentication: GatewayAuthentication,
|
||||
sessions: &mut crate::session::GatewaySessions,
|
||||
) {
|
||||
sessions.register(crate::session::GatewaySession {
|
||||
gateway,
|
||||
transport: self.authenticated_transport(authentication),
|
||||
addresses: self
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.addresses())
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
pub fn new(gateway: &str, params: GpParams) -> anyhow::Result<Self> {
|
||||
let origin = reqwest::Url::parse(&normalize_server(gateway)?)?;
|
||||
let client = Client::try_from(¶ms)?;
|
||||
Ok(Self {
|
||||
origin,
|
||||
client,
|
||||
params,
|
||||
binding: None,
|
||||
login_endpoint: None,
|
||||
login_url: None,
|
||||
maintenance_client: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Only called after an authenticated non-tunnel response and registration in
|
||||
/// the caller's cleanup ledger. Tunnel login never inspects physical routing.
|
||||
pub async fn bind_non_tunnel(
|
||||
&mut self,
|
||||
disable_ipv6: bool,
|
||||
detection: Option<&crate::session::network::InternalHostDetection>,
|
||||
cancellation: &tokio_util::sync::CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
let origin = gateway_origin(self.origin.as_str())?;
|
||||
let response_url = self
|
||||
.login_url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?;
|
||||
anyhow::ensure!(
|
||||
response_url.origin() == origin.origin(),
|
||||
"Redirected non-tunnel authentication is unsupported"
|
||||
);
|
||||
let endpoint = self
|
||||
.login_endpoint
|
||||
.ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?;
|
||||
let network = crate::session::network::PhysicalNetwork::capture_controlled(cancellation).await?;
|
||||
let binding = network
|
||||
.bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation)
|
||||
.await?;
|
||||
network
|
||||
.validate_internal_binding(&binding, detection, cancellation)
|
||||
.await?;
|
||||
let client = bound_client(origin.as_str(), &self.params, &binding)?;
|
||||
self.binding = Some(binding);
|
||||
self.maintenance_client = Some(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_registered_session(
|
||||
&self,
|
||||
gateway: &crate::gateway::Gateway,
|
||||
authentication: &GatewayAuthentication,
|
||||
sessions: &mut crate::session::GatewaySessions,
|
||||
) {
|
||||
sessions.update(crate::session::GatewaySession {
|
||||
gateway: gateway.clone(),
|
||||
transport: self.authenticated_transport(authentication.clone()),
|
||||
addresses: self
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.addresses())
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn authenticated_transport(
|
||||
&self,
|
||||
authentication: GatewayAuthentication,
|
||||
) -> crate::session::transport::GatewayTransport {
|
||||
crate::session::transport::GatewayTransport::from_authenticated_login(
|
||||
self.maintenance_client.as_ref().unwrap_or(&self.client).clone(),
|
||||
self.origin.clone(),
|
||||
authentication,
|
||||
self.params.os_profile().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn binding(&self) -> Option<&GatewayBinding> {
|
||||
self.binding.as_ref()
|
||||
}
|
||||
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
|
||||
self.params.client_identity()
|
||||
}
|
||||
pub(crate) fn request_client(&self) -> &Client {
|
||||
&self.client
|
||||
}
|
||||
pub(crate) fn origin(&self) -> &reqwest::Url {
|
||||
&self.origin
|
||||
}
|
||||
|
||||
pub fn respond_mfa(&mut self, input: &str, otp: &str) {
|
||||
self.params.set_input_str(input);
|
||||
self.params.set_otp(otp);
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
&mut self,
|
||||
cred: &Credential,
|
||||
context: Option<&GatewayLoginContext>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
let client_ip = context.and_then(|context| {
|
||||
context
|
||||
.client_ip()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| detect_local_ipv4(context.host()))
|
||||
});
|
||||
let request = receive_gateway_login(
|
||||
&self.origin,
|
||||
&self.client,
|
||||
cred,
|
||||
&self.params,
|
||||
context,
|
||||
client_ip.as_deref(),
|
||||
false,
|
||||
);
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
response = request => response?,
|
||||
_ = cancellation.cancelled() => return Err(crate::auth::AuthenticationCancelled.into()),
|
||||
};
|
||||
// Once the full response is available, retain issued authentication or finish
|
||||
// cleanup-only logout before the caller observes cancellation.
|
||||
let response = parse_login_response(response, &self.client, &self.origin, &self.params).await?;
|
||||
self.login_endpoint = response.endpoint;
|
||||
self.login_url = Some(response.url);
|
||||
Ok(response.login)
|
||||
}
|
||||
|
||||
pub(crate) async fn extend_lifetime(&self, cred: &Credential) -> anyhow::Result<GatewayLogin> {
|
||||
let response = receive_gateway_login(&self.origin, &self.client, cred, &self.params, None, None, true).await?;
|
||||
Ok(
|
||||
parse_login_response(response, &self.client, &self.origin, &self.params)
|
||||
.await?
|
||||
.login,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn gateway_login_with_extend_lifetime(
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, None, true).await
|
||||
struct LoginResponse {
|
||||
login: GatewayLogin,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
}
|
||||
|
||||
async fn gateway_login_with_options(
|
||||
gateway: &str,
|
||||
struct ReceivedLogin {
|
||||
body: String,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
async fn receive_gateway_login(
|
||||
origin: &reqwest::Url,
|
||||
client: &Client,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
context: Option<&GatewayLoginContext>,
|
||||
client_ip: Option<&str>,
|
||||
extend_lifetime: bool,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
let url = normalize_server(gateway)?;
|
||||
let gateway = remove_url_scheme(&url);
|
||||
|
||||
let login_url = format!("{}/ssl-vpn/login.esp", url);
|
||||
let client = Client::try_from(gp_params)?;
|
||||
|
||||
let client_ip = context.and_then(|context| {
|
||||
context
|
||||
.client_ip()
|
||||
.map(|ip| ip.to_string())
|
||||
.or_else(|| detect_local_ipv4(context.host()))
|
||||
});
|
||||
) -> anyhow::Result<ReceivedLogin> {
|
||||
let gateway = remove_url_scheme(origin.as_str().trim_end_matches('/'));
|
||||
let login_url = format!("{}/ssl-vpn/login.esp", origin.as_str().trim_end_matches('/'));
|
||||
let request_params = gateway_login::build(&GatewayLoginInput {
|
||||
gp_params,
|
||||
cred,
|
||||
gateway_host: &gateway,
|
||||
context,
|
||||
client_ip: client_ip.as_deref(),
|
||||
client_ip,
|
||||
extend_lifetime,
|
||||
});
|
||||
|
||||
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
|
||||
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
|
||||
log_gateway_login_context(context, client_ip, gp_params);
|
||||
|
||||
let res = client
|
||||
.post(&login_url)
|
||||
.post(login_url)
|
||||
.form(&request_params.body)
|
||||
.send()
|
||||
.await
|
||||
@@ -82,11 +257,32 @@ async fn gateway_login_with_options(
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
|
||||
let endpoint = res.remote_addr();
|
||||
let url = res.url().clone();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
warn!("{err}");
|
||||
warn!("Gateway login response failed: {}", err.reason);
|
||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||
})?;
|
||||
|
||||
Ok(ReceivedLogin {
|
||||
body: res,
|
||||
endpoint,
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
||||
async fn parse_login_response(
|
||||
response: ReceivedLogin,
|
||||
client: &Client,
|
||||
origin: &reqwest::Url,
|
||||
gp_params: &GpParams,
|
||||
) -> anyhow::Result<LoginResponse> {
|
||||
let ReceivedLogin {
|
||||
body: res,
|
||||
endpoint,
|
||||
url,
|
||||
} = response;
|
||||
|
||||
// It's possible to get an empty response, log the response headers for debugging
|
||||
if res.trim().is_empty() {
|
||||
info!("Empty gateway login response headers: {:?}", res);
|
||||
@@ -96,27 +292,47 @@ async fn gateway_login_with_options(
|
||||
// MFA detected
|
||||
if res.contains("Challenge") {
|
||||
let Some((message, input_str)) = parse_mfa(&res) else {
|
||||
bail!("Failed to parse MFA challenge: {res}");
|
||||
bail!("Failed to parse MFA challenge");
|
||||
};
|
||||
|
||||
return Ok(GatewayLogin::Mfa(message, input_str));
|
||||
return Ok(LoginResponse {
|
||||
login: GatewayLogin::Mfa(message, input_str),
|
||||
endpoint,
|
||||
url,
|
||||
});
|
||||
}
|
||||
|
||||
debug!("Gateway login response: {}", res);
|
||||
|
||||
let root = Element::parse(res.as_bytes())?;
|
||||
|
||||
let cookie = build_gateway_token(&root, gp_params.computer())?;
|
||||
|
||||
Ok(GatewayLogin::Cookie(cookie))
|
||||
}
|
||||
|
||||
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 }
|
||||
let lower = res.to_ascii_lowercase();
|
||||
if lower.contains("<!doctype") || lower.contains("<!entity") {
|
||||
return Err(GatewayLoginProtocolError.into());
|
||||
}
|
||||
let root = Element::parse(res.as_bytes()).map_err(|_| GatewayLoginProtocolError)?;
|
||||
let (cookie, connection_type) =
|
||||
parse_issued_authentication(&root, gp_params.computer()).map_err(|_| GatewayLoginProtocolError)?;
|
||||
let cookie = Zeroizing::new(cookie);
|
||||
let authentication = connection_type.and_then(|mode| GatewayAuthentication::new(cookie.to_string(), mode));
|
||||
let authentication = match authentication {
|
||||
Ok(authentication) => authentication,
|
||||
Err(_) => {
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
crate::session::transport::logout_cookie(client, origin, &cookie, gp_params.os_profile()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => warn!("Cleanup-only gateway logout failed: {error}"),
|
||||
Err(_) => warn!("Cleanup-only gateway logout timed out"),
|
||||
}
|
||||
return Err(GatewayLoginProtocolError.into());
|
||||
}
|
||||
};
|
||||
debug!("Gateway login succeeded, mode: {:?}", authentication.mode());
|
||||
Ok(LoginResponse {
|
||||
login: GatewayLogin::Authenticated(authentication),
|
||||
endpoint,
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
||||
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
|
||||
@@ -136,13 +352,33 @@ fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: O
|
||||
);
|
||||
}
|
||||
|
||||
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
|
||||
let args = element
|
||||
.descendants("argument")
|
||||
fn parse_issued_authentication(element: &Element, computer: &str) -> anyhow::Result<(String, anyhow::Result<String>)> {
|
||||
anyhow::ensure!(element.name == "jnlp", "Gateway login response is not JNLP");
|
||||
anyhow::ensure!(
|
||||
element.attr("status").is_none_or(|status| status == "success"),
|
||||
"Gateway login response rejected authentication"
|
||||
);
|
||||
let application = element
|
||||
.child("application-desc")
|
||||
.ok_or_else(|| anyhow::anyhow!("Gateway login response has no application description"))?;
|
||||
let args = application
|
||||
.children("argument")
|
||||
.iter()
|
||||
.map(|e| e.get_text().unwrap_or_default())
|
||||
.collect::<Vec<_>>();
|
||||
let cookie = build_gateway_token(&args, computer)?;
|
||||
let connection_type = read_arg_value(&args, 12)
|
||||
.and_then(|mode| mode.ok_or_else(|| anyhow::anyhow!("Gateway login response has no connection type")));
|
||||
Ok((cookie, connection_type))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn parse_gateway_authentication(element: &Element, computer: &str) -> anyhow::Result<GatewayAuthentication> {
|
||||
let (cookie, mode) = parse_issued_authentication(element, computer)?;
|
||||
GatewayAuthentication::new(cookie, mode?)
|
||||
}
|
||||
|
||||
fn build_gateway_token(args: &[Cow<'_, str>], computer: &str) -> anyhow::Result<String> {
|
||||
let mut params = vec![
|
||||
read_required_arg(&args, 1, "authcookie")?,
|
||||
read_optional_arg(&args, 2, "persistent-cookie")?,
|
||||
@@ -198,11 +434,15 @@ fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<
|
||||
}
|
||||
|
||||
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
|
||||
let value = decode(value)?;
|
||||
if value.is_empty() || value == "(null)" || value == "-1" {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(Some(decode(value)?.into_owned()))
|
||||
anyhow::ensure!(
|
||||
!value.chars().any(char::is_control),
|
||||
"Gateway argument contains control characters"
|
||||
);
|
||||
Ok(Some(value.into_owned()))
|
||||
}
|
||||
|
||||
fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||
@@ -223,6 +463,268 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tunnel_response() -> String {
|
||||
let root = login_response(Some("tunnel"), "issued-cookie");
|
||||
let mut xml = Vec::new();
|
||||
root.write(&mut xml).unwrap();
|
||||
crate::session::transport::tests::response(std::str::from_utf8(&xml).unwrap())
|
||||
}
|
||||
|
||||
fn test_params() -> GpParams {
|
||||
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_cancels_stalled_headers_and_body() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
for partial_response in ["", "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<jnlp>"] {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let (ready, received) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = [0; 4096];
|
||||
assert!(socket.read(&mut buffer).await.unwrap() > 0);
|
||||
socket.write_all(partial_response.as_bytes()).await.unwrap();
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
});
|
||||
let cancellation = CancellationToken::new();
|
||||
let token = cancellation.clone();
|
||||
let login = tokio::spawn(async move {
|
||||
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
client.login(&credential, None, &token).await
|
||||
});
|
||||
received.await.unwrap();
|
||||
cancellation.cancel();
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(1), login)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(result.err().unwrap().is::<crate::auth::AuthenticationCancelled>());
|
||||
release.send(()).unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_during_cleanup_only_logout_awaits_cleanup() {
|
||||
use crate::session::transport::tests::response;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let mut xml = Vec::new();
|
||||
login_response(None, "issued-cookie").write(&mut xml).unwrap();
|
||||
let login_response = response(std::str::from_utf8(&xml).unwrap());
|
||||
let (ready, received) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = [0; 4096];
|
||||
assert!(socket.read(&mut buffer).await.unwrap() > 0);
|
||||
socket.write_all(login_response.as_bytes()).await.unwrap();
|
||||
drop(socket);
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let read = socket.read(&mut buffer).await.unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(&buffer[..read])
|
||||
.unwrap()
|
||||
.contains("/ssl-vpn/logout.esp")
|
||||
);
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
socket
|
||||
.write_all(response("<response status='success'/>").as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let cancellation = CancellationToken::new();
|
||||
let token = cancellation.clone();
|
||||
let mut login = tokio::spawn(async move {
|
||||
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
client.login(&credential, None, &token).await
|
||||
});
|
||||
received.await.unwrap();
|
||||
cancellation.cancel();
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_millis(20), &mut login)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
release.send(()).unwrap();
|
||||
assert!(login.await.unwrap().err().unwrap().is::<GatewayLoginProtocolError>());
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_login_follows_redirects_without_physical_binding() {
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
tunnel_response(),
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
tunnel_response(),
|
||||
]).await;
|
||||
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(
|
||||
matches!(client.login(&credential, None, &CancellationToken::new()).await.unwrap(), GatewayLogin::Authenticated(authentication) if authentication.mode() == crate::session::SessionMode::Tunnel)
|
||||
);
|
||||
assert!(client.binding().is_none());
|
||||
assert!(matches!(
|
||||
client.extend_lifetime(&credential).await.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
|
||||
assert_eq!(requests[1].0, "/redirected-login");
|
||||
assert_eq!(requests[3].0, "/redirected-login");
|
||||
assert!(requests[3].1.contains("extend-lifetime=true"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_login_keeps_reqwest_address_fallback() {
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
|
||||
let port = origin.port().unwrap();
|
||||
let params = test_params();
|
||||
let mut client = GatewayLoginClient::new(&format!("http://gateway.invalid:{port}"), params.clone()).unwrap();
|
||||
// Supply deterministic DNS candidates; all other client behavior is the
|
||||
// ordinary request path. The first address refuses, the second is reachable.
|
||||
client.client = params
|
||||
.client_builder()
|
||||
.unwrap()
|
||||
.no_proxy()
|
||||
.resolve_to_addrs(
|
||||
"gateway.invalid",
|
||||
&[
|
||||
SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, port)),
|
||||
SocketAddr::from(([127, 0, 0, 1], port)),
|
||||
],
|
||||
)
|
||||
.build()
|
||||
.unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(matches!(
|
||||
client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
assert!(client.binding().is_none());
|
||||
assert_eq!(server.await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_login_can_use_a_proxy_without_local_gateway_resolution() {
|
||||
let (_, proxy, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
|
||||
let params = test_params();
|
||||
let mut client = GatewayLoginClient::new("http://unresolvable.invalid", params.clone()).unwrap();
|
||||
client.client = params
|
||||
.client_builder()
|
||||
.unwrap()
|
||||
.proxy(reqwest::Proxy::all(proxy.as_str()).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(matches!(
|
||||
client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
assert!(client.binding().is_none());
|
||||
assert_eq!(
|
||||
server.await.unwrap()[0].0,
|
||||
"http://unresolvable.invalid/ssl-vpn/login.esp"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_mode_logs_out_issued_cookie_before_returning_protocol_error() {
|
||||
use crate::session::transport::tests::{login_gateway, response};
|
||||
let root = login_response(None, "issued-cookie");
|
||||
let mut xml = Vec::new();
|
||||
root.write(&mut xml).unwrap();
|
||||
let (client, origin, server) = login_gateway(vec![
|
||||
response(std::str::from_utf8(&xml).unwrap()),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let params =
|
||||
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let mut client = GatewayLoginClient {
|
||||
client,
|
||||
..GatewayLoginClient::new(origin.as_str(), params).unwrap()
|
||||
};
|
||||
let error = client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.is::<GatewayLoginProtocolError>());
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
|
||||
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
|
||||
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[1].1).unwrap();
|
||||
assert_eq!(form.get("authcookie").map(String::as_str), Some("issued-cookie"));
|
||||
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_only_parsing_does_not_salvage_server_error_authentication() {
|
||||
let mut root = login_response(None, "issued-cookie");
|
||||
root.attributes.insert("status".into(), "error".into());
|
||||
assert!(parse_issued_authentication(&root, "computer").is_err());
|
||||
for encoded in ["%28null%29", "%2D1", "%00"] {
|
||||
assert!(parse_issued_authentication(&login_response(Some("tunnel"), encoded), "computer").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn login_response(mode: Option<&str>, cookie: &str) -> Element {
|
||||
let mut args = vec![""; 19];
|
||||
args[1] = cookie;
|
||||
args[4] = "alice";
|
||||
if let Some(mode) = mode {
|
||||
args[12] = mode;
|
||||
}
|
||||
let arguments = args
|
||||
.iter()
|
||||
.map(|value| format!("<argument>{value}</argument>"))
|
||||
.collect::<String>();
|
||||
Element::parse(format!("<jnlp><application-desc>{arguments}</application-desc></jnlp>").as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_mode_is_independent_of_network_location() {
|
||||
for (value, mode) in [
|
||||
("tunnel", crate::session::SessionMode::Tunnel),
|
||||
("non-tunnel", crate::session::SessionMode::NonTunnel),
|
||||
("internal", crate::session::SessionMode::NonTunnel),
|
||||
] {
|
||||
let authentication =
|
||||
parse_gateway_authentication(&login_response(Some(value), "test-cookie"), "computer").unwrap();
|
||||
assert_eq!(authentication.mode(), mode);
|
||||
assert_eq!(authentication.connection_type(), value);
|
||||
assert!(!format!("{authentication:?}").contains("test-cookie"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_rejects_missing_mode_or_cookie() {
|
||||
for mode in [None, Some(""), Some("(null)"), Some("-1"), Some(" ")] {
|
||||
assert!(parse_gateway_authentication(&login_response(mode, "test-cookie"), "computer").is_err());
|
||||
}
|
||||
assert!(parse_gateway_authentication(&login_response(Some("tunnel"), ""), "computer").is_err());
|
||||
let response = Element::parse(b"<response status='error'/>".as_slice()).unwrap();
|
||||
assert!(parse_gateway_authentication(&response, "computer").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mfa() {
|
||||
let res = r#"var respStatus = "Challenge";
|
||||
@@ -263,7 +765,9 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
||||
"#;
|
||||
|
||||
let root = Element::parse(res.as_bytes()).unwrap();
|
||||
let token = build_gateway_token(&root, "metalklesk").unwrap();
|
||||
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
|
||||
let token = authentication.cookie();
|
||||
assert_eq!(authentication.mode(), crate::session::SessionMode::Tunnel);
|
||||
|
||||
assert_eq!(
|
||||
token,
|
||||
@@ -300,7 +804,8 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
||||
"#;
|
||||
|
||||
let root = Element::parse(res.as_bytes()).unwrap();
|
||||
let token = build_gateway_token(&root, "metalklesk").unwrap();
|
||||
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
|
||||
let token = authentication.cookie();
|
||||
|
||||
assert_eq!(
|
||||
token,
|
||||
|
||||
@@ -118,7 +118,7 @@ impl GatewayLoginContext {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub(crate) fn kind(&self) -> GatewayKind {
|
||||
pub fn kind(&self) -> GatewayKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
|
||||
@@ -5,15 +5,13 @@ use std::{
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{info, warn};
|
||||
use reqwest::Client;
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
credential::Credential,
|
||||
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
|
||||
gp_params::GpParams,
|
||||
gateway::login::{GatewayLogin, GatewayLoginClient},
|
||||
session::SessionRequestArgs,
|
||||
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
|
||||
utils::{parse_gp_response, xml::ElementExt},
|
||||
};
|
||||
|
||||
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
|
||||
@@ -22,12 +20,18 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
|
||||
#[derive(Clone)]
|
||||
pub struct SessionExtensionAuth {
|
||||
credential: Credential,
|
||||
gp_params: GpParams,
|
||||
client: GatewayLoginClient,
|
||||
}
|
||||
|
||||
impl SessionExtensionAuth {
|
||||
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
|
||||
Self { credential, gp_params }
|
||||
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
|
||||
Self { credential, client }
|
||||
}
|
||||
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
|
||||
self.client.client_identity()
|
||||
}
|
||||
pub fn binding(&self) -> Option<&crate::session::network::GatewayBinding> {
|
||||
self.client.binding()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +39,7 @@ impl std::fmt::Debug for SessionExtensionAuth {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SessionExtensionAuth")
|
||||
.field("username", &self.credential.username())
|
||||
.field("gp_params", &"<redacted>")
|
||||
.field("client", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -83,10 +87,15 @@ impl SessionContext {
|
||||
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
extend_session_lifetime(ctx).await?;
|
||||
|
||||
let base_url = normalize_server(ctx.server())?;
|
||||
let client = build_session_client(ctx.session_args())?;
|
||||
let auth = ctx
|
||||
.extension_auth()
|
||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
||||
let client = auth.client.request_client();
|
||||
let url = format!(
|
||||
"{}/ssl-vpn/agentmessage.esp",
|
||||
auth.client.origin().as_str().trim_end_matches('/')
|
||||
);
|
||||
let form = build_extend_session_form(ctx)?;
|
||||
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
|
||||
|
||||
info!("Sending extend-session request");
|
||||
|
||||
@@ -108,33 +117,17 @@ async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
.extension_auth()
|
||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
||||
|
||||
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
|
||||
let login = auth.client.extend_lifetime(&auth.credential).await?;
|
||||
validate_extension_login(login)
|
||||
}
|
||||
|
||||
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
|
||||
match login {
|
||||
GatewayLogin::Cookie(_) => Ok(()),
|
||||
GatewayLogin::Authenticated(_) => Ok(()),
|
||||
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
|
||||
let mut builder = Client::builder();
|
||||
|
||||
if let Some(user_agent) = args.user_agent() {
|
||||
builder = builder.user_agent(user_agent);
|
||||
}
|
||||
|
||||
if let Some(cert) = args.certificate() {
|
||||
info!("Using client certificate authentication...");
|
||||
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
||||
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
|
||||
Ok(serde_urlencoded::from_str(args.cookie())?)
|
||||
}
|
||||
|
||||
+109
-14
@@ -1,11 +1,12 @@
|
||||
use log::info;
|
||||
use reqwest::Client;
|
||||
use reqwest::{Client, ClientBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
utils::request::create_identity,
|
||||
utils::request::{ClientIdentity, create_identity},
|
||||
};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||
@@ -43,6 +44,7 @@ pub struct GpParams {
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
key_password: Option<String>,
|
||||
prepared_identity: Option<ClientIdentity>,
|
||||
// Feature
|
||||
csc_mode: CscMode,
|
||||
// Per-request state
|
||||
@@ -135,9 +137,49 @@ impl GpParams {
|
||||
pub(crate) fn otp(&self) -> Option<&str> {
|
||||
self.otp.as_deref()
|
||||
}
|
||||
|
||||
pub fn prepare_client_identity(&mut self) -> anyhow::Result<()> {
|
||||
if self.prepared_identity.is_none() {
|
||||
if let Some(certificate) = self.certificate.as_deref() {
|
||||
self.prepared_identity = Some(ClientIdentity::load(
|
||||
certificate,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
self.certificate = None;
|
||||
self.sslkey = None;
|
||||
if let Some(mut passphrase) = self.key_password.take() {
|
||||
passphrase.zeroize();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn client_identity(&self) -> Option<&ClientIdentity> {
|
||||
self.prepared_identity.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let mut builder = Client::builder()
|
||||
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
.user_agent(self.user_agent());
|
||||
if let Some(identity) = &self.prepared_identity {
|
||||
builder = builder.identity(identity.request_identity());
|
||||
} else if let Some(cert) = self.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
builder = builder.identity(create_identity(
|
||||
cert,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GpParamsBuilder {
|
||||
prepared_identity: Option<ClientIdentity>,
|
||||
is_gateway: bool,
|
||||
os_profile: OsProfile,
|
||||
csc_mode: CscMode,
|
||||
@@ -150,6 +192,7 @@ pub struct GpParamsBuilder {
|
||||
impl GpParamsBuilder {
|
||||
pub fn new(os_profile: OsProfile) -> Self {
|
||||
Self {
|
||||
prepared_identity: None,
|
||||
is_gateway: false,
|
||||
os_profile,
|
||||
csc_mode: Default::default(),
|
||||
@@ -176,22 +219,34 @@ impl GpParamsBuilder {
|
||||
}
|
||||
|
||||
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.certificate = certificate.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.sslkey = sslkey.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn key_password<T: Into<Option<String>>>(&mut self, password: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.key_password = password.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_identity(&mut self, identity: Option<ClientIdentity>) -> &mut Self {
|
||||
self.prepared_identity = identity;
|
||||
self.certificate = None;
|
||||
self.sslkey = None;
|
||||
self.key_password = None;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(&self) -> GpParams {
|
||||
GpParams {
|
||||
prepared_identity: self.prepared_identity.clone(),
|
||||
os_profile: self.os_profile.clone(),
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
certificate: self.certificate.clone(),
|
||||
@@ -209,24 +264,64 @@ impl TryFrom<&GpParams> for Client {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
|
||||
let mut builder = Client::builder()
|
||||
.danger_accept_invalid_certs(value.ignore_tls_errors)
|
||||
.user_agent(value.user_agent());
|
||||
|
||||
if let Some(cert) = value.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
let identity = create_identity(cert, value.sslkey.as_deref(), value.key_password.as_deref())?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
|
||||
let client = builder.build()?;
|
||||
Ok(client)
|
||||
Ok(value.client_builder()?.build()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn path_identity_settings_replace_a_prepared_snapshot() {
|
||||
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
|
||||
let setters: [fn(&mut GpParamsBuilder); 3] = [
|
||||
|builder| {
|
||||
builder.certificate(Some("missing-replacement-certificate.pem".into()));
|
||||
},
|
||||
|builder| {
|
||||
builder.sslkey(Some("replacement-key.pem".into()));
|
||||
},
|
||||
|builder| {
|
||||
builder.key_password(Some("replacement-password".into()));
|
||||
},
|
||||
];
|
||||
for setter in setters {
|
||||
let mut builder = GpParams::builder(profile(ClientOs::Linux));
|
||||
builder.client_identity(Some(identity.clone()));
|
||||
setter(&mut builder);
|
||||
let params = builder.build();
|
||||
assert!(
|
||||
params.client_identity().is_none(),
|
||||
"Path settings must not silently use the previous identity"
|
||||
);
|
||||
if params.certificate.is_some() {
|
||||
assert!(
|
||||
Client::try_from(¶ms).is_err(),
|
||||
"The replacement certificate path must actually be loaded"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_identity_replaces_paths_and_can_be_explicitly_disabled() {
|
||||
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
|
||||
let mut builder = GpParams::builder(profile(ClientOs::Linux));
|
||||
builder
|
||||
.certificate(Some("missing-certificate.pem".into()))
|
||||
.sslkey(Some("missing-key.pem".into()))
|
||||
.key_password(Some("unused-password".into()))
|
||||
.client_identity(Some(identity));
|
||||
let params = builder.build();
|
||||
assert!(params.client_identity().is_some());
|
||||
assert!(params.certificate.is_none() && params.sslkey.is_none() && params.key_password.is_none());
|
||||
assert!(Client::try_from(¶ms).is_ok());
|
||||
builder.certificate(None);
|
||||
let params = builder.build();
|
||||
assert!(params.client_identity().is_none());
|
||||
assert!(params.certificate.is_none());
|
||||
}
|
||||
use crate::os_profile::runtime_client_os;
|
||||
|
||||
fn profile(client_os: ClientOs) -> OsProfile {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -20,8 +23,39 @@ impl HostIdentity {
|
||||
Self::collect_with_host_id(None)
|
||||
}
|
||||
|
||||
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
|
||||
Self::collect_with_host_id_and_control(None, control)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
|
||||
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
|
||||
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
|
||||
Ok(identity) => identity,
|
||||
Err(error) => {
|
||||
log::warn!("Host identity collection was unavailable: {error}");
|
||||
Self::default_with_host_id(host_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort convenience callers retain the established derived identity
|
||||
/// when native collection is unavailable. Controlled HIP callers get errors.
|
||||
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
|
||||
Self::from_parts(
|
||||
fallback_hostname(),
|
||||
resolve_host_id(host_id, fallback_host_id),
|
||||
String::new(),
|
||||
primary_mac_colon().unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id_and_control(
|
||||
host_id: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<Self> {
|
||||
control.check()?;
|
||||
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -29,7 +63,8 @@ impl HostIdentity {
|
||||
Self::from_parts(computer, host_id, serialno, mac_addr)
|
||||
}
|
||||
|
||||
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
/// Construct a host identity from an already collected or negotiated snapshot.
|
||||
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
let host_id = non_empty(host_id, fallback_host_id());
|
||||
let computer = non_empty(computer, fallback_hostname());
|
||||
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
|
||||
@@ -163,12 +198,12 @@ fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod platform {
|
||||
use std::process::Command;
|
||||
|
||||
use super::{
|
||||
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
|
||||
primary_mac_colon, resolve_host_id,
|
||||
};
|
||||
use crate::process::collection::{CollectionControl, CollectorCommands};
|
||||
use std::io;
|
||||
|
||||
pub(super) struct RuntimeNativeHostIdentity;
|
||||
|
||||
@@ -177,74 +212,80 @@ mod platform {
|
||||
ClientOs::Mac
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<NativeHostIdentitySnapshot> {
|
||||
let commands = CollectorCommands::new(control);
|
||||
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
|
||||
control.check()?;
|
||||
let host_id = resolve_host_id(host_id_override, || {
|
||||
native_mac
|
||||
.clone()
|
||||
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
|
||||
});
|
||||
NativeHostIdentitySnapshot {
|
||||
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
|
||||
let serial_number = collect_macos_serial_number(&commands)?;
|
||||
control.check()?;
|
||||
Ok(NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
|
||||
serial_number: collect_macos_serial_number(),
|
||||
computer,
|
||||
serial_number,
|
||||
mac_address: native_mac,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn macos_computer_name() -> Option<String> {
|
||||
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
|
||||
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
|
||||
Ok(
|
||||
commands
|
||||
.run(program, args)?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok()),
|
||||
)
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
for name in ["ComputerName", "LocalHostName"] {
|
||||
if let Some(value) = output(commands, "scutil", &["--get", name])?
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_builtin_mac() -> Option<String> {
|
||||
macos_networksetup_mac("Wi-Fi")
|
||||
.or_else(|| macos_networksetup_mac("AirPort"))
|
||||
.or_else(macos_system_profiler_wifi_mac)
|
||||
}
|
||||
|
||||
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
|
||||
let output = Command::new("networksetup")
|
||||
.arg("-listallhardwareports")
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
{
|
||||
return Ok(Some(value));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
|
||||
for name in ["Wi-Fi", "AirPort"] {
|
||||
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
|
||||
return Ok(Some(mac));
|
||||
}
|
||||
}
|
||||
}
|
||||
macos_system_profiler_wifi_mac(commands)
|
||||
}
|
||||
|
||||
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
|
||||
let mut in_port = false;
|
||||
for line in stdout.lines() {
|
||||
if let Some(port) = line.strip_prefix("Hardware Port: ") {
|
||||
in_port = port == port_name;
|
||||
in_port = port == name;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn macos_system_profiler_wifi_mac() -> Option<String> {
|
||||
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut in_wifi = false;
|
||||
for line in stdout.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -252,29 +293,24 @@ mod platform {
|
||||
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
return Ok(normalize_mac_colon(mac));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn collect_macos_serial_number() -> Option<String> {
|
||||
let output = Command::new("ioreg")
|
||||
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
stdout.lines().find_map(|line| {
|
||||
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
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())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +327,17 @@ mod platform {
|
||||
ClientOs::Windows
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let host_id = resolve_host_id(host_id_override, Self::host_id);
|
||||
NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
@@ -373,7 +419,17 @@ mod platform {
|
||||
ClientOs::Linux
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
|
||||
debug!("Runtime host-id source: explicit override ({})", host_id);
|
||||
}
|
||||
@@ -476,6 +532,15 @@ mod platform {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_identity_collection_propagates_cancellation() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = HostIdentity::collect_with_control(&control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_produces_non_empty_identity() {
|
||||
let identity = HostIdentity::collect();
|
||||
@@ -528,7 +593,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn native_snapshot_uses_host_id_as_derivation_seed() {
|
||||
let native = RuntimeNativeHostIdentity::collect(None);
|
||||
let native =
|
||||
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
|
||||
|
||||
assert!(!native.host_id.is_empty());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ mod serial_number;
|
||||
|
||||
pub use host_identity::HostIdentity;
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -366,6 +369,7 @@ impl OsProfile {
|
||||
pub struct OsProfileBuilder {
|
||||
client_os: ClientOs,
|
||||
client_version: Option<String>,
|
||||
os_version_override: Option<String>,
|
||||
computer_name_override: Option<String>,
|
||||
host_id_override: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
@@ -377,6 +381,7 @@ impl OsProfileBuilder {
|
||||
Self {
|
||||
client_os,
|
||||
client_version: None,
|
||||
os_version_override: None,
|
||||
computer_name_override: None,
|
||||
host_id_override: None,
|
||||
host_identity: None,
|
||||
@@ -394,6 +399,13 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Preserve an explicitly negotiated operating system version.
|
||||
pub fn os_version(mut self, version: impl Into<String>) -> Self {
|
||||
let version = version.into();
|
||||
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
|
||||
self
|
||||
}
|
||||
|
||||
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
|
||||
self.host_identity = Some(identity);
|
||||
self
|
||||
@@ -411,31 +423,67 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Build a best-effort profile with a bounded native collection budget.
|
||||
/// Use `build_with_control` when interruption or timeout must be reported.
|
||||
pub fn build(self) -> OsProfile {
|
||||
match self
|
||||
.clone()
|
||||
.build_with_control(&CollectionBudget::new(Duration::from_secs(60)))
|
||||
{
|
||||
Ok(profile) => profile,
|
||||
Err(error) => {
|
||||
log::warn!("OS profile collection was unavailable: {error}");
|
||||
let identity = self
|
||||
.host_identity
|
||||
.clone()
|
||||
.unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref()));
|
||||
let (os_version, software_version) = match self.client_os {
|
||||
ClientOs::Mac => (
|
||||
format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
|
||||
DEFAULT_MACOS_VERSION.into(),
|
||||
),
|
||||
os => (target::os_version(os), target::software_version(os)),
|
||||
};
|
||||
self.finish(identity, os_version, software_version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result<OsProfile> {
|
||||
control.check()?;
|
||||
let host_identity = match (&self.host_identity, &self.host_id_override) {
|
||||
(Some(identity), _) => identity.clone(),
|
||||
(None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?,
|
||||
};
|
||||
let (os_version, software_version) = if self.client_os == ClientOs::Mac {
|
||||
let version = macos_version_with_control(control)?;
|
||||
(format!("Apple Mac OS X {version}"), version)
|
||||
} else {
|
||||
(
|
||||
target::os_version(self.client_os),
|
||||
target::software_version(self.client_os),
|
||||
)
|
||||
};
|
||||
control.check()?;
|
||||
Ok(self.finish(host_identity, os_version, software_version))
|
||||
}
|
||||
|
||||
fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile {
|
||||
let client_version = self
|
||||
.client_version
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().to_string());
|
||||
|
||||
let host_identity = match (self.host_identity, self.host_id_override) {
|
||||
(Some(identity), _) => identity,
|
||||
(None, host_id) => HostIdentity::collect_with_host_id(host_id.as_deref()),
|
||||
};
|
||||
.filter(|version| !version.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().into());
|
||||
let profile_identity =
|
||||
ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override);
|
||||
let os_version = target::os_version(self.client_os);
|
||||
let software_version = target::software_version(self.client_os);
|
||||
let os_vendor = target::os_vendor(self.client_os);
|
||||
|
||||
let os_version = self.os_version_override.unwrap_or(default_os_version);
|
||||
let user_agent = self
|
||||
.user_agent
|
||||
.unwrap_or_else(|| format!("{}/{} ({})", GP_USER_AGENT, client_version, os_version));
|
||||
|
||||
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
|
||||
OsProfile {
|
||||
client_os: self.client_os,
|
||||
os_version,
|
||||
software_version,
|
||||
os_vendor,
|
||||
os_vendor: target::os_vendor(self.client_os),
|
||||
client_version,
|
||||
host_identity,
|
||||
profile_identity,
|
||||
@@ -500,14 +548,28 @@ fn runtime_distro_or(fallback: &str) -> String {
|
||||
}
|
||||
|
||||
fn macos_version() -> String {
|
||||
if runtime_client_os() == ClientOs::Mac {
|
||||
match os_info::get().version() {
|
||||
os_info::Version::Unknown => DEFAULT_MACOS_VERSION.to_string(),
|
||||
v => v.to_string(),
|
||||
}
|
||||
} else {
|
||||
DEFAULT_MACOS_VERSION.to_string()
|
||||
macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| {
|
||||
log::warn!("Operating system version collection was unavailable: {error}");
|
||||
DEFAULT_MACOS_VERSION.into()
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result<String> {
|
||||
control.check()?;
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let commands = crate::process::collection::CollectorCommands::new(control);
|
||||
let version = commands
|
||||
.run("sw_vers", &["-productVersion"])?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok())
|
||||
.map(|version| version.trim().to_string())
|
||||
.filter(|version| !version.is_empty());
|
||||
control.check()?;
|
||||
Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into()))
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Ok(DEFAULT_MACOS_VERSION.into())
|
||||
}
|
||||
|
||||
fn macos_os_string() -> String {
|
||||
@@ -691,6 +753,37 @@ mod target_identity {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
|
||||
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.build_with_control(&cancelled)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let expired = CollectionBudget::new(Duration::ZERO);
|
||||
let error = OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build_with_control(&expired)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.host_identity(identity)
|
||||
.client_version("6.3.3")
|
||||
.os_version("negotiated-system-version")
|
||||
.build();
|
||||
assert_eq!(profile.os_version(), "negotiated-system-version");
|
||||
assert!(profile.user_agent().contains("negotiated-system-version"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csc_support_defaults_match_official_profiles() {
|
||||
assert!(!ClientOs::Linux.default_csc_support());
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::bail;
|
||||
use dns_lookup::lookup_addr;
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
@@ -14,6 +14,7 @@ use crate::{
|
||||
gateway::{Gateway, parse_gateways},
|
||||
gp_params::GpParams,
|
||||
params,
|
||||
session::{InternalSessionPolicy, network::InternalHostDetection},
|
||||
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
@@ -35,6 +36,7 @@ pub struct PortalConfig {
|
||||
* - Some(true): Internal host detection is supported and the user is connected to the internal network
|
||||
*/
|
||||
internal_host_detection: Option<bool>,
|
||||
internal_detection: Option<InternalHostDetection>,
|
||||
/**
|
||||
* The version returned by the portal config, if any
|
||||
*/
|
||||
@@ -47,6 +49,7 @@ pub struct PortalConfig {
|
||||
* Whether the portal policy enables default-browser authentication.
|
||||
*/
|
||||
default_browser: Option<bool>,
|
||||
internal_session_policy: Option<InternalSessionPolicy>,
|
||||
}
|
||||
|
||||
impl PortalConfig {
|
||||
@@ -70,6 +73,10 @@ impl PortalConfig {
|
||||
self.internal_host_detection
|
||||
}
|
||||
|
||||
pub fn internal_detection(&self) -> Option<&InternalHostDetection> {
|
||||
self.internal_detection.as_ref()
|
||||
}
|
||||
|
||||
pub fn connect_method(&self) -> Option<&str> {
|
||||
self.connect_method.as_deref()
|
||||
}
|
||||
@@ -86,6 +93,10 @@ impl PortalConfig {
|
||||
self.default_browser
|
||||
}
|
||||
|
||||
pub fn internal_session_policy(&self) -> Option<InternalSessionPolicy> {
|
||||
self.internal_session_policy
|
||||
}
|
||||
|
||||
/// In-place sort the gateways by region
|
||||
pub fn sort_gateways(&mut self, region: &str) {
|
||||
let preferred_gateway = self.find_preferred_gateway(region);
|
||||
@@ -129,7 +140,14 @@ impl PortalConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<PortalConfig> {
|
||||
/// Cancellation is handled inside the request so a running native detection
|
||||
/// helper is always cancelled and joined. Do not drop this future on disconnect.
|
||||
pub async fn retrieve_config(
|
||||
portal: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
let portal = normalize_server(portal)?;
|
||||
let server = remove_url_scheme(&portal);
|
||||
|
||||
@@ -146,29 +164,35 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
|
||||
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
|
||||
info!("Portal config request params: {}", redact_form_params(&body_pairs));
|
||||
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
let res_xml = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = async {
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
|
||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
|
||||
if err.is_status_error() {
|
||||
warn!("{err}");
|
||||
bail!("Portal config error: {}", err.reason);
|
||||
}
|
||||
if err.is_status_error() {
|
||||
warn!("{err}");
|
||||
bail!("Portal config error: {}", err.reason);
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
|
||||
})?;
|
||||
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
|
||||
})
|
||||
} => result?,
|
||||
};
|
||||
|
||||
if res_xml.is_empty() {
|
||||
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
|
||||
}
|
||||
|
||||
debug!("Portal config response: {}", res_xml);
|
||||
debug!("Portal config response received: {} bytes", res_xml.len());
|
||||
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
|
||||
if csc::is_config_criteria(&root) {
|
||||
@@ -178,14 +202,18 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
|
||||
"Portal returned CSC criteria but CSC support is disabled".to_string()
|
||||
));
|
||||
}
|
||||
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
|
||||
debug!("Portal CSC config response: {}", csc_xml);
|
||||
let csc_xml = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
|
||||
};
|
||||
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
|
||||
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
return parse_portal_config(&server, cred, root);
|
||||
return parse_portal_config(&server, cred, root, cancellation).await;
|
||||
}
|
||||
|
||||
info!("Portal did not return CSC criteria");
|
||||
parse_portal_config(&server, cred, root)
|
||||
parse_portal_config(&server, cred, root, cancellation).await
|
||||
}
|
||||
|
||||
async fn retrieve_csc_config(
|
||||
@@ -245,12 +273,31 @@ fn present(value: Option<&str>) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
async fn parse_portal_config(
|
||||
server: &str,
|
||||
cred: &Credential,
|
||||
root: Element,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
let internal_detection = root
|
||||
.descendant("internal-host-detection")
|
||||
.map(parse_internal_detection)
|
||||
.transpose()
|
||||
.unwrap_or_else(|error| {
|
||||
warn!("Internal host detection policy is unavailable: {error}");
|
||||
None
|
||||
})
|
||||
.flatten();
|
||||
let prefer_internal = match &internal_detection {
|
||||
Some(detection) => detection.detect(cancellation).await.unwrap_or_else(|error| {
|
||||
warn!("Internal host detection failed: {error}");
|
||||
false
|
||||
}),
|
||||
None => false,
|
||||
};
|
||||
|
||||
if cancellation.is_cancelled() {
|
||||
bail!("Portal configuration cancelled");
|
||||
}
|
||||
|
||||
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
|
||||
@@ -275,6 +322,7 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
|
||||
info!("Detected portal version: {:?}", version);
|
||||
let allow_extend_session = parse_allow_extend_session(&root);
|
||||
let default_browser = parse_default_browser(&root);
|
||||
let internal_session_policy = parse_internal_session_policy(&root).ok();
|
||||
|
||||
Ok(PortalConfig {
|
||||
portal: server.to_string(),
|
||||
@@ -283,13 +331,42 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
|
||||
gateways,
|
||||
connect_method,
|
||||
config_digest: config_digest.map(|s| s.to_string()),
|
||||
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
|
||||
internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal),
|
||||
internal_detection,
|
||||
version,
|
||||
allow_extend_session,
|
||||
default_browser,
|
||||
internal_session_policy,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_internal_session_policy(root: &Element) -> anyhow::Result<InternalSessionPolicy> {
|
||||
let hip = root.descendant("hip-collection");
|
||||
let interval = hip
|
||||
.and_then(|hip| hip.child("hip-report-interval"))
|
||||
.map(|element| element.get_text().unwrap_or_default().into_owned());
|
||||
let collect = hip
|
||||
.and_then(|hip| hip.child("collect-hip-data"))
|
||||
.map(|element| element.get_text().unwrap_or_default().into_owned());
|
||||
let interval = parse_policy_number(interval, 3600, "hip-report-interval")?;
|
||||
let collect = match collect.as_deref().map(str::trim) {
|
||||
None | Some("yes") => true,
|
||||
Some("no") => false,
|
||||
Some(_) => bail!("Invalid portal collect-hip-data policy"),
|
||||
};
|
||||
InternalSessionPolicy::new(interval, collect)
|
||||
}
|
||||
|
||||
fn parse_policy_number(value: Option<String>, default: u32, field: &str) -> anyhow::Result<u32> {
|
||||
match value {
|
||||
Some(value) => value
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("Invalid portal {field} policy")),
|
||||
None => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_default_browser(root: &Element) -> Option<bool> {
|
||||
match root.descendant_text("default-browser")?.trim() {
|
||||
"yes" => Some(true),
|
||||
@@ -313,49 +390,94 @@ fn parse_connect_method(root: &Element) -> Option<String> {
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
// Perform DNS lookup and compare the result with the expected hostname
|
||||
fn internal_host_detect(element: &Element) -> bool {
|
||||
fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<InternalHostDetection>> {
|
||||
let ip_info = [
|
||||
(element.child_text("ip-address"), element.child_text("host")),
|
||||
(element.child_text("ipv6-address"), element.child_text("ipv6-host")),
|
||||
];
|
||||
|
||||
info!("Found internal-host-detection, performing DNS lookup");
|
||||
|
||||
let mut targets = Vec::new();
|
||||
for (ip_address, host) in ip_info.iter() {
|
||||
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),
|
||||
}
|
||||
let address = ip_address.as_deref().filter(|value| !value.is_empty());
|
||||
let host = host.as_deref().filter(|value| !value.is_empty());
|
||||
match (address, host) {
|
||||
(None, None) => {}
|
||||
(Some(address), Some(host)) => targets.push((address.parse()?, host.to_owned())),
|
||||
_ => bail!("Incomplete internal host detection policy"),
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
if targets.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(InternalHostDetection::new(targets)?))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_non_tunnel_policy_does_not_reject_tunnel_candidates() {
|
||||
let root = parse_xml(
|
||||
"<policy><hip-collection><hip-report-interval>invalid</hip-report-interval></hip-collection><internal-host-detection><ip-address>invalid</ip-address><host>internal.example</host></internal-host-detection><gateways><external><list><entry name='vpn.example'/></list></external></gateways></policy>",
|
||||
);
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let config = parse_portal_config("portal.example", &credential, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(config.internal_session_policy().is_none());
|
||||
assert_eq!(config.gateways()[0].server(), "vpn.example");
|
||||
assert_eq!(config.gateways()[0].kind(), crate::gateway::GatewayKind::External);
|
||||
}
|
||||
|
||||
fn parse_xml(xml: &str) -> Element {
|
||||
Element::parse(xml.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_internal_maintenance_policy_with_explicit_units() {
|
||||
let root = parse_xml(
|
||||
"<policy><hip-collection><hip-report-interval>60</hip-report-interval><collect-hip-data>no</collect-hip-data></hip-collection><max-internal-gateway-connection-attempts>3</max-internal-gateway-connection-attempts></policy>",
|
||||
);
|
||||
let policy = parse_internal_session_policy(&root).unwrap();
|
||||
assert_eq!(policy.hip_interval(), std::time::Duration::from_secs(60));
|
||||
assert!(!policy.collect_hip_data());
|
||||
assert_eq!(
|
||||
parse_internal_session_policy(&parse_xml("<policy/>")).unwrap(),
|
||||
InternalSessionPolicy::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_supplied_internal_policy() {
|
||||
for interval in ["0", "-1", "", "4294967295", "not-a-number"] {
|
||||
let root = parse_xml(&format!(
|
||||
"<policy><hip-collection><hip-report-interval>{interval}</hip-report-interval></hip-collection></policy>"
|
||||
));
|
||||
assert!(parse_internal_session_policy(&root).is_err());
|
||||
}
|
||||
let root = parse_xml("<policy><hip-collection><collect-hip-data>true</collect-hip-data></hip-collection></policy>");
|
||||
assert!(parse_internal_session_policy(&root).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepts_existing_full_portal_fixture() {
|
||||
let root = parse_xml(include_str!("../../tests/files/portal_config.xml"));
|
||||
let cred = Credential::from(crate::credential::PasswordCredential::new(
|
||||
"fixture-user",
|
||||
"fixture-password",
|
||||
));
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
config.internal_session_policy().unwrap().hip_interval(),
|
||||
std::time::Duration::from_secs(3600)
|
||||
);
|
||||
assert!(!config.gateways().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_allow_extend_session_yes() {
|
||||
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
|
||||
@@ -412,8 +534,8 @@ mod tests {
|
||||
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_csc_policy_response_as_portal_config() {
|
||||
#[tokio::test]
|
||||
async fn parses_csc_policy_response_as_portal_config() {
|
||||
let root = parse_xml(
|
||||
r#"<policy>
|
||||
<portal-userauthcookie>user-cookie</portal-userauthcookie>
|
||||
@@ -431,7 +553,9 @@ mod tests {
|
||||
);
|
||||
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
|
||||
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
|
||||
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
path::{Path, PathBuf},
|
||||
process::Stdio,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
use super::{command_runner::run_observed, command_traits::CommandExt};
|
||||
|
||||
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
auth_executable: Option<&'a str>,
|
||||
gateway: bool,
|
||||
@@ -41,11 +46,13 @@ pub struct SamlAuthLauncher<'a> {
|
||||
browser_listen: Option<IpAddr>,
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
dmabuf_disabled: bool,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
pub fn new(server: &'a str) -> Self {
|
||||
Self {
|
||||
cancellation: CancellationToken::new(),
|
||||
server,
|
||||
auth_executable: None,
|
||||
gateway: false,
|
||||
@@ -72,9 +79,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
browser_listen: None,
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
dmabuf_disabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||
self.dmabuf_disabled = disabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn auth_executable(mut self, auth_executable: Option<&'a str>) -> Self {
|
||||
self.auth_executable = auth_executable;
|
||||
self
|
||||
@@ -176,6 +189,11 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
|
||||
self.cancellation = cancellation.clone();
|
||||
self
|
||||
}
|
||||
|
||||
/// The command line this launcher will run.
|
||||
///
|
||||
/// Split out from `launch` so a test can observe the argv the child actually
|
||||
@@ -273,26 +291,74 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let mut non_root_cmd = auth_cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => {
|
||||
bail!("Failed to spawn {}: {}", program.display(), err);
|
||||
let mut command = auth_cmd.into_non_root()?.into_std();
|
||||
let embedded = cfg!(feature = "webview-auth") && self.browser.is_none();
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let embedded = embedded && !self.default_browser;
|
||||
let bundled = is_bundled_authenticator(&program, &binary_paths::gpauth());
|
||||
let can_recover = embedded && bundled && eligible(&command);
|
||||
if embedded && bundled && self.dmabuf_disabled {
|
||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
}
|
||||
let cancellation = self.cancellation.clone();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let mut diagnostic = StderrDiagnostic::default();
|
||||
let output = run_observed(
|
||||
command,
|
||||
&check,
|
||||
Some(MAX_AUTH_RESULT_BYTES),
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut std::io::stderr(),
|
||||
None,
|
||||
)?;
|
||||
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||
})
|
||||
.await?;
|
||||
let (output, rendering_diagnostic) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let output = child.wait_with_output().await?;
|
||||
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
|
||||
Credential::try_from(auth_result)
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
decode_auth_output(output, can_recover && rendering_diagnostic)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bundled_authenticator(program: &Path, bundled: &Path) -> bool {
|
||||
match (program.canonicalize(), bundled.canonicalize()) {
|
||||
(Ok(program), Ok(bundled)) => program == bundled,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_auth_output(output: std::process::Output, rendering_failure: bool) -> anyhow::Result<Credential> {
|
||||
if !output.status.success() {
|
||||
if rendering_failure && is_crash_exit(output.status) {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
}
|
||||
bail!("Authenticator exited unsuccessfully: {}", output.status);
|
||||
}
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
Credential::try_from(auth_result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -383,4 +449,76 @@ mod tests {
|
||||
|
||||
assert_eq!(launcher.browser_listen, Some(listen_ip));
|
||||
}
|
||||
#[test]
|
||||
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||
stdout,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<RenderingCrash>().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: b"partial".to_vec(),
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<RenderingCrash>().is_none());
|
||||
assert_eq!(error.to_string(), "Failed to parse auth data");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_authenticator_crash_does_not_request_recovery() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let executable = directory.path().join("auth-fixture");
|
||||
std::fs::write(
|
||||
&executable,
|
||||
"#!/bin/sh\nprintf 'Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display\\n' >&2\nexit 71\n",
|
||||
)
|
||||
.unwrap();
|
||||
// The launcher drops root privileges in CI; its child must be able to
|
||||
// traverse the fixture directory and execute this non-sensitive script.
|
||||
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let error = SamlAuthLauncher::new("fixture.invalid")
|
||||
.auth_executable(executable.to_str())
|
||||
.dmabuf_disabled(true)
|
||||
.launch()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<RenderingCrash>().is_none());
|
||||
assert!(
|
||||
error.to_string().starts_with("Authenticator exited unsuccessfully:"),
|
||||
"unexpected launch error: {error:#}"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn service_provided_bundled_path_is_not_a_custom_authenticator() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let bundled = directory.path().join("gpauth");
|
||||
let custom = directory.path().join("custom");
|
||||
std::fs::write(&bundled, "bundled").unwrap();
|
||||
std::fs::write(&custom, "custom").unwrap();
|
||||
assert!(is_bundled_authenticator(&bundled, &bundled));
|
||||
assert!(!is_bundled_authenticator(&custom, &bundled));
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
use std::{
|
||||
fs, io,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use super::command_runner::run_controlled;
|
||||
|
||||
/// Invocation control borrowed by collection; interruption must never be treated
|
||||
/// as an unavailable optional product.
|
||||
pub trait CollectionControl {
|
||||
fn check(&self) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
self()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CollectionBudget {
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl CollectionBudget {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
deadline: Instant::now() + timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CollectionControl for CollectionBudget {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
if Instant::now() >= self.deadline {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Device information collection timed out",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
|
||||
const TOOL_DIRECTORIES: &[&str] = &[
|
||||
"/usr/bin",
|
||||
"/usr/sbin",
|
||||
"/bin",
|
||||
"/sbin",
|
||||
"/usr/local/bin",
|
||||
"/usr/local/sbin",
|
||||
#[cfg(target_os = "linux")]
|
||||
"/run/current-system/sw/bin",
|
||||
];
|
||||
|
||||
fn tool_directories() -> Vec<PathBuf> {
|
||||
let configured = std::env::var_os("GP_COMMAND_PATH").unwrap_or_default();
|
||||
let mut directories: Vec<_> = std::env::split_paths(&configured)
|
||||
.filter(|path| path.is_absolute())
|
||||
.collect();
|
||||
directories.extend(TOOL_DIRECTORIES.iter().map(PathBuf::from));
|
||||
directories
|
||||
}
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0)
|
||||
}
|
||||
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = self.resolve(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
/// Run an installed helper with the same trust checks as system collectors.
|
||||
/// Root only executes helpers protected from unprivileged modification.
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = resolve_executable(path, uzers::get_effective_uid() == 0) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let home = if uzers::get_effective_uid() == 0 {
|
||||
if cfg!(target_os = "macos") {
|
||||
"/var/root"
|
||||
} else {
|
||||
"/root"
|
||||
}
|
||||
} else {
|
||||
"/"
|
||||
};
|
||||
let mut command = Command::new(path);
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
|
||||
.env("LC_ALL", "C")
|
||||
.env("HOME", home)
|
||||
.current_dir("/")
|
||||
.stderr(Stdio::null());
|
||||
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option<PathBuf> {
|
||||
directories.iter().find_map(|directory| {
|
||||
let directory = fs::canonicalize(directory).ok()?;
|
||||
if require_root && !root_owned_path(&directory) {
|
||||
return None;
|
||||
}
|
||||
resolve_executable(&directory.join(name), require_root)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
|
||||
let resolved = fs::canonicalize(path).ok()?;
|
||||
let metadata = fs::metadata(&resolved).ok()?;
|
||||
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Known command directories, canonicalized and restricted to trusted root
|
||||
/// ownership when used for privileged execution.
|
||||
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
|
||||
let configured = tool_directories();
|
||||
let directories = configured.iter().filter_map(|directory| {
|
||||
let resolved = fs::canonicalize(directory).ok()?;
|
||||
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
|
||||
}
|
||||
|
||||
fn root_owned_path(path: &Path) -> bool {
|
||||
path.ancestors().all(|part| {
|
||||
fs::symlink_metadata(part).is_ok_and(|metadata| {
|
||||
let mode = metadata.permissions().mode();
|
||||
let writable = mode & 0o022 != 0;
|
||||
// A root-owned sticky directory protects each root-owned descendant
|
||||
// from replacement, including entries in the Nix store.
|
||||
let protected_ancestor = part != path && metadata.is_dir() && mode & 0o1000 != 0;
|
||||
metadata.uid() == 0 && (!writable || protected_ancestor) && !metadata.file_type().is_symlink()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
|
||||
// A focused privileged CI check runs this test; the ordinary suite cannot create root-owned fixtures.
|
||||
if uzers::get_effective_uid() != 0 {
|
||||
return;
|
||||
}
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let tool = directory.path().join("collector");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert_eq!(resolve_executable(&tool, true), Some(fs::canonicalize(&tool).unwrap()));
|
||||
// A PATH directory must itself reject unprivileged additions, even with the sticky bit.
|
||||
assert!(!root_owned_path(directory.path()));
|
||||
assert!(resolve_in_directories("collector", &[directory.path().to_owned()], true).is_none());
|
||||
let bin = directory.path().join("bin");
|
||||
fs::create_dir(&bin).unwrap();
|
||||
fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::copy(&tool, bin.join("collector")).unwrap();
|
||||
assert!(resolve_in_directories("collector", &[bin], true).is_some());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1777)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_some());
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::os::unix::fs::chown(&tool, Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
std::os::unix::fs::chown(&tool, Some(0), None).unwrap();
|
||||
std::os::unix::fs::chown(directory.path(), Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_directories_resolve_tools_without_using_the_process_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tool = dir.path().join("configured-tool");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(
|
||||
resolve_in_directories("configured-tool", &[dir.path().to_owned()], false),
|
||||
Some(fs::canonicalize(&tool).unwrap())
|
||||
);
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(resolve_in_directories("configured-tool", &[dir.path().to_owned()], true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_command_path_contains_only_trusted_canonical_directories() {
|
||||
let path = command_path(true).unwrap();
|
||||
let directories: Vec<_> = std::env::split_paths(&path).collect();
|
||||
assert!(!directories.is_empty());
|
||||
for directory in directories {
|
||||
assert!(directory.is_dir());
|
||||
assert!(root_owned_path(&directory));
|
||||
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_resolution_returns_target_not_mutable_symlink() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let link = dir.path().join("tool");
|
||||
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
|
||||
let resolved = resolve_executable(&link, false).unwrap();
|
||||
fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
|
||||
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
|
||||
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_running_collector() {
|
||||
let started = Instant::now();
|
||||
let control = || {
|
||||
if started.elapsed() >= Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = CollectorCommands::new(&control)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_has_private_environment_and_cwd() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let output = CollectorCommands::new(&budget)
|
||||
.run_path(
|
||||
Path::new("/bin/sh"),
|
||||
&[
|
||||
"-c",
|
||||
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deadline_stops_collector_instead_of_hanging() {
|
||||
let budget = CollectionBudget::new(Duration::from_millis(100));
|
||||
let started = Instant::now();
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_output_is_bounded() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_is_not_an_optional_missing_product() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use std::{
|
||||
io::{self, Read, Write},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
use super::collection::CollectionControl;
|
||||
|
||||
/// Owns and reaps the command's process group. Its async caller must cancel and await this worker.
|
||||
pub(crate) fn run_controlled(
|
||||
command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: usize,
|
||||
) -> io::Result<Output> {
|
||||
run(command, control, Some(output_limit), None, None).map(|observed| observed.output)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ObservedOutput {
|
||||
pub output: Output,
|
||||
pub input_error: Option<io::Error>,
|
||||
}
|
||||
|
||||
pub(crate) fn run_observed(
|
||||
command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
observer: &mut dyn FnMut(&[u8]),
|
||||
stderr_sink: &mut dyn Write,
|
||||
stdin_frame: Option<&[u8]>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
run(
|
||||
command,
|
||||
control,
|
||||
output_limit,
|
||||
Some((observer, stderr_sink)),
|
||||
stdin_frame,
|
||||
)
|
||||
}
|
||||
|
||||
fn nonblocking(fd: &impl std::os::fd::AsFd) -> io::Result<()> {
|
||||
let flags = fcntl(fd, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
fcntl(
|
||||
fd,
|
||||
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
mut observation: Option<(&mut dyn FnMut(&[u8]), &mut dyn Write)>,
|
||||
stdin_frame: Option<&[u8]>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
control.check()?;
|
||||
command
|
||||
.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
})
|
||||
.process_group(0);
|
||||
command.stdin(if stdin_frame.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
});
|
||||
if observation.is_some() {
|
||||
command.stderr(Stdio::piped());
|
||||
}
|
||||
let mut child = ControlledChild {
|
||||
process: command.spawn()?,
|
||||
stopped: false,
|
||||
};
|
||||
let mut stdout = child.process.stdout.take();
|
||||
if let Some(pipe) = &stdout {
|
||||
nonblocking(pipe)?;
|
||||
}
|
||||
let mut stderr = if observation.is_some() {
|
||||
child.process.stderr.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(pipe) = &stderr {
|
||||
nonblocking(pipe)?;
|
||||
}
|
||||
let mut input = child.process.stdin.take();
|
||||
if let Some(pipe) = &input {
|
||||
nonblocking(pipe)?;
|
||||
}
|
||||
let mut input_offset = 0;
|
||||
let mut input_error = None;
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
let mut stdout_eof = stdout.is_none();
|
||||
let mut stderr_eof = stderr.is_none();
|
||||
let mut status = None;
|
||||
let mut exited_at = None;
|
||||
loop {
|
||||
control.check()?;
|
||||
let mut progressed = false;
|
||||
if let (Some(frame), Some(pipe)) = (stdin_frame, &mut input) {
|
||||
if input_offset < frame.len() && input_error.is_none() {
|
||||
match pipe.write(&frame[input_offset..]) {
|
||||
Ok(0) => input_error = Some(io::Error::new(io::ErrorKind::WriteZero, "Credential input pipe closed")),
|
||||
Ok(length) => {
|
||||
input_offset += length;
|
||||
progressed = true;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => input_error = Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !stdout_eof {
|
||||
match stdout.as_mut().unwrap().read(&mut buffer) {
|
||||
Ok(0) => stdout_eof = true,
|
||||
Ok(length) => {
|
||||
if length > output_limit.unwrap().saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
progressed = true;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if !stderr_eof {
|
||||
match stderr.as_mut().unwrap().read(&mut buffer) {
|
||||
Ok(0) => stderr_eof = true,
|
||||
Ok(length) => {
|
||||
let (observer, sink) = observation.as_mut().unwrap();
|
||||
observer(&buffer[..length]);
|
||||
sink.write_all(&buffer[..length])?;
|
||||
progressed = true;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if status.is_none()
|
||||
&& let Some(exit_status) = child.process.try_wait()?
|
||||
{
|
||||
status = Some(exit_status);
|
||||
exited_at = Some(Instant::now());
|
||||
child.stop_helpers();
|
||||
}
|
||||
if let Some(status) = status {
|
||||
if (stdout_eof && stderr_eof) || exited_at.unwrap().elapsed() >= Duration::from_millis(250) {
|
||||
if stdin_frame.is_some_and(|frame| input_offset < frame.len()) && input_error.is_none() {
|
||||
input_error = Some(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"Child exited before receiving its credential",
|
||||
));
|
||||
}
|
||||
return Ok(ObservedOutput {
|
||||
output: Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
input_error,
|
||||
});
|
||||
}
|
||||
}
|
||||
if !progressed {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ControlledChild {
|
||||
process: Child,
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
impl ControlledChild {
|
||||
fn stop_helpers(&mut self) {
|
||||
if !self.stopped {
|
||||
let _ = killpg(Pid::from_raw(self.process.id() as i32), Signal::SIGKILL);
|
||||
self.stopped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
self.stop_helpers();
|
||||
let _ = self.process.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn drains_both_pipes_and_reaps_helpers_that_hold_them_open() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "printf auth; printf diagnostic >&2; sleep 30 & exit 1"]);
|
||||
let mut seen = Vec::new();
|
||||
let mut sink = Vec::new();
|
||||
let start = Instant::now();
|
||||
let output = run_observed(
|
||||
command,
|
||||
&|| Ok(()),
|
||||
Some(1024),
|
||||
&mut |bytes| seen.extend_from_slice(bytes),
|
||||
&mut sink,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!output.output.status.success());
|
||||
assert_eq!(output.output.stdout, b"auth");
|
||||
assert_eq!(seen, b"diagnostic");
|
||||
assert_eq!(sink, seen);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
#[test]
|
||||
fn continuous_stderr_does_not_starve_cancellation_or_stdout() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "printf auth; while :; do printf 'diagnostic\\n' >&2; done"]);
|
||||
let start = Instant::now();
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = run_observed(command, &control, Some(1024), &mut |_| {}, &mut io::sink(), None).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retains_broken_input_pipe_for_failed_child_without_a_diagnostic() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "exec 0<&-; exit 2"]);
|
||||
let observed = run_observed(
|
||||
command,
|
||||
&|| Ok(()),
|
||||
None,
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
Some(&vec![0; 128 * 1024]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(observed.output.status.code(), Some(2));
|
||||
assert!(observed.input_error.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_interrupts_a_blocked_credential_write() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "sleep 30"]);
|
||||
let start = Instant::now();
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = run_observed(
|
||||
command,
|
||||
&control,
|
||||
None,
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
Some(&vec![0; 128 * 1024]),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use super::{
|
||||
command_runner::run_observed,
|
||||
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||
};
|
||||
use crate::service::transport::SessionCredential;
|
||||
use anyhow::Context;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::PathBuf,
|
||||
process::{Command, ExitStatus},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Monitor a credential-bearing desktop child; the owner cancels and joins this attempt.
|
||||
pub(super) async fn launch_desktop_child(
|
||||
name: &'static str,
|
||||
command: Command,
|
||||
envs: Option<&HashMap<String, String>>,
|
||||
credential: &SessionCredential,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
||||
let log_file = match envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
};
|
||||
let mut sink: Box<dyn std::io::Write + Send> = match log_file {
|
||||
Some(path) => Box::new(
|
||||
OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?,
|
||||
),
|
||||
None => Box::new(std::io::stderr()),
|
||||
};
|
||||
let frame = credential.encode_frame()?;
|
||||
let cancellation = cancellation.clone();
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Desktop child launch cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let mut diagnostic = StderrDiagnostic::default();
|
||||
let observed = run_observed(
|
||||
command,
|
||||
&check,
|
||||
None,
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut sink,
|
||||
Some(&frame),
|
||||
)?;
|
||||
let output = observed.output;
|
||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
}
|
||||
if let Some(error) = observed.input_error {
|
||||
return Err(error.into());
|
||||
}
|
||||
anyhow::ensure!(output.status.success(), "{name} exited with {}", output.status);
|
||||
Ok(output.status)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{File, OpenOptions},
|
||||
path::Path,
|
||||
process::{ExitStatus, Stdio},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::rendering_recovery::RecoveryState;
|
||||
use crate::service::transport::{DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY};
|
||||
use anyhow::{Context, ensure};
|
||||
use common::binary_paths;
|
||||
use log::warn;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
|
||||
process::Command,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{CommandExt, gui_launcher::GuiLauncher};
|
||||
use crate::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
||||
|
||||
/// Owns the desktop GUI and its privileged service without leaving the desktop session.
|
||||
pub struct DesktopLauncher<'a> {
|
||||
version: &'a str,
|
||||
minimized: bool,
|
||||
log_file: Option<String>,
|
||||
}
|
||||
|
||||
impl<'a> DesktopLauncher<'a> {
|
||||
pub fn new(version: &'a str) -> Self {
|
||||
Self {
|
||||
version,
|
||||
minimized: false,
|
||||
log_file: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn minimized(mut self, minimized: bool) -> Self {
|
||||
self.minimized = minimized;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn log_file(mut self, log_file: &str) -> Self {
|
||||
self.log_file = Some(log_file.to_owned());
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop launcher must not run as root"
|
||||
);
|
||||
let mut command = Command::new_pkexec(binary_paths::gpservice());
|
||||
command
|
||||
.arg("--desktop-credentials")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped());
|
||||
if let Some(path) = &self.log_file {
|
||||
command.stderr(Stdio::from(create_log_file(Path::new(path))?));
|
||||
}
|
||||
let mut service = command.spawn().context("Failed to start the privileged service")?;
|
||||
let mut input = service.stdin.take().context("Service input pipe is unavailable")?;
|
||||
let mut output = service
|
||||
.stdout
|
||||
.take()
|
||||
.context("Service credential pipe is unavailable")?;
|
||||
let mut received_credential = false;
|
||||
let mut cancelled = false;
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut recovery = RecoveryState::default();
|
||||
let result = {
|
||||
let operation = async {
|
||||
let mut minimized = self.minimized;
|
||||
let mut expecting_renewal = false;
|
||||
let mut program = None;
|
||||
loop {
|
||||
let credential = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return Ok(()),
|
||||
result = read_credential(&mut output) => result?,
|
||||
};
|
||||
let Some(credential) = credential else {
|
||||
ensure!(
|
||||
!expecting_renewal,
|
||||
"Service closed before issuing the recovery credential"
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
expecting_renewal = false;
|
||||
received_credential = true;
|
||||
ensure!(
|
||||
credential.product_version() == self.version,
|
||||
"Service product version mismatch"
|
||||
);
|
||||
let mut envs: HashMap<String, String> = std::env::vars().collect();
|
||||
if recovery.dmabuf_disabled() {
|
||||
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into());
|
||||
}
|
||||
if let Some(path) = &self.log_file {
|
||||
envs.insert("GP_LOG_FILE".into(), path.clone());
|
||||
}
|
||||
let launcher = GuiLauncher::new(self.version, Arc::new(credential))
|
||||
.envs(envs)
|
||||
.minimized(minimized);
|
||||
let mut unexpected = [0];
|
||||
// Program resolution may launch the WebKit download helper. Keep it under
|
||||
// the same cancellation, service ownership and recovery budget as gpgui.
|
||||
let attempt = async {
|
||||
if program.is_none() {
|
||||
program = Some(launcher.resolve_program(&cancellation).await?);
|
||||
}
|
||||
launcher.launch_program(program.as_ref().unwrap(), &cancellation).await
|
||||
};
|
||||
tokio::pin!(attempt);
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
|
||||
result = &mut attempt => result,
|
||||
status = service.wait() => {
|
||||
cancellation.cancel(); let _ = attempt.await;
|
||||
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
|
||||
}
|
||||
result = output.read(&mut unexpected) => {
|
||||
cancellation.cancel(); let _ = attempt.await;
|
||||
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
|
||||
anyhow::bail!("The privileged service closed its credential channel");
|
||||
}
|
||||
};
|
||||
if cancellation.is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
match outcome {
|
||||
Err(error) if recovery.recover(&error) => {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
expecting_renewal = true;
|
||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||
}
|
||||
Err(error) => return Err(recovery.terminal(error)),
|
||||
Ok(_) => {
|
||||
input.write_all(&[DESKTOP_GUI_EXITED]).await?;
|
||||
minimized = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::pin!(operation);
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = crate::utils::shutdown_signal() => {
|
||||
cancelled = true;
|
||||
cancellation.cancel();
|
||||
operation.await
|
||||
},
|
||||
result = &mut operation => result,
|
||||
};
|
||||
result
|
||||
};
|
||||
let result = recovery.finish(result);
|
||||
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
|
||||
drop(input);
|
||||
if cancelled && !received_credential {
|
||||
// pkexec is still user-owned during authorization. After elevation, EOF owns shutdown.
|
||||
if let Err(error) = service.start_kill()
|
||||
&& error.kind() != std::io::ErrorKind::PermissionDenied
|
||||
{
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
let status = service.wait().await?;
|
||||
result?;
|
||||
ensure!(
|
||||
cancelled || status.success(),
|
||||
"The privileged service exited with {status}"
|
||||
);
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
|
||||
fn create_log_file(path: &Path) -> std::io::Result<File> {
|
||||
// Start a fresh desktop session, then let both processes append without overwriting each other.
|
||||
File::create(path)?;
|
||||
OpenOptions::new().append(true).open(path)
|
||||
}
|
||||
|
||||
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
|
||||
let mut header = [0; 2];
|
||||
if reader.read(&mut header[..1]).await? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
reader.read_exact(&mut header[1..]).await?;
|
||||
let length = usize::from(u16::from_be_bytes(header));
|
||||
ensure!(
|
||||
length != 0 && length + 2 <= MAX_CREDENTIAL_FRAME,
|
||||
"Invalid service credential length"
|
||||
);
|
||||
let mut frame = Zeroizing::new(vec![0; length + 2]);
|
||||
frame[..2].copy_from_slice(&header);
|
||||
reader.read_exact(&mut frame[2..]).await?;
|
||||
Ok(Some(SessionCredential::decode_frame(&frame)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Write;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_log_starts_fresh_and_service_writes_preserve_gui_logs() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = dir.path().join("desktop.log");
|
||||
std::fs::write(&path, "previous session\n").unwrap();
|
||||
let mut service = create_log_file(&path).unwrap();
|
||||
writeln!(service, "[gpservice] started").unwrap();
|
||||
let mut gui = OpenOptions::new().append(true).open(&path).unwrap();
|
||||
writeln!(gui, "[gpgui] initialized").unwrap();
|
||||
writeln!(service, "[gpservice] connected").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpservice] connected\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_channel_distinguishes_clean_close_from_truncated_or_oversized_frames() {
|
||||
assert!(read_credential(&mut &[][..]).await.unwrap().is_none());
|
||||
assert!(read_credential(&mut &[0][..]).await.is_err());
|
||||
assert!(read_credential(&mut &[0, 0][..]).await.is_err());
|
||||
assert!(read_credential(&mut &[255, 255][..]).await.is_err());
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let decoded = read_credential(&mut frame.as_slice()).await.unwrap().unwrap();
|
||||
assert_eq!(decoded.session_id(), credential.session_id());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::{collections::HashMap, path::PathBuf, process::Stdio};
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{process::command_traits::CommandExt, service::transport::SessionCredential};
|
||||
use crate::service::transport::SessionCredential;
|
||||
|
||||
pub struct GuiHelperLauncher<'a> {
|
||||
program: PathBuf,
|
||||
@@ -34,7 +34,7 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<()> {
|
||||
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
let mut cmd = Command::new(&self.program);
|
||||
|
||||
if let Some(envs) = self.envs {
|
||||
@@ -49,24 +49,114 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
}
|
||||
|
||||
info!("Launching gpgui-helper");
|
||||
let mut non_root_cmd = cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
||||
};
|
||||
|
||||
let Some(mut stdin) = child.stdin.take() else {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
info!("gpgui-helper exited with: {}", exit_status);
|
||||
|
||||
anyhow::ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
super::desktop_child::launch_desktop_child(
|
||||
"gpgui-helper",
|
||||
cmd.into_std(),
|
||||
self.envs,
|
||||
self.credential,
|
||||
cancellation,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::process::rendering_recovery::RenderingCrash;
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
fn fixture(dir: &tempfile::TempDir, credential: &SessionCredential, body: &str) -> PathBuf {
|
||||
let path = dir.path().join("helper");
|
||||
let length = credential.encode_frame().unwrap().len();
|
||||
fs::write(
|
||||
&path,
|
||||
format!("#!/bin/sh\ndd bs=1 count={length} of=/dev/null 2>/dev/null || exit 1\n{body}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn propagates_helper_failure_and_preserves_stderr_in_desktop_log() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let path = fixture(&dir, &credential, "printf 'download failed\\n' >&2; exit 23");
|
||||
let log = dir.path().join("desktop.log");
|
||||
fs::write(&log, "").unwrap();
|
||||
let envs = HashMap::from([("GP_LOG_FILE".into(), log.to_str().unwrap().into())]);
|
||||
let launcher = GuiHelperLauncher {
|
||||
program: path,
|
||||
envs: Some(&envs),
|
||||
credential: &credential,
|
||||
gui_version: None,
|
||||
};
|
||||
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
|
||||
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
|
||||
assert!(error.to_string().contains("23"));
|
||||
assert_eq!(fs::read_to_string(log).unwrap(), "download failed\n");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recognizes_helper_rendering_crash_and_respects_explicit_override() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let path = fixture(
|
||||
&dir,
|
||||
&credential,
|
||||
"printf '(gpgui-helper:42): Gdk-Message: 12:00:00: Error 71 (Protocol error) dispatching to Wayland display\\n' >&2; exit 71",
|
||||
);
|
||||
let mut envs = HashMap::from([("WAYLAND_DISPLAY".into(), "wayland-0".into())]);
|
||||
for override_value in [None, Some(""), Some("0"), Some("1")] {
|
||||
if let Some(value) = override_value {
|
||||
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), value.into());
|
||||
}
|
||||
let launcher = GuiHelperLauncher {
|
||||
program: path.clone(),
|
||||
envs: Some(&envs),
|
||||
credential: &credential,
|
||||
gui_version: None,
|
||||
};
|
||||
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
|
||||
let eligible =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")) && override_value.is_none();
|
||||
assert_eq!(error.downcast_ref::<RenderingCrash>().is_some(), eligible, "{error:#}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_joins_helper_before_returning() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let body = format!("echo $$ > '{}'; exec sleep 30", pid_file.display());
|
||||
let path = fixture(&dir, &credential, &body);
|
||||
let envs = HashMap::new();
|
||||
let launcher = GuiHelperLauncher {
|
||||
program: path,
|
||||
envs: Some(&envs),
|
||||
credential: &credential,
|
||||
gui_version: None,
|
||||
};
|
||||
let cancellation = CancellationToken::new();
|
||||
let attempt = launcher.launch(&cancellation);
|
||||
tokio::pin!(attempt);
|
||||
tokio::select! {
|
||||
result = &mut attempt => panic!("helper exited early: {result:?}"),
|
||||
_ = async { while !pid_file.exists() { tokio::time::sleep(std::time::Duration::from_millis(10)).await; } } => {}
|
||||
}
|
||||
cancellation.cancel();
|
||||
assert!(attempt.await.is_err());
|
||||
let pid: i32 = fs::read_to_string(pid_file).unwrap().trim().parse().unwrap();
|
||||
assert_eq!(
|
||||
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
|
||||
Err(nix::errno::Errno::ESRCH)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,18 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
process::{ExitStatus, Stdio},
|
||||
process::ExitStatus,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
|
||||
pub struct GuiLauncher<'a> {
|
||||
version: &'a str,
|
||||
programs: Vec<PathBuf>,
|
||||
@@ -51,16 +50,26 @@ impl<'a> GuiLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
if let Some(program) = self.find_compatible_program().await {
|
||||
return self.launch_program(&program).await;
|
||||
pub(crate) async fn resolve_program(&self, cancellation: &CancellationToken) -> anyhow::Result<PathBuf> {
|
||||
anyhow::ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
if let Some(program) = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
|
||||
result = self.find_compatible_program() => result,
|
||||
} {
|
||||
return Ok(program);
|
||||
}
|
||||
|
||||
self.download_program().await?;
|
||||
|
||||
self.download_program(cancellation).await?;
|
||||
let program = binary_paths::gpgui_update_target();
|
||||
self.check_version(&program).await?;
|
||||
self.launch_program(&program).await
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
|
||||
result = self.check_version(&program) => result?,
|
||||
}
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
async fn find_compatible_program(&self) -> Option<PathBuf> {
|
||||
@@ -77,39 +86,28 @@ impl<'a> GuiLauncher<'a> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn launch_program(&self, program: &Path) -> anyhow::Result<ExitStatus> {
|
||||
pub(crate) async fn launch_program(
|
||||
&self,
|
||||
program: &Path,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new(program);
|
||||
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
cmd.env_clear().envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
}
|
||||
|
||||
info!("Launching gpgui");
|
||||
let mut non_root_cmd = cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
|
||||
};
|
||||
|
||||
let Some(mut stdin) = child.stdin.take() else {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
|
||||
Ok(exit_status)
|
||||
super::desktop_child::launch_desktop_child(
|
||||
"gpgui",
|
||||
cmd.into_std(),
|
||||
self.envs.as_ref(),
|
||||
&self.credential,
|
||||
cancellation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn check_version(&self, program: &Path) -> anyhow::Result<()> {
|
||||
@@ -118,8 +116,8 @@ impl<'a> GuiLauncher<'a> {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
}
|
||||
cmd.arg("--version");
|
||||
let output = cmd.into_non_root()?.output().await?;
|
||||
cmd.kill_on_drop(true).arg("--version");
|
||||
let output = cmd.output().await?;
|
||||
if !output.status.success() {
|
||||
bail!("Version command exited with {}", output.status);
|
||||
}
|
||||
@@ -139,13 +137,13 @@ impl<'a> GuiLauncher<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn download_program(&self) -> anyhow::Result<()> {
|
||||
async fn download_program(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
let gui_helper = GuiHelperLauncher::new(&self.credential);
|
||||
|
||||
gui_helper
|
||||
.envs(self.envs.as_ref())
|
||||
.gui_version(Some(self.version))
|
||||
.launch()
|
||||
.launch(cancellation)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -183,6 +181,95 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn captures_gui_logs_in_the_desktop_log_file_across_restarts() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let log_file = dir.path().join("desktop.log");
|
||||
fs::write(&log_file, "[gpservice] started\n").unwrap();
|
||||
let program = dir.path().join("gui");
|
||||
let launcher = launcher(VERSION, vec![]).envs(HashMap::from([(
|
||||
"GP_LOG_FILE".to_owned(),
|
||||
log_file.to_str().unwrap().to_owned(),
|
||||
)]));
|
||||
let frame_len = launcher.credential.encode_frame().unwrap().len();
|
||||
// Consume the credential frame like the real GUI before exiting.
|
||||
fs::write(
|
||||
&program,
|
||||
format!(
|
||||
"#!/bin/sh\ndd bs=1 count={frame_len} of=/dev/null 2>/dev/null || exit 1\nprintf '[gpgui] initialized\\n' >&2\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(
|
||||
launcher
|
||||
.launch_program(&program, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
launcher
|
||||
.launch_program(&program, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(log_file).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpgui] initialized\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_stops_a_hung_version_probe_before_other_candidates() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let pid_file = dir.path().join("version.pid");
|
||||
let next_marker = dir.path().join("next-probe");
|
||||
let first = dir.path().join("hung");
|
||||
let second = dir.path().join("next");
|
||||
fs::write(
|
||||
&first,
|
||||
format!("#!/bin/sh\necho $$ > '{}'; exec sleep 30\n", pid_file.display()),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
&second,
|
||||
format!(
|
||||
"#!/bin/sh\ntouch '{}'; echo 'gpgui test-version'\n",
|
||||
next_marker.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
for path in [&first, &second] {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let launcher = launcher(VERSION, vec![first, second]);
|
||||
let cancellation = CancellationToken::new();
|
||||
let attempt = launcher.resolve_program(&cancellation);
|
||||
tokio::pin!(attempt);
|
||||
tokio::select! {
|
||||
result = &mut attempt => panic!("version probe exited early: {result:?}"),
|
||||
ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while !pid_file.exists() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
}) => ready.unwrap(),
|
||||
}
|
||||
cancellation.cancel();
|
||||
assert!(attempt.await.unwrap_err().to_string().contains("cancelled"));
|
||||
assert!(!next_marker.exists());
|
||||
let pid: i32 = fs::read_to_string(pid_file).unwrap().trim().parse().unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None).is_ok() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prefers_the_first_compatible_program() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
mod command_runner;
|
||||
mod command_traits;
|
||||
mod desktop_child;
|
||||
mod desktop_session_env;
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
pub mod desktop_launcher;
|
||||
pub mod gui_launcher;
|
||||
pub mod service_launcher;
|
||||
pub mod users;
|
||||
|
||||
pub mod collection;
|
||||
|
||||
pub mod rendering_recovery;
|
||||
@@ -0,0 +1,189 @@
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("WebKit Wayland rendering process exited with {status}")]
|
||||
pub struct RenderingCrash {
|
||||
pub status: ExitStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Rendering recovery failed: {0:#}. Collect diagnostics for a bug report")]
|
||||
pub struct RecoveryFailed(#[source] anyhow::Error);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RecoveryState {
|
||||
first_failure: Option<String>,
|
||||
}
|
||||
|
||||
impl RecoveryState {
|
||||
pub fn dmabuf_disabled(&self) -> bool {
|
||||
self.first_failure.is_some()
|
||||
}
|
||||
|
||||
pub fn recover(&mut self, error: &anyhow::Error) -> bool {
|
||||
if self.first_failure.is_none() && error.downcast_ref::<RenderingCrash>().is_some() {
|
||||
self.first_failure = Some(error.to_string());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error {
|
||||
if error.downcast_ref::<crate::auth::AuthenticationCancelled>().is_some()
|
||||
|| error.downcast_ref::<RecoveryFailed>().is_some()
|
||||
{
|
||||
return error;
|
||||
}
|
||||
match &self.first_failure {
|
||||
Some(first) => RecoveryFailed(error.context(format!("First attempt: {first}"))).into(),
|
||||
None => error,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish<T>(&self, result: anyhow::Result<T>) -> anyhow::Result<T> {
|
||||
result.map_err(|error| self.terminal(error))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15))
|
||||
}
|
||||
|
||||
pub fn eligible(command: &Command) -> bool {
|
||||
eligible_with_inheritance(command, true)
|
||||
}
|
||||
|
||||
pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bool {
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))
|
||||
&& effective_env(command, "WAYLAND_DISPLAY", inherits).is_some_and(|value| !value.is_empty())
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
}
|
||||
|
||||
fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ffi::OsString> {
|
||||
for (name, value) in command.get_envs() {
|
||||
if name == key {
|
||||
return value.map(ToOwned::to_owned);
|
||||
}
|
||||
}
|
||||
inherits.then(|| std::env::var_os(key)).flatten()
|
||||
}
|
||||
|
||||
/// Observes diagnostic lines without retaining arbitrary application output.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StderrDiagnostic {
|
||||
line: Vec<u8>,
|
||||
overflow: bool,
|
||||
matched: bool,
|
||||
}
|
||||
|
||||
impl StderrDiagnostic {
|
||||
pub(crate) fn push(&mut self, bytes: &[u8]) {
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
self.check_line();
|
||||
self.line.clear();
|
||||
self.overflow = false;
|
||||
} else if self.line.len() < 1024 {
|
||||
self.line.push(byte);
|
||||
} else {
|
||||
self.overflow = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_line(&mut self) {
|
||||
let line = self.line.as_slice();
|
||||
if !self.overflow
|
||||
&& (line.starts_with(b"Gdk-Message:")
|
||||
|| line.starts_with(b"(gpgui:")
|
||||
|| line.starts_with(b"(gpauth:")
|
||||
|| line.starts_with(b"(gpgui-helper:"))
|
||||
&& line.windows(b"Gdk-Message:".len()).any(|part| part == b"Gdk-Message:")
|
||||
&& line.strip_suffix(b"\r").unwrap_or(line).ends_with(DIAGNOSTIC)
|
||||
{
|
||||
self.matched = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn matched(&mut self) -> bool {
|
||||
self.check_line();
|
||||
self.matched
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_split_diagnostic_without_matching_quoted_warning() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(b"warning: Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display\n");
|
||||
assert!(!observer.matched());
|
||||
observer.push(b"Gdk-Message: 12:00:00: Error 71 (Protocol error) dispat");
|
||||
observer.push(b"ching to Wayland display\n");
|
||||
assert!(observer.matched());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_lines_do_not_grow_or_match() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(&vec![b'x'; 100_000]);
|
||||
assert_eq!(observer.line.len(), 1024);
|
||||
observer.push(DIAGNOSTIC);
|
||||
assert!(!observer.matched());
|
||||
}
|
||||
#[test]
|
||||
fn respects_explicit_overrides_and_x11_environment() {
|
||||
let mut command = Command::new("fixture");
|
||||
command.env_clear().env("WAYLAND_DISPLAY", "wayland-0");
|
||||
let platform = cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
|
||||
assert_eq!(eligible_with_inheritance(&command, false), platform);
|
||||
for value in ["", "0", "1"] {
|
||||
command.env(DMABUF, value);
|
||||
assert!(!eligible_with_inheritance(&command, false));
|
||||
}
|
||||
command
|
||||
.env_remove(DMABUF)
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env("DISPLAY", ":0");
|
||||
assert!(!eligible_with_inheritance(&command, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let mut recovery = RecoveryState::default();
|
||||
let first = RenderingCrash {
|
||||
status: ExitStatus::from_raw(71 << 8),
|
||||
}
|
||||
.into();
|
||||
assert!(recovery.recover(&first));
|
||||
assert!(!recovery.recover(&first));
|
||||
assert!(
|
||||
recovery
|
||||
.terminal(crate::auth::AuthenticationCancelled.into())
|
||||
.downcast_ref::<crate::auth::AuthenticationCancelled>()
|
||||
.is_some()
|
||||
);
|
||||
let error = recovery.terminal(anyhow::anyhow!("second exit 72"));
|
||||
assert!(error.downcast_ref::<RecoveryFailed>().is_some());
|
||||
assert!(error.to_string().contains("71"));
|
||||
assert!(error.to_string().contains("second exit 72"));
|
||||
}
|
||||
#[test]
|
||||
fn explicit_termination_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
for signal in [1, 2, 9, 15] {
|
||||
assert!(!is_crash_exit(ExitStatus::from_raw(signal)));
|
||||
}
|
||||
assert!(is_crash_exit(ExitStatus::from_raw(6)));
|
||||
assert!(is_crash_exit(ExitStatus::from_raw(71 << 8)));
|
||||
assert!(!is_crash_exit(ExitStatus::from_raw(0)));
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
path::PathBuf,
|
||||
process::{ExitStatus, Stdio},
|
||||
};
|
||||
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
|
||||
pub struct ServiceLauncher<'a> {
|
||||
program: PathBuf,
|
||||
minimized: bool,
|
||||
env_file: Option<String>,
|
||||
log_file: Option<String>,
|
||||
verbose: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl Default for ServiceLauncher<'_> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ServiceLauncher<'a> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
program: binary_paths::gpservice(),
|
||||
minimized: false,
|
||||
env_file: None,
|
||||
log_file: None,
|
||||
verbose: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn minimized(mut self, minimized: bool) -> Self {
|
||||
self.minimized = minimized;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn env_file(mut self, env_file: &str) -> Self {
|
||||
self.env_file = Some(env_file.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn log_file(mut self, log_file: &str) -> Self {
|
||||
self.log_file = Some(log_file.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new_pkexec(&self.program);
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
}
|
||||
|
||||
if let Some(env_file) = &self.env_file {
|
||||
cmd.arg("--env-file").arg(env_file);
|
||||
}
|
||||
|
||||
if let Some(verbose) = self.verbose {
|
||||
cmd.arg(verbose);
|
||||
}
|
||||
|
||||
if let Some(log_file) = &self.log_file {
|
||||
let log_file = File::create(log_file)?;
|
||||
let stdio = Stdio::from(log_file);
|
||||
cmd.stderr(stdio);
|
||||
}
|
||||
|
||||
let exit_status = cmd.kill_on_drop(true).spawn()?.wait().await?;
|
||||
|
||||
Ok(exit_status)
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,9 @@ use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
hip::HipSource,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
session::ConnectionPlan,
|
||||
};
|
||||
|
||||
use super::vpn_state::ConnectInfo;
|
||||
@@ -58,8 +58,9 @@ impl LaunchGuiRequest {
|
||||
|
||||
#[derive(Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectArgs {
|
||||
cookie: String,
|
||||
vpnc_script: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
ignore_tls_errors: bool,
|
||||
|
||||
user_agent: Option<String>,
|
||||
os: Option<ClientOs>,
|
||||
@@ -87,10 +88,11 @@ pub struct ConnectArgs {
|
||||
}
|
||||
|
||||
impl ConnectArgs {
|
||||
pub fn new(cookie: String) -> Self {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
cookie,
|
||||
vpnc_script: None,
|
||||
host_identity: None,
|
||||
ignore_tls_errors: false,
|
||||
user_agent: None,
|
||||
os: None,
|
||||
os_version: None,
|
||||
@@ -113,8 +115,12 @@ impl ConnectArgs {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie(&self) -> &str {
|
||||
&self.cookie
|
||||
pub fn host_identity(&self) -> Option<&HostIdentity> {
|
||||
self.host_identity.as_ref()
|
||||
}
|
||||
|
||||
pub fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
pub fn vpnc_script(&self) -> Option<String> {
|
||||
@@ -213,7 +219,6 @@ impl ConnectArgs {
|
||||
impl fmt::Debug for ConnectArgs {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ConnectArgs")
|
||||
.field("cookie", &"<redacted>")
|
||||
.field("vpnc_script", &self.vpnc_script)
|
||||
.field(
|
||||
"client_auth_path",
|
||||
@@ -235,7 +240,6 @@ impl fmt::Debug for ConnectArgs {
|
||||
|
||||
impl Drop for ConnectArgs {
|
||||
fn drop(&mut self) {
|
||||
self.cookie.zeroize();
|
||||
self.key_password.zeroize();
|
||||
self.certificate_data.zeroize();
|
||||
self.sslkey_data.zeroize();
|
||||
@@ -245,14 +249,16 @@ impl Drop for ConnectArgs {
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectRequest {
|
||||
info: ConnectInfo,
|
||||
plan: ConnectionPlan,
|
||||
args: ConnectArgs,
|
||||
}
|
||||
|
||||
impl ConnectRequest {
|
||||
pub fn new(info: ConnectInfo, cookie: String) -> Self {
|
||||
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
|
||||
Self {
|
||||
info,
|
||||
args: ConnectArgs::new(cookie),
|
||||
plan,
|
||||
args: ConnectArgs::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,6 +273,7 @@ impl ConnectRequest {
|
||||
}
|
||||
|
||||
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
|
||||
self.args.host_identity = Some(profile.host_identity().clone());
|
||||
self.args.os = Some(profile.client_os());
|
||||
self.args.os_version = Some(profile.os_version().to_string());
|
||||
self.args.client_version = Some(profile.client_version().to_string());
|
||||
@@ -275,6 +282,11 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
|
||||
self.args.ignore_tls_errors = ignore_tls_errors;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
|
||||
self.args.certificate = certificate.into();
|
||||
self
|
||||
@@ -340,8 +352,8 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn gateway(&self) -> &Gateway {
|
||||
self.info.gateway()
|
||||
pub fn plan(&self) -> &ConnectionPlan {
|
||||
&self.plan
|
||||
}
|
||||
|
||||
pub fn info(&self) -> &ConnectInfo {
|
||||
@@ -370,6 +382,7 @@ pub struct UpdateLogLevelRequest(pub String);
|
||||
pub enum WsRequest {
|
||||
Connect(Box<ConnectRequest>),
|
||||
Disconnect(DisconnectRequest),
|
||||
StopNonTunnelAttachment { connection_id: uuid::Uuid },
|
||||
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
|
||||
PreviewHipReport(PreviewHipReportRequest),
|
||||
GetHipApprovalStatus { approval_id: String },
|
||||
@@ -393,17 +406,52 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::os_profile::OsProfileBuilder;
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy},
|
||||
};
|
||||
|
||||
fn test_request(info: ConnectInfo) -> ConnectRequest {
|
||||
let plan = ConnectionPlan::new(
|
||||
vec![AuthenticatedGateway {
|
||||
gateway: info.gateway().clone(),
|
||||
binding: Some(crate::session::network::test_binding()),
|
||||
authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into())
|
||||
.unwrap(),
|
||||
}],
|
||||
vec![],
|
||||
InternalSessionPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
ConnectRequest::new(info, plan)
|
||||
}
|
||||
|
||||
fn test_connect_info() -> ConnectInfo {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_request_round_trips_a_validated_plan_and_rejects_cookie_only_wire_input() {
|
||||
let request = test_request(test_connect_info());
|
||||
let mut value = serde_json::to_value(&request).unwrap();
|
||||
assert!(value["args"].get("cookie").is_none());
|
||||
let decoded: ConnectRequest = serde_json::from_value(value.clone()).unwrap();
|
||||
assert_eq!(decoded.plan().members().len(), 1);
|
||||
assert_eq!(decoded.plan().members()[0].authentication.connection_type(), "tunnel");
|
||||
value["plan"]["members"] = json!([]);
|
||||
assert!(serde_json::from_value::<ConnectRequest>(value).is_err());
|
||||
let mut legacy = serde_json::to_value(&request).unwrap();
|
||||
legacy.as_object_mut().unwrap().remove("plan");
|
||||
legacy["args"]["cookie"] = json!("authcookie=secret-cookie&user=user");
|
||||
assert!(serde_json::from_value::<ConnectRequest>(legacy).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_request_serializes_allow_extend_session() {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
|
||||
let req = test_request(info).with_allow_extend_session(true);
|
||||
let value = serde_json::to_value(req).unwrap();
|
||||
|
||||
assert_eq!(value["args"]["allowExtendSession"], json!(true));
|
||||
@@ -413,7 +461,7 @@ mod tests {
|
||||
fn with_os_profile_sets_user_agent_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
|
||||
|
||||
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
|
||||
let req = test_request(test_connect_info()).with_os_profile(&profile);
|
||||
|
||||
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
|
||||
}
|
||||
@@ -422,7 +470,7 @@ mod tests {
|
||||
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
|
||||
|
||||
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
|
||||
let req = test_request(test_connect_info()).with_os_profile(&profile);
|
||||
|
||||
assert_eq!(
|
||||
req.args().host_id(),
|
||||
@@ -432,7 +480,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn client_identity_data_round_trips_without_debug_disclosure() {
|
||||
let req = ConnectRequest::new(test_connect_info(), "secret-cookie".to_string())
|
||||
let req = test_request(test_connect_info())
|
||||
.with_certificate_data(Some(b"certificate".to_vec()))
|
||||
.with_sslkey_data(Some(b"private-key".to_vec()));
|
||||
let encoded = serde_json::to_vec(&req).unwrap();
|
||||
|
||||
@@ -167,7 +167,21 @@ mod tests {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
|
||||
let request = ConnectRequest::new(info, "cookie".to_string())
|
||||
let plan = crate::session::ConnectionPlan::new(
|
||||
vec![crate::session::AuthenticatedGateway {
|
||||
gateway: info.gateway().clone(),
|
||||
binding: Some(crate::session::network::test_binding()),
|
||||
authentication: crate::session::GatewayAuthentication::new(
|
||||
"authcookie=token&user=user".into(),
|
||||
"tunnel".into(),
|
||||
)
|
||||
.unwrap(),
|
||||
}],
|
||||
vec![],
|
||||
crate::session::InternalSessionPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let request = ConnectRequest::new(info, plan)
|
||||
.with_certificate_data(Some(vec![b'c'; certificate_size]))
|
||||
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
|
||||
let message = ClientMessage::Request {
|
||||
|
||||
@@ -17,3 +17,7 @@ pub const HIP_PROTOCOL_VERSION: u16 = 1;
|
||||
pub const MAX_PLAINTEXT: usize = 60 * 1024;
|
||||
pub const MAX_WS_MESSAGE: usize = u16::MAX as usize;
|
||||
pub const MAX_SERVICE_MESSAGE: usize = 256;
|
||||
|
||||
/// Private desktop control messages; never carry credentials.
|
||||
pub const DESKTOP_GUI_EXITED: u8 = 0;
|
||||
pub const DESKTOP_RENDERING_RETRY: u8 = 1;
|
||||
@@ -3,7 +3,10 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::{gateway::Gateway, session::SessionInfo};
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectInfo {
|
||||
@@ -18,6 +21,8 @@ pub struct ConnectedInfo {
|
||||
info: Box<ConnectInfo>,
|
||||
session_info: Option<SessionInfo>,
|
||||
connected_at: u32,
|
||||
members: Vec<GatewaySessionSummary>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
}
|
||||
|
||||
impl ConnectedInfo {
|
||||
@@ -26,9 +31,25 @@ impl ConnectedInfo {
|
||||
info: Box::new(info),
|
||||
session_info,
|
||||
connected_at: unix_timestamp(),
|
||||
members: vec![],
|
||||
failures: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_members(mut self, members: Vec<GatewaySessionSummary>, failures: Vec<GatewayFailureSummary>) -> Self {
|
||||
self.members = members;
|
||||
self.failures = failures;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn members(&self) -> &[GatewaySessionSummary] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
pub fn failures(&self) -> &[GatewayFailureSummary] {
|
||||
&self.failures
|
||||
}
|
||||
|
||||
pub fn info(&self) -> &ConnectInfo {
|
||||
&self.info
|
||||
}
|
||||
@@ -67,6 +88,7 @@ impl ConnectInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VpnState {
|
||||
Disconnected,
|
||||
Failed(String),
|
||||
Connecting(Box<ConnectInfo>),
|
||||
Connected(Box<ConnectedInfo>),
|
||||
Disconnecting,
|
||||
|
||||
@@ -4,6 +4,14 @@ use chrono::{Local, TimeZone};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
mod connection;
|
||||
mod gateway_sessions;
|
||||
pub mod network;
|
||||
pub mod non_tunnel;
|
||||
pub mod transport;
|
||||
pub use connection::*;
|
||||
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct SessionWarning {
|
||||
pub prior_secs: u32,
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
use std::{fmt, time::Duration};
|
||||
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::gateway::Gateway;
|
||||
|
||||
/// Network location and session mode are independent: an internal gateway can
|
||||
/// still require a tunnel.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionMode {
|
||||
Tunnel,
|
||||
NonTunnel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MaintenanceState {
|
||||
Authenticated,
|
||||
Healthy,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GatewaySessionSummary {
|
||||
pub gateway: Gateway,
|
||||
pub mode: SessionMode,
|
||||
pub client_ip: Option<String>,
|
||||
pub client_ipv6: Option<String>,
|
||||
pub maintenance: MaintenanceState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionEndReason {
|
||||
InvalidCookie,
|
||||
NetworkChanged,
|
||||
AllMembersFailed,
|
||||
AuthorizationRevoked,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "GatewayAuthenticationFields")]
|
||||
pub struct GatewayAuthentication {
|
||||
cookie: String,
|
||||
connection_type: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GatewayAuthenticationFields {
|
||||
cookie: String,
|
||||
connection_type: String,
|
||||
}
|
||||
|
||||
impl TryFrom<GatewayAuthenticationFields> for GatewayAuthentication {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: GatewayAuthenticationFields) -> Result<Self, Self::Error> {
|
||||
Self::new(fields.cookie, fields.connection_type)
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayAuthentication {
|
||||
pub fn new(cookie: String, connection_type: String) -> anyhow::Result<Self> {
|
||||
let authentication = Self {
|
||||
cookie,
|
||||
connection_type,
|
||||
};
|
||||
ensure!(
|
||||
!authentication.cookie.is_empty() && authentication.cookie.len() <= 64 * 1024,
|
||||
"Gateway authentication cookie is missing or too large"
|
||||
);
|
||||
let params = url::form_urlencoded::parse(authentication.cookie.as_bytes()).collect::<Vec<_>>();
|
||||
for key in ["authcookie", "user"] {
|
||||
let mut values = params.iter().filter(|(name, _)| name == key).map(|(_, value)| value);
|
||||
ensure!(
|
||||
values.next().is_some_and(|value| !value.is_empty()) && values.next().is_none(),
|
||||
"Gateway authentication requires one nonempty {key}"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!authentication.connection_type.trim().is_empty()
|
||||
&& authentication.connection_type != "(null)"
|
||||
&& authentication.connection_type != "-1",
|
||||
"Gateway connection type is missing"
|
||||
);
|
||||
Ok(authentication)
|
||||
}
|
||||
|
||||
pub fn cookie(&self) -> &str {
|
||||
&self.cookie
|
||||
}
|
||||
|
||||
pub fn connection_type(&self) -> &str {
|
||||
&self.connection_type
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> SessionMode {
|
||||
if self.connection_type == "tunnel" {
|
||||
SessionMode::Tunnel
|
||||
} else {
|
||||
SessionMode::NonTunnel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for GatewayAuthentication {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("GatewayAuthentication")
|
||||
.field("cookie", &"<redacted>")
|
||||
.field("mode", &self.mode())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for GatewayAuthentication {
|
||||
fn drop(&mut self) {
|
||||
self.cookie.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", try_from = "InternalSessionPolicyFields")]
|
||||
pub struct InternalSessionPolicy {
|
||||
hip_interval_secs: u32,
|
||||
collect_hip_data: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct InternalSessionPolicyFields {
|
||||
hip_interval_secs: u32,
|
||||
collect_hip_data: bool,
|
||||
}
|
||||
|
||||
impl TryFrom<InternalSessionPolicyFields> for InternalSessionPolicy {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: InternalSessionPolicyFields) -> Result<Self, Self::Error> {
|
||||
Self::new(fields.hip_interval_secs, fields.collect_hip_data)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct AuthenticatedGateway {
|
||||
pub gateway: Gateway,
|
||||
pub authentication: GatewayAuthentication,
|
||||
pub binding: Option<super::network::GatewayBinding>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GatewayFailure {
|
||||
AuthenticationRejected,
|
||||
Unreachable,
|
||||
TunnelFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct GatewayFailureSummary {
|
||||
pub gateway: Gateway,
|
||||
pub failure: GatewayFailure,
|
||||
}
|
||||
|
||||
/// Credentials remain in the interactive authentication owner; only issued
|
||||
/// gateway cookies cross the runtime/service boundary.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "ConnectionPlanFields")]
|
||||
pub struct ConnectionPlan {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<super::network::InternalHostDetection>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ConnectionPlanFields {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<super::network::InternalHostDetection>,
|
||||
}
|
||||
|
||||
impl TryFrom<ConnectionPlanFields> for ConnectionPlan {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: ConnectionPlanFields) -> Result<Self, Self::Error> {
|
||||
Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionPlan {
|
||||
pub fn new(
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
) -> anyhow::Result<Self> {
|
||||
ensure!(!members.is_empty(), "Connection plan has no authenticated gateways");
|
||||
ensure!(
|
||||
members.len() <= 64 && failures.len() <= 64,
|
||||
"Connection plan exceeds its gateway limit"
|
||||
);
|
||||
let mode = members[0].authentication.mode();
|
||||
ensure!(
|
||||
members.iter().all(|member| member.authentication.mode() == mode),
|
||||
"Mixed tunnel and non-tunnel sessions are unsupported"
|
||||
);
|
||||
ensure!(
|
||||
mode != SessionMode::NonTunnel
|
||||
|| members
|
||||
.iter()
|
||||
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
|
||||
"Non-tunnel sessions require freshly discovered internal gateways"
|
||||
);
|
||||
ensure!(
|
||||
members.len() == 1
|
||||
|| members
|
||||
.iter()
|
||||
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
|
||||
"Multiple authenticated gateways require an internal connection"
|
||||
);
|
||||
let mut hosts = std::collections::HashSet::new();
|
||||
for member in &members {
|
||||
if mode == SessionMode::NonTunnel {
|
||||
let binding = member
|
||||
.binding
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Non-tunnel session has no physical binding"))?;
|
||||
binding.validate_server(member.gateway.server())?;
|
||||
}
|
||||
let host = crate::utils::normalize_server(member.gateway.server())?;
|
||||
ensure!(hosts.insert(host), "Connection plan has duplicate gateways");
|
||||
}
|
||||
Ok(Self {
|
||||
members,
|
||||
failures,
|
||||
policy,
|
||||
internal_detection: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn members(&self) -> &[AuthenticatedGateway] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
pub fn failures(&self) -> &[GatewayFailureSummary] {
|
||||
&self.failures
|
||||
}
|
||||
|
||||
pub fn policy(&self) -> InternalSessionPolicy {
|
||||
self.policy
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> SessionMode {
|
||||
self.members[0].authentication.mode()
|
||||
}
|
||||
|
||||
pub fn with_internal_detection(mut self, detection: Option<super::network::InternalHostDetection>) -> Self {
|
||||
self.internal_detection = detection;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn internal_detection(&self) -> Option<&super::network::InternalHostDetection> {
|
||||
self.internal_detection.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for InternalSessionPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hip_interval_secs: 3600,
|
||||
collect_hip_data: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InternalSessionPolicy {
|
||||
pub fn new(hip_interval_secs: u32, collect_hip_data: bool) -> anyhow::Result<Self> {
|
||||
ensure!(hip_interval_secs > 0, "HIP report interval must be positive");
|
||||
ensure!(
|
||||
hip_interval_secs.checked_mul(1000).is_some(),
|
||||
"HIP report interval exceeds the supported range"
|
||||
);
|
||||
Ok(Self {
|
||||
hip_interval_secs,
|
||||
collect_hip_data,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn hip_interval(&self) -> Duration {
|
||||
Duration::from_secs(u64::from(self.hip_interval_secs))
|
||||
}
|
||||
|
||||
pub fn collect_hip_data(&self) -> bool {
|
||||
self.collect_hip_data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deserialization_enforces_authentication_invariants() {
|
||||
for (cookie, mode) in [
|
||||
("", "tunnel"),
|
||||
("not-a-cookie", "tunnel"),
|
||||
("user=alice", "tunnel"),
|
||||
("authcookie=token", "tunnel"),
|
||||
("authcookie=token&user=alice&user=bob", "tunnel"),
|
||||
("authcookie=token&user=alice", ""),
|
||||
] {
|
||||
let serialized = serde_json::json!({"cookie":cookie, "connection_type":mode});
|
||||
assert!(serde_json::from_value::<GatewayAuthentication>(serialized).is_err());
|
||||
}
|
||||
let auth = GatewayAuthentication::new("authcookie=token&user=alice".into(), "non-tunnel".into()).unwrap();
|
||||
let decoded: GatewayAuthentication = serde_json::from_str(&serde_json::to_string(&auth).unwrap()).unwrap();
|
||||
assert_eq!(decoded.mode(), SessionMode::NonTunnel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialization_enforces_schedule_invariants() {
|
||||
for interval in [0, u32::MAX] {
|
||||
let serialized = serde_json::json!({"hipIntervalSecs":interval,"collectHipData":false});
|
||||
assert!(serde_json::from_value::<InternalSessionPolicy>(serialized).is_err());
|
||||
}
|
||||
let serialized = serde_json::to_string(&InternalSessionPolicy::default()).unwrap();
|
||||
let decoded: InternalSessionPolicy = serde_json::from_str(&serialized).unwrap();
|
||||
assert_eq!(decoded.hip_interval(), Duration::from_secs(3600));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use std::{
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::gateway::Gateway;
|
||||
|
||||
use super::transport::GatewayTransport;
|
||||
|
||||
const LOGOUT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct ClientAddresses {
|
||||
pub ipv4: Option<Ipv4Addr>,
|
||||
pub ipv6: Option<Ipv6Addr>,
|
||||
}
|
||||
|
||||
/// One issued gateway authentication and its original request context. Session
|
||||
/// mode governs execution, while every mode has the same cleanup owner.
|
||||
pub struct GatewaySession {
|
||||
pub gateway: Gateway,
|
||||
pub transport: GatewayTransport,
|
||||
pub addresses: ClientAddresses,
|
||||
}
|
||||
|
||||
/// Owns issued gateway sessions independently of tunnel or HIP setup. Workers
|
||||
/// borrow members; their owner joins them before consuming this ledger in logout.
|
||||
/// This owner is deliberately not Clone: transfer or drain it exactly once.
|
||||
#[derive(Default)]
|
||||
pub struct GatewaySessions {
|
||||
members: Vec<Arc<GatewaySession>>,
|
||||
}
|
||||
|
||||
impl GatewaySessions {
|
||||
pub fn new(members: Vec<GatewaySession>) -> Self {
|
||||
Self {
|
||||
members: members.into_iter().map(Arc::new).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&mut self, session: GatewaySession) {
|
||||
self.members.push(Arc::new(session));
|
||||
}
|
||||
|
||||
pub(crate) fn update(&mut self, session: GatewaySession) {
|
||||
if let Some(member) = self
|
||||
.members
|
||||
.iter_mut()
|
||||
.find(|member| member.gateway.server() == session.gateway.server())
|
||||
{
|
||||
*member = Arc::new(session);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.members.is_empty()
|
||||
}
|
||||
|
||||
/// Consume the local cleanup copies only after another owner has proved it
|
||||
/// acquired responsibility for these issued sessions.
|
||||
pub fn relinquish(self) {}
|
||||
|
||||
pub fn members(&self) -> &[Arc<GatewaySession>] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
/// Transfer a selected tunnel login to OpenConnect immediately before its
|
||||
/// native worker starts. OpenConnect owns the live reconnect cookie and logout.
|
||||
pub fn relinquish_gateway(&mut self, server: &str) {
|
||||
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
|
||||
self.members.remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// Call only after this member's worker has joined. Removing ownership before
|
||||
/// awaiting logout prevents routine final cleanup from repeating the request.
|
||||
pub async fn logout_gateway(&mut self, server: &str) {
|
||||
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
|
||||
logout(self.members.remove(index)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn logout(self) {
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for session in self.members {
|
||||
workers.spawn(logout(session));
|
||||
}
|
||||
while let Some(result) = workers.join_next().await {
|
||||
if let Err(error) = result {
|
||||
log::warn!("Gateway cleanup worker failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn logout(session: Arc<GatewaySession>) {
|
||||
match tokio::time::timeout(LOGOUT_TIMEOUT, session.transport.logout()).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => log::warn!("Gateway logout failed: {error}"),
|
||||
Err(_) => log::warn!("Gateway logout timed out"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use super::super::ClientAddresses;
|
||||
|
||||
/// Physical network context bound to the authenticated non-tunnel endpoint. Wire input is validated;
|
||||
/// runtime transports use this context without performing another DNS lookup.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "BindingFields", rename_all = "camelCase")]
|
||||
pub struct GatewayBinding {
|
||||
endpoint: SocketAddr,
|
||||
source: SocketAddr,
|
||||
interface: String,
|
||||
interface_index: u32,
|
||||
addresses: ClientAddresses,
|
||||
network_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct BindingFields {
|
||||
endpoint: SocketAddr,
|
||||
source: SocketAddr,
|
||||
interface: String,
|
||||
interface_index: u32,
|
||||
addresses: ClientAddresses,
|
||||
network_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
impl TryFrom<BindingFields> for GatewayBinding {
|
||||
type Error = anyhow::Error;
|
||||
fn try_from(fields: BindingFields) -> Result<Self, Self::Error> {
|
||||
Self::new(
|
||||
fields.endpoint,
|
||||
fields.source,
|
||||
fields.interface,
|
||||
fields.interface_index,
|
||||
fields.addresses,
|
||||
fields.network_fingerprint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayBinding {
|
||||
pub fn new(
|
||||
endpoint: SocketAddr,
|
||||
source: SocketAddr,
|
||||
interface: String,
|
||||
interface_index: u32,
|
||||
addresses: ClientAddresses,
|
||||
network_fingerprint: impl Into<Option<String>>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let network_fingerprint = network_fingerprint.into();
|
||||
ensure!(
|
||||
network_fingerprint
|
||||
.as_ref()
|
||||
.is_none_or(|value| value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())),
|
||||
"Physical network fingerprint is invalid"
|
||||
);
|
||||
ensure!(
|
||||
endpoint.port() != 0 && !endpoint.ip().is_unspecified() && !endpoint.ip().is_multicast(),
|
||||
"Gateway endpoint is invalid"
|
||||
);
|
||||
ensure!(
|
||||
source.port() == 0 && !source.ip().is_unspecified() && !source.ip().is_multicast(),
|
||||
"Gateway source is invalid"
|
||||
);
|
||||
ensure!(
|
||||
endpoint.is_ipv4() == source.is_ipv4(),
|
||||
"Gateway address families differ"
|
||||
);
|
||||
ensure!(
|
||||
!interface.is_empty() && interface.len() < 64 && !interface.contains('\0') && interface_index != 0,
|
||||
"Gateway interface is invalid"
|
||||
);
|
||||
for address in [endpoint, source] {
|
||||
if let SocketAddr::V6(address) = address {
|
||||
ensure!(address.flowinfo() == 0, "Gateway IPv6 flow information is invalid");
|
||||
ensure!(
|
||||
address.scope_id() == 0 || address.scope_id() == interface_index,
|
||||
"Gateway IPv6 scope differs from its interface"
|
||||
);
|
||||
ensure!(
|
||||
!address.ip().is_unicast_link_local() || address.scope_id() == interface_index,
|
||||
"Gateway IPv6 scope is missing"
|
||||
);
|
||||
}
|
||||
}
|
||||
match source.ip() {
|
||||
IpAddr::V4(ip) => ensure!(
|
||||
addresses.ipv4 == Some(ip),
|
||||
"Gateway IPv4 source differs from its identity"
|
||||
),
|
||||
IpAddr::V6(ip) => ensure!(
|
||||
addresses.ipv6 == Some(ip),
|
||||
"Gateway IPv6 source differs from its identity"
|
||||
),
|
||||
}
|
||||
Ok(Self {
|
||||
endpoint,
|
||||
source,
|
||||
interface,
|
||||
interface_index,
|
||||
addresses,
|
||||
network_fingerprint,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn endpoint(&self) -> SocketAddr {
|
||||
self.endpoint
|
||||
}
|
||||
pub fn source(&self) -> SocketAddr {
|
||||
self.source
|
||||
}
|
||||
pub fn interface(&self) -> &str {
|
||||
&self.interface
|
||||
}
|
||||
pub fn interface_index(&self) -> u32 {
|
||||
self.interface_index
|
||||
}
|
||||
pub fn addresses(&self) -> ClientAddresses {
|
||||
self.addresses
|
||||
}
|
||||
|
||||
pub fn network_fingerprint(&self) -> Option<&str> {
|
||||
self.network_fingerprint.as_deref()
|
||||
}
|
||||
|
||||
pub fn validate_server(&self, server: &str) -> anyhow::Result<()> {
|
||||
let origin = super::super::transport::gateway_origin(server)?;
|
||||
ensure!(
|
||||
origin.port_or_known_default() == Some(self.endpoint.port()),
|
||||
"Gateway endpoint port differs"
|
||||
);
|
||||
let literal = match origin.host() {
|
||||
Some(url::Host::Ipv4(ip)) => Some(IpAddr::V4(ip)),
|
||||
Some(url::Host::Ipv6(ip)) => Some(IpAddr::V6(ip)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(ip) = literal {
|
||||
ensure!(self.endpoint.ip() == ip, "Literal gateway endpoint differs");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ipv4_binding() -> GatewayBinding {
|
||||
GatewayBinding::new(
|
||||
"192.0.2.10:443".parse().unwrap(),
|
||||
"192.0.2.5:0".parse().unwrap(),
|
||||
"fixture".into(),
|
||||
7,
|
||||
ClientAddresses {
|
||||
ipv4: Some("192.0.2.5".parse().unwrap()),
|
||||
ipv6: None,
|
||||
},
|
||||
"a".repeat(64),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_input_rejects_inconsistent_network_identity() {
|
||||
let original = serde_json::to_value(ipv4_binding()).unwrap();
|
||||
for (field, value) in [
|
||||
("source", serde_json::json!("192.0.2.6:0")),
|
||||
("source", serde_json::json!("192.0.2.5:1234")),
|
||||
("endpoint", serde_json::json!("[2001:db8::10]:443")),
|
||||
("interfaceIndex", serde_json::json!(0)),
|
||||
("networkFingerprint", serde_json::json!("not-a-fingerprint")),
|
||||
] {
|
||||
let mut invalid = original.clone();
|
||||
invalid[field] = value;
|
||||
assert!(
|
||||
serde_json::from_value::<GatewayBinding>(invalid).is_err(),
|
||||
"accepted {field}"
|
||||
);
|
||||
}
|
||||
assert!(serde_json::from_value::<GatewayBinding>(original).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_local_scope_survives_wire_round_trip_and_must_match_interface() {
|
||||
let addresses = ClientAddresses {
|
||||
ipv4: None,
|
||||
ipv6: Some("fe80::5".parse().unwrap()),
|
||||
};
|
||||
let binding = GatewayBinding::new(
|
||||
"[fe80::10%7]:443".parse().unwrap(),
|
||||
"[fe80::5%7]:0".parse().unwrap(),
|
||||
"fixture".into(),
|
||||
7,
|
||||
addresses,
|
||||
"a".repeat(64),
|
||||
)
|
||||
.unwrap();
|
||||
let value = serde_json::to_value(&binding).unwrap();
|
||||
let restored: GatewayBinding = serde_json::from_value(value.clone()).unwrap();
|
||||
assert_eq!(restored.source(), binding.source());
|
||||
assert_eq!(restored.endpoint(), binding.endpoint());
|
||||
for source in ["[fe80::5]:0", "[fe80::5%8]:0"] {
|
||||
let mut invalid = value.clone();
|
||||
invalid["source"] = serde_json::json!(source);
|
||||
assert!(serde_json::from_value::<GatewayBinding>(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_origin_must_match_endpoint_port_and_literal_address() {
|
||||
let binding = ipv4_binding();
|
||||
assert!(binding.validate_server("gateway.example.com").is_ok());
|
||||
assert!(binding.validate_server("192.0.2.10").is_ok());
|
||||
assert!(binding.validate_server("192.0.2.11").is_err());
|
||||
assert!(binding.validate_server("gateway.example.com:444").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub(super) use super::bsd_routes::routes;
|
||||
use super::*;
|
||||
|
||||
pub(super) fn scope_resolver_socket(
|
||||
_socket: &tokio::net::UdpSocket,
|
||||
_interface: &Interface,
|
||||
_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
// resolv.conf has no per-interface resolver contexts. IPv6 zones are carried
|
||||
// in the destination address instead.
|
||||
anyhow::bail!("Interface-scoped resolver contexts are unsupported on BSD")
|
||||
}
|
||||
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
resolv_conf(control)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos"))]
|
||||
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let mut routes = Vec::new();
|
||||
for family in ["inet", "inet6"] {
|
||||
routes.extend(parse_routes(&command("netstat", &["-rn", "-f", family], control)?)?);
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let mut interface_column = None;
|
||||
let mut routes = Vec::new();
|
||||
for line in contents.lines() {
|
||||
let fields = line.split_whitespace().collect::<Vec<_>>();
|
||||
if fields.first() == Some(&"Destination") {
|
||||
interface_column = Some(
|
||||
fields
|
||||
.iter()
|
||||
.position(|field| matches!(*field, "Netif" | "Iface"))
|
||||
.context("Route table has no interface column")?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let Some(column) = interface_column else {
|
||||
continue;
|
||||
};
|
||||
if fields.len() <= column {
|
||||
continue;
|
||||
}
|
||||
// L/W entries are neighbor-cache or cloned host routes. Their presence,
|
||||
// gateway MAC and expiry depend on traffic and must not cause rediscovery.
|
||||
if fields[2].contains('L') || fields[2].contains('W') {
|
||||
continue;
|
||||
}
|
||||
routes.push(RouteContext {
|
||||
destination: fields[0].into(),
|
||||
gateway: fields[1].into(),
|
||||
interface: fields[column].into(),
|
||||
table: String::new(),
|
||||
metric: String::new(),
|
||||
});
|
||||
}
|
||||
ensure!(interface_column.is_some(), "Route table header is missing");
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn ignores_route_use_expiry_and_platform_column_positions() {
|
||||
let darwin = parse_routes("Routing tables\nInternet:\nDestination Gateway Flags Netif Expire\ndefault 192.0.2.1 UGScg en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHLWI en0 123").unwrap();
|
||||
let bsd = parse_routes("Destination Gateway Flags Refs Use Mtu Netif Expire\ndefault 192.0.2.1 UGS 4 22 1500 en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHL 0 33 1500 en0 99").unwrap();
|
||||
assert_eq!(darwin, bsd);
|
||||
assert_eq!(darwin.len(), 1);
|
||||
assert!(parse_routes("unrecognized table").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "DetectionFields")]
|
||||
pub struct InternalHostDetection {
|
||||
targets: Vec<DetectionTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
struct DetectionTarget {
|
||||
address: IpAddr,
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DetectionFields {
|
||||
targets: Vec<DetectionTarget>,
|
||||
}
|
||||
|
||||
impl TryFrom<DetectionFields> for InternalHostDetection {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: DetectionFields) -> anyhow::Result<Self> {
|
||||
Self::new(
|
||||
fields
|
||||
.targets
|
||||
.into_iter()
|
||||
.map(|target| (target.address, target.hostname))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl InternalHostDetection {
|
||||
pub fn new(targets: Vec<(IpAddr, String)>) -> anyhow::Result<Self> {
|
||||
ensure!(
|
||||
!targets.is_empty() && targets.len() <= 2,
|
||||
"Invalid internal detection target count"
|
||||
);
|
||||
let targets = targets
|
||||
.into_iter()
|
||||
.map(|(address, hostname)| {
|
||||
validate_target(address, &hostname)?;
|
||||
Ok(DetectionTarget { address, hostname })
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
Ok(Self { targets })
|
||||
}
|
||||
|
||||
pub async fn detect(&self, cancellation: &CancellationToken) -> anyhow::Result<bool> {
|
||||
for target in &self.targets {
|
||||
if super::native::detect(target.address, &target.hostname, cancellation).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_target(address: IpAddr, hostname: &str) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!address.is_unspecified() && !address.is_loopback() && !address.is_multicast(),
|
||||
"Invalid internal detection address"
|
||||
);
|
||||
ensure!(
|
||||
!hostname.is_empty()
|
||||
&& hostname.len() <= 253
|
||||
&& hostname.is_ascii()
|
||||
&& hostname
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')),
|
||||
"Invalid internal detection hostname"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detection_inputs_are_retained_and_validated_on_deserialization() {
|
||||
let detection = InternalHostDetection::new(vec![("192.0.2.10".parse().unwrap(), "host.example".into())]).unwrap();
|
||||
let value = serde_json::to_value(&detection).unwrap();
|
||||
assert!(serde_json::from_value::<InternalHostDetection>(value).is_ok());
|
||||
assert!(InternalHostDetection::new(vec![]).is_err());
|
||||
assert!(InternalHostDetection::new(vec![("127.0.0.1".parse().unwrap(), "host.example".into())]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn scope_resolver_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
interface: &Interface,
|
||||
_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
socket2::SockRef::from(socket).bind_device(Some(interface.name.as_bytes()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let mut routes = Vec::new();
|
||||
for family in ["-4", "-6"] {
|
||||
routes.extend(parse_routes(&command(
|
||||
"ip",
|
||||
&[family, "-j", "route", "show", "table", "all"],
|
||||
control,
|
||||
)?)?);
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let value: Vec<serde_json::Value> = serde_json::from_str(contents)?;
|
||||
let mut routes = Vec::new();
|
||||
for route in value {
|
||||
// Kernel cache and neighbor lifetimes are traffic, not network changes.
|
||||
if route.get("cache").is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(interface) = route["dev"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
let field = |name| {
|
||||
route
|
||||
.get(name)
|
||||
.map(|value| value.as_str().map(str::to_owned).unwrap_or_else(|| value.to_string()))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
routes.push(RouteContext {
|
||||
destination: field("dst"),
|
||||
gateway: field("gateway"),
|
||||
interface: interface.into(),
|
||||
table: field("table"),
|
||||
metric: field("metric"),
|
||||
});
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
let path = std::fs::canonicalize("/etc/resolv.conf")?;
|
||||
if path.starts_with("/run/systemd/resolve") {
|
||||
let dns = command("resolvectl", &["dns"], control)?;
|
||||
let domains = command("resolvectl", &["domain"], control)?;
|
||||
return parse_resolved(&dns, &domains);
|
||||
}
|
||||
resolv_conf(control)
|
||||
}
|
||||
|
||||
fn parse_resolved(dns: &str, domains: &str) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
let mut resolvers = std::collections::BTreeMap::<Option<String>, ResolverContext>::new();
|
||||
for (contents, is_dns) in [(dns, true), (domains, false)] {
|
||||
for line in contents.lines().filter(|line| !line.trim().is_empty()) {
|
||||
let (label, values) = line.split_once(':').context("Invalid systemd resolver output")?;
|
||||
let interface = if label == "Global" {
|
||||
None
|
||||
} else {
|
||||
let (_, name) = label.split_once('(').context("Invalid systemd resolver interface")?;
|
||||
Some(
|
||||
name
|
||||
.strip_suffix(')')
|
||||
.context("Invalid systemd resolver interface")?
|
||||
.to_owned(),
|
||||
)
|
||||
};
|
||||
let resolver = resolvers.entry(interface.clone()).or_insert_with(|| ResolverContext {
|
||||
interface,
|
||||
servers: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
});
|
||||
if is_dns {
|
||||
for server in values.split_whitespace() {
|
||||
server
|
||||
.split('%')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.parse::<IpAddr>()
|
||||
.context("Invalid systemd resolver address")?;
|
||||
resolver.servers.push(server.to_owned());
|
||||
}
|
||||
} else {
|
||||
resolver
|
||||
.domains
|
||||
.extend(values.split_whitespace().map(|domain| domain.to_ascii_lowercase()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(resolvers.into_values().collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn route_identity_retains_ipv6_and_ignores_cache() {
|
||||
let routes = parse_routes(r#"[{"dst":"default","gateway":"2001:db8::1","dev":"eth0","metric":600,"table":"main"},{"dst":"2001:db8::5","dev":"eth0","cache":[]}]"#).unwrap();
|
||||
assert_eq!(routes.len(), 1);
|
||||
assert_eq!(routes[0].gateway, "2001:db8::1");
|
||||
assert_eq!(routes[0].metric, "600");
|
||||
}
|
||||
#[test]
|
||||
fn resolved_preserves_interface_domains_and_empty_global_context() {
|
||||
let resolvers = parse_resolved(
|
||||
"Global:\nLink 2 (eth0): 192.0.2.53\n\nLink 3 (tun0): 198.51.100.53\n",
|
||||
"Global:\nLink 2 (eth0): CORP.EXAMPLE\nLink 3 (tun0): ~.\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(resolvers.len(), 3);
|
||||
assert!(
|
||||
resolvers
|
||||
.iter()
|
||||
.any(|resolver| resolver.interface.as_deref() == Some("eth0")
|
||||
&& resolver.domains.iter().any(|domain| domain == "corp.example"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
pub(super) use super::bsd_routes::routes;
|
||||
use super::*;
|
||||
|
||||
pub(super) fn scope_resolver_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
interface: &Interface,
|
||||
endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
let index = std::num::NonZeroU32::new(interface.index).context("Resolver interface index is missing")?;
|
||||
let socket = socket2::SockRef::from(socket);
|
||||
if endpoint.is_ipv4() {
|
||||
socket.bind_device_by_index_v4(Some(index))?;
|
||||
} else {
|
||||
socket.bind_device_by_index_v6(Some(index))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
parse_resolvers(&command("scutil", &["--dns"], control)?)
|
||||
}
|
||||
|
||||
fn parse_resolvers(contents: &str) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
let mut resolvers = Vec::new();
|
||||
let mut current: Option<ResolverContext> = None;
|
||||
for line in contents.lines().map(str::trim) {
|
||||
if line.starts_with("resolver #") {
|
||||
if let Some(resolver) = current.take() {
|
||||
resolvers.push(resolver);
|
||||
}
|
||||
current = Some(ResolverContext {
|
||||
interface: None,
|
||||
servers: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let Some(resolver) = &mut current else {
|
||||
continue;
|
||||
};
|
||||
let Some((field, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let field = field.trim();
|
||||
let value = value.trim();
|
||||
if field.starts_with("nameserver[") {
|
||||
value
|
||||
.split('%')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.parse::<IpAddr>()
|
||||
.context("Invalid macOS resolver address")?;
|
||||
resolver.servers.push(value.to_owned());
|
||||
} else if field == "domain" || field.starts_with("search domain[") {
|
||||
resolver.domains.push(value.to_ascii_lowercase());
|
||||
} else if field == "if_index" {
|
||||
if let Some((_, name)) = value.split_once('(') {
|
||||
resolver.interface = Some(
|
||||
name
|
||||
.strip_suffix(')')
|
||||
.context("Invalid macOS resolver interface")?
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(resolver) = current {
|
||||
resolvers.push(resolver);
|
||||
}
|
||||
Ok(resolvers)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn resolver_identity_is_scoped_and_ignores_reachability_counters() {
|
||||
let a = parse_resolvers(
|
||||
"resolver #1\n nameserver[0] : 192.0.2.53\n if_index : 4 (en0)\n search domain[0] : CORP.EXAMPLE\n reach : 2",
|
||||
)
|
||||
.unwrap();
|
||||
let b = parse_resolvers(
|
||||
"resolver #9\n search domain[0] : corp.example\n if_index : 4 (en0)\n nameserver[0] : 192.0.2.53\n reach : 3",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a[0].interface.as_deref(), Some("en0"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
io,
|
||||
net::{IpAddr, SocketAddr},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use netdev::Interface;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::ClientAddresses;
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
mod bsd;
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos", test))]
|
||||
mod bsd_routes;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
use bsd as platform;
|
||||
#[cfg(target_os = "linux")]
|
||||
use linux as platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos as platform;
|
||||
|
||||
mod binding;
|
||||
mod detection;
|
||||
pub mod native;
|
||||
pub use binding::GatewayBinding;
|
||||
pub use detection::InternalHostDetection;
|
||||
|
||||
const INSPECTION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
struct InterfaceIdentity {
|
||||
index: u32,
|
||||
name: String,
|
||||
mac: Option<String>,
|
||||
flags: u32,
|
||||
addresses: BTreeSet<(String, u32)>,
|
||||
}
|
||||
|
||||
impl From<&Interface> for InterfaceIdentity {
|
||||
fn from(interface: &Interface) -> Self {
|
||||
let mut addresses = interface
|
||||
.ipv4
|
||||
.iter()
|
||||
.map(|ip| (ip.to_string(), 0))
|
||||
.collect::<BTreeSet<_>>();
|
||||
addresses.extend(interface.ipv6.iter().enumerate().map(|(index, ip)| {
|
||||
(
|
||||
ip.to_string(),
|
||||
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
|
||||
)
|
||||
}));
|
||||
Self {
|
||||
index: interface.index,
|
||||
name: interface.name.clone(),
|
||||
mac: interface.mac_addr.map(|mac| mac.to_string()),
|
||||
flags: interface.flags,
|
||||
addresses,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
struct RouteContext {
|
||||
destination: String,
|
||||
gateway: String,
|
||||
interface: String,
|
||||
table: String,
|
||||
metric: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
struct ResolverContext {
|
||||
interface: Option<String>,
|
||||
servers: Vec<String>,
|
||||
domains: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
struct NetworkSnapshot {
|
||||
interfaces: BTreeSet<InterfaceIdentity>,
|
||||
routes: BTreeSet<RouteContext>,
|
||||
resolvers: Vec<ResolverContext>,
|
||||
}
|
||||
|
||||
/// Captured before this attempt installs a tunnel. Interface counters and
|
||||
/// timestamps do not participate in identity; routes and resolver context do.
|
||||
#[derive(Clone)]
|
||||
pub struct PhysicalNetwork {
|
||||
snapshot: NetworkSnapshot,
|
||||
interfaces: Vec<Interface>,
|
||||
}
|
||||
|
||||
impl PhysicalNetwork {
|
||||
pub async fn bind_authenticated_endpoint(
|
||||
&self,
|
||||
server: &str,
|
||||
endpoint: SocketAddr,
|
||||
disable_ipv6: bool,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<GatewayBinding> {
|
||||
self.ensure_current(cancellation).await?;
|
||||
let binding = resolve_binding(
|
||||
&self.interfaces,
|
||||
Some(self.fingerprint()?),
|
||||
server,
|
||||
disable_ipv6,
|
||||
cancellation,
|
||||
endpoint,
|
||||
)
|
||||
.await?;
|
||||
self.ensure_current(cancellation).await?;
|
||||
Ok(binding)
|
||||
}
|
||||
pub async fn validate_internal_binding(
|
||||
&self,
|
||||
binding: &GatewayBinding,
|
||||
detection: Option<&InternalHostDetection>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
self.validate_binding(binding, cancellation).await?;
|
||||
physical_interface_for_source(&self.interfaces, binding.source(), binding.endpoint())?;
|
||||
self.validate_internal(detection, cancellation).await
|
||||
}
|
||||
|
||||
pub async fn validate_internal(
|
||||
&self,
|
||||
detection: Option<&InternalHostDetection>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
self.ensure_current(cancellation).await?;
|
||||
let mut resolver_count = 0;
|
||||
for resolver in &self.snapshot.resolvers {
|
||||
if resolver.servers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for server in &resolver.servers {
|
||||
let endpoint = resolver_endpoint(server, resolver.interface.as_deref(), &self.interfaces)?;
|
||||
ensure!(
|
||||
!endpoint.ip().is_loopback() && !endpoint.ip().is_unspecified(),
|
||||
"Unattributed local DNS stub is unsupported"
|
||||
);
|
||||
let socket = tokio::net::UdpSocket::bind(if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }).await?;
|
||||
if let Some(name) = &resolver.interface {
|
||||
let interface = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.find(|interface| interface.name == *name)
|
||||
.context("Configured resolver interface is missing")?;
|
||||
platform::scope_resolver_socket(&socket, interface, endpoint)?;
|
||||
}
|
||||
socket.connect(endpoint).await?;
|
||||
let interface = physical_interface_for_source(&self.interfaces, socket.local_addr()?, endpoint)?;
|
||||
ensure!(
|
||||
resolver.interface.as_deref().is_none_or(|name| name == interface.name),
|
||||
"Resolver route differs from its configured interface"
|
||||
);
|
||||
resolver_count += 1;
|
||||
}
|
||||
}
|
||||
ensure!(resolver_count > 0, "Physical resolver context is unavailable");
|
||||
if let Some(detection) = detection {
|
||||
ensure!(
|
||||
detection.detect(cancellation).await?,
|
||||
"Internal host detection no longer matches"
|
||||
);
|
||||
}
|
||||
self.ensure_current(cancellation).await
|
||||
}
|
||||
pub async fn capture_controlled(cancellation: &CancellationToken) -> anyhow::Result<Self> {
|
||||
let cancellation = cancellation.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "Network capture cancelled"));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
Self::capture(&check)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub async fn validate_binding(
|
||||
&self,
|
||||
binding: &GatewayBinding,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
self.ensure_current(cancellation).await?;
|
||||
ensure!(
|
||||
binding.network_fingerprint() == Some(self.fingerprint()?.as_str()),
|
||||
"Physical network changed since authentication"
|
||||
);
|
||||
let interface = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.find(|interface| interface.index == binding.interface_index() && interface.name == binding.interface())
|
||||
.context("Authenticated gateway interface is no longer present")?;
|
||||
let addresses = binding.addresses();
|
||||
ensure!(
|
||||
addresses
|
||||
.ipv4
|
||||
.is_none_or(|ip| interface.ipv4.iter().any(|address| address.addr() == ip)),
|
||||
"Authenticated IPv4 address changed"
|
||||
);
|
||||
ensure!(
|
||||
addresses
|
||||
.ipv6
|
||||
.is_none_or(|ip| interface.ipv6.iter().any(|address| address.addr() == ip)),
|
||||
"Authenticated IPv6 address changed"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fingerprint(&self) -> anyhow::Result<String> {
|
||||
Ok(sha256::digest(serde_json::to_vec(&self.snapshot)?))
|
||||
}
|
||||
|
||||
pub fn capture(control: &dyn CollectionControl) -> anyhow::Result<Self> {
|
||||
control.check()?;
|
||||
let mut interfaces = netdev::get_interfaces();
|
||||
for interface in &mut interfaces {
|
||||
interface.ipv4.sort();
|
||||
// The address and its zone must move together when native enumeration
|
||||
// order changes between captures.
|
||||
let mut ipv6 = interface
|
||||
.ipv6
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(index, address)| {
|
||||
(
|
||||
address,
|
||||
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
ipv6.sort();
|
||||
interface.ipv6 = ipv6.iter().map(|(address, _)| *address).collect();
|
||||
interface.ipv6_scope_ids = ipv6.into_iter().map(|(_, scope)| scope).collect();
|
||||
}
|
||||
let snapshot = snapshot(&interfaces, control)?;
|
||||
control.check()?;
|
||||
Ok(Self { snapshot, interfaces })
|
||||
}
|
||||
|
||||
/// Validate endpoint selection against the captured network. The inspection
|
||||
/// is joined even when cancellation occurs, so native collectors cannot outlive
|
||||
/// the connection attempt.
|
||||
pub async fn ensure_current(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
let current = inspect(cancellation.clone()).await?;
|
||||
ensure!(
|
||||
current == self.snapshot,
|
||||
"Physical network changed during gateway setup"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The owner must cancel and await this monitor, including its blocking
|
||||
/// inspection. Dropping a selected future would detach the native collector.
|
||||
pub async fn wait_for_change(
|
||||
&self,
|
||||
detection: Option<InternalHostDetection>,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<bool> {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return Ok(false),
|
||||
_ = tokio::time::sleep(POLL_INTERVAL) => {},
|
||||
}
|
||||
let current = self.validate_internal(detection.as_ref(), &cancellation).await;
|
||||
if cancellation.is_cancelled() {
|
||||
return Ok(false);
|
||||
}
|
||||
if current.is_err() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_binding(
|
||||
interfaces: &[Interface],
|
||||
fingerprint: Option<String>,
|
||||
server: &str,
|
||||
disable_ipv6: bool,
|
||||
cancellation: &CancellationToken,
|
||||
authenticated_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<GatewayBinding> {
|
||||
let origin = super::transport::gateway_origin(server)?;
|
||||
let host = origin.host_str().context("Gateway host is missing")?;
|
||||
let port = origin.port_or_known_default().context("Gateway port is missing")?;
|
||||
let literal = literal_gateway_address(&origin)?;
|
||||
let endpoints = if let Some(ip) = literal {
|
||||
vec![SocketAddr::new(ip, port)]
|
||||
} else {
|
||||
native::resolve(host, port, disable_ipv6, cancellation).await?
|
||||
};
|
||||
ensure!(
|
||||
endpoints.contains(&authenticated_endpoint),
|
||||
"Authenticated peer differs from the gateway's current DNS addresses; check for a proxy or changed DNS answer"
|
||||
);
|
||||
let endpoint = authenticated_endpoint;
|
||||
ensure!(
|
||||
!(disable_ipv6 && endpoint.is_ipv6()),
|
||||
"Authenticated gateway uses disabled IPv6"
|
||||
);
|
||||
let bind = if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" };
|
||||
let socket = tokio::net::UdpSocket::bind(bind).await?;
|
||||
socket.connect(endpoint).await?;
|
||||
let mut source_address = socket.local_addr()?;
|
||||
source_address.set_port(0);
|
||||
let source = source_address.ip();
|
||||
let interface = physical_interface_for_source(interfaces, source_address, endpoint)?;
|
||||
let ipv4 = match source {
|
||||
IpAddr::V4(ip) => Some(ip),
|
||||
_ => interface
|
||||
.ipv4
|
||||
.iter()
|
||||
.map(|ip| ip.addr())
|
||||
.find(|ip| !ip.is_loopback() && !ip.is_unspecified()),
|
||||
};
|
||||
let ipv6 = if disable_ipv6 {
|
||||
None
|
||||
} else {
|
||||
match source {
|
||||
IpAddr::V6(ip) => Some(ip),
|
||||
_ => interface
|
||||
.ipv6
|
||||
.iter()
|
||||
.map(|ip| ip.addr())
|
||||
.find(|ip| !ip.is_loopback() && !ip.is_unspecified() && !ip.is_unicast_link_local()),
|
||||
}
|
||||
};
|
||||
if let std::net::SocketAddr::V6(address) = &mut source_address {
|
||||
if address.ip().is_unicast_link_local() && address.scope_id() == 0 {
|
||||
address.set_scope_id(interface.index);
|
||||
}
|
||||
}
|
||||
GatewayBinding::new(
|
||||
endpoint,
|
||||
source_address,
|
||||
interface.name.clone(),
|
||||
interface.index,
|
||||
ClientAddresses { ipv4, ipv6 },
|
||||
fingerprint.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
// Default-route inventories include scoped, backup, and unrelated address-family
|
||||
// routes. Attribute each actual destination by its selected source instead.
|
||||
fn physical_interface_for_source(
|
||||
interfaces: &[Interface],
|
||||
source: SocketAddr,
|
||||
endpoint: SocketAddr,
|
||||
) -> anyhow::Result<&Interface> {
|
||||
let mut scope = None;
|
||||
for address in [source, endpoint] {
|
||||
if let SocketAddr::V6(address) = address {
|
||||
if address.scope_id() != 0 {
|
||||
ensure!(
|
||||
scope.is_none_or(|scope| scope == address.scope_id()),
|
||||
"Network source and destination have different interface scopes"
|
||||
);
|
||||
scope = Some(address.scope_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
let source = source.ip();
|
||||
ensure!(
|
||||
!source.is_unspecified() && !source.is_loopback(),
|
||||
"Network route has no physical source address"
|
||||
);
|
||||
let mut matches = interfaces.iter().filter(|interface| {
|
||||
scope.is_none_or(|scope| scope == interface.index)
|
||||
&& (interface.ipv4.iter().any(|ip| IpAddr::V4(ip.addr()) == source)
|
||||
|| interface.ipv6.iter().any(|ip| IpAddr::V6(ip.addr()) == source))
|
||||
});
|
||||
let interface = matches
|
||||
.next()
|
||||
.context("Network route has no matching physical interface")?;
|
||||
ensure!(
|
||||
matches.next().is_none(),
|
||||
"Network route has ambiguous physical interfaces"
|
||||
);
|
||||
ensure!(
|
||||
matches!(
|
||||
interface.if_type,
|
||||
netdev::prelude::InterfaceType::Ethernet
|
||||
| netdev::prelude::InterfaceType::Wireless80211
|
||||
| netdev::prelude::InterfaceType::FastEthernetT
|
||||
| netdev::prelude::InterfaceType::FastEthernetFx
|
||||
| netdev::prelude::InterfaceType::GigabitEthernet
|
||||
),
|
||||
"Network route uses an unsupported physical interface: {}",
|
||||
interface.name
|
||||
);
|
||||
Ok(interface)
|
||||
}
|
||||
|
||||
fn resolver_endpoint(server: &str, interface: Option<&str>, interfaces: &[Interface]) -> anyhow::Result<SocketAddr> {
|
||||
let (address, zone) = server
|
||||
.split_once('%')
|
||||
.map_or((server, None), |(ip, zone)| (ip, Some(zone)));
|
||||
let ip: IpAddr = address.parse().context("Invalid resolver address")?;
|
||||
let mut endpoint = SocketAddr::new(ip, 53);
|
||||
if let SocketAddr::V6(address) = &mut endpoint {
|
||||
let zone = if zone.is_none() && address.ip().is_unicast_link_local() {
|
||||
interface
|
||||
} else {
|
||||
zone
|
||||
};
|
||||
if let Some(zone) = zone {
|
||||
let index = interfaces
|
||||
.iter()
|
||||
.find(|candidate| candidate.name == zone || candidate.index.to_string() == zone)
|
||||
.context("Resolver IPv6 zone has no matching interface")?
|
||||
.index;
|
||||
address.set_scope_id(index);
|
||||
}
|
||||
ensure!(
|
||||
!address.ip().is_unicast_link_local() || address.scope_id() != 0,
|
||||
"Link-local resolver has no interface scope"
|
||||
);
|
||||
} else {
|
||||
ensure!(zone.is_none(), "IPv4 resolver cannot have an interface scope");
|
||||
}
|
||||
Ok(endpoint)
|
||||
}
|
||||
|
||||
async fn inspect(cancellation: CancellationToken) -> anyhow::Result<NetworkSnapshot> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Network inspection cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
let result = snapshot(&netdev::get_interfaces(), &check)?;
|
||||
check()?;
|
||||
Ok(result)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn literal_gateway_address(origin: &url::Url) -> anyhow::Result<Option<IpAddr>> {
|
||||
Ok(match origin.host().context("Gateway host is missing")? {
|
||||
url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
|
||||
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
|
||||
url::Host::Domain(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow::Result<NetworkSnapshot> {
|
||||
control.check()?;
|
||||
Ok(NetworkSnapshot {
|
||||
interfaces: interfaces.iter().map(InterfaceIdentity::from).collect(),
|
||||
routes: platform::routes(control)?.into_iter().collect(),
|
||||
resolvers: platform::resolvers(control)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
let output = CollectorCommands::new(control)
|
||||
.run(name, args)?
|
||||
.with_context(|| format!("Required network tool {name} is unavailable"))?;
|
||||
ensure!(output.status.success(), "Network tool {name} failed");
|
||||
String::from_utf8(output.stdout).context("Network tool output is not UTF-8")
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn resolv_conf(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
control.check()?;
|
||||
let file = std::fs::File::open("/etc/resolv.conf")?;
|
||||
use std::io::Read;
|
||||
let mut contents = String::new();
|
||||
file.take(64 * 1024 + 1).read_to_string(&mut contents)?;
|
||||
ensure!(contents.len() <= 64 * 1024, "Resolver configuration is too large");
|
||||
control.check()?;
|
||||
Ok(vec![parse_resolv_conf(&contents)?])
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn parse_resolv_conf(contents: &str) -> anyhow::Result<ResolverContext> {
|
||||
let mut resolver = ResolverContext {
|
||||
interface: None,
|
||||
servers: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
};
|
||||
for line in contents.lines() {
|
||||
let line = line.split(['#', ';']).next().unwrap_or_default();
|
||||
let mut fields = line.split_whitespace();
|
||||
match fields.next() {
|
||||
Some("nameserver") => {
|
||||
if let Some(server) = fields.next() {
|
||||
// IPv6 zone identifiers are retained for scoped physical resolvers.
|
||||
server
|
||||
.split('%')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.parse::<IpAddr>()
|
||||
.context("Invalid resolver address")?;
|
||||
resolver.servers.push(server.to_owned());
|
||||
}
|
||||
}
|
||||
Some("search" | "domain") => resolver
|
||||
.domains
|
||||
.extend(fields.map(|domain| domain.to_ascii_lowercase())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(resolver)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ethernet(name: &str, index: u32, address: &str) -> Interface {
|
||||
let mut interface = Interface::dummy();
|
||||
interface.name = name.into();
|
||||
interface.index = index;
|
||||
interface.if_type = netdev::prelude::InterfaceType::Ethernet;
|
||||
interface.ipv4 = vec![address.parse().unwrap()];
|
||||
interface.ipv6 = vec!["fe80::1/64".parse().unwrap()];
|
||||
interface
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_each_destination_without_requiring_a_single_uplink() {
|
||||
let ethernet = ethernet("en0", 7, "192.0.2.10/24");
|
||||
let mut wifi = ethernet.clone();
|
||||
wifi.name = "en1".into();
|
||||
wifi.index = 8;
|
||||
wifi.if_type = netdev::prelude::InterfaceType::Wireless80211;
|
||||
wifi.ipv4 = vec!["198.51.100.10/24".parse().unwrap()];
|
||||
let mut tunnel = Interface::dummy();
|
||||
tunnel.name = "utun0".into();
|
||||
tunnel.index = 9;
|
||||
tunnel.ipv4 = vec!["10.0.0.1/24".parse().unwrap()];
|
||||
let interfaces = [ethernet, wifi, tunnel];
|
||||
for (source, endpoint, expected) in [
|
||||
("192.0.2.10:0", "203.0.113.1:443", "en0"),
|
||||
("198.51.100.10:0", "198.51.100.53:53", "en1"),
|
||||
("[fe80::1%8]:0", "[fe80::53%8]:53", "en1"),
|
||||
] {
|
||||
assert_eq!(
|
||||
physical_interface_for_source(&interfaces, source.parse().unwrap(), endpoint.parse().unwrap())
|
||||
.unwrap()
|
||||
.name,
|
||||
expected
|
||||
);
|
||||
}
|
||||
// Virtual interfaces may coexist, but must never supply the selected source.
|
||||
assert!(
|
||||
physical_interface_for_source(
|
||||
&interfaces,
|
||||
"10.0.0.1:0".parse().unwrap(),
|
||||
"10.0.0.53:53".parse().unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
// Identical link-local addresses without scope are ambiguous.
|
||||
assert!(
|
||||
physical_interface_for_source(
|
||||
&interfaces,
|
||||
"[fe80::1]:0".parse().unwrap(),
|
||||
"[fe80::53]:53".parse().unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
physical_interface_for_source(
|
||||
&interfaces,
|
||||
"[fe80::1%7]:0".parse().unwrap(),
|
||||
"[fe80::53%8]:53".parse().unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ambiguous_or_unattributed_sources() {
|
||||
let interfaces = [ethernet("en0", 7, "192.0.2.10/24"), ethernet("en1", 8, "192.0.2.10/24")];
|
||||
for source in ["192.0.2.10:0", "192.0.2.11:0", "127.0.0.1:0", "0.0.0.0:0"] {
|
||||
assert!(
|
||||
physical_interface_for_source(&interfaces, source.parse().unwrap(), "192.0.2.53:53".parse().unwrap()).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_zones_support_native_names_and_numeric_indices() {
|
||||
let interfaces = [ethernet("en0", 7, "192.0.2.10/24")];
|
||||
let expected: SocketAddr = "[fe80::53%7]:53".parse().unwrap();
|
||||
assert_eq!(resolver_endpoint("fe80::53%en0", None, &interfaces).unwrap(), expected);
|
||||
assert_eq!(resolver_endpoint("fe80::53%7", None, &interfaces).unwrap(), expected);
|
||||
assert_eq!(
|
||||
resolver_endpoint("fe80::53", Some("en0"), &interfaces).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
resolver_endpoint("192.0.2.53", Some("en0"), &interfaces).unwrap(),
|
||||
"192.0.2.53:53".parse().unwrap()
|
||||
);
|
||||
for server in ["fe80::53", "fe80::53%missing", "fe80::53%8", "192.0.2.53%en0"] {
|
||||
assert!(
|
||||
resolver_endpoint(server, None, &interfaces).is_err(),
|
||||
"accepted {server}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_ipv6_gateway_is_a_literal_endpoint() {
|
||||
let origin = super::super::transport::gateway_origin("https://[2001:db8::1]:444").unwrap();
|
||||
assert_eq!(
|
||||
literal_gateway_address(&origin).unwrap(),
|
||||
Some("2001:db8::1".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_order_comments_and_case_do_not_change_network_identity() {
|
||||
assert_eq!(
|
||||
parse_resolv_conf("nameserver 192.0.2.53\nsearch CORP.EXAMPLE\n# comment").unwrap(),
|
||||
parse_resolv_conf("search corp.example\nnameserver 192.0.2.53 # DHCP\n").unwrap()
|
||||
);
|
||||
assert_ne!(
|
||||
parse_resolv_conf("nameserver 192.0.2.53").unwrap(),
|
||||
parse_resolv_conf("nameserver 192.0.2.54").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_identity_ignores_counters_and_address_enumeration_order() {
|
||||
let mut interface = Interface::dummy();
|
||||
interface.index = 7;
|
||||
interface.name = "bridge0".into();
|
||||
interface.ipv4 = vec!["192.0.2.10/24".parse().unwrap(), "192.0.2.11/24".parse().unwrap()];
|
||||
let original = InterfaceIdentity::from(&interface);
|
||||
interface.ipv4.reverse();
|
||||
interface.mtu = Some(1200);
|
||||
interface.default = !interface.default;
|
||||
assert_eq!(original, InterfaceIdentity::from(&interface));
|
||||
interface.index = 8;
|
||||
assert_ne!(original, InterfaceIdentity::from(&interface));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_binding() -> GatewayBinding {
|
||||
GatewayBinding::new(
|
||||
"192.0.2.10:443".parse().unwrap(),
|
||||
"192.0.2.5:0".parse().unwrap(),
|
||||
"fixture".into(),
|
||||
1,
|
||||
ClientAddresses {
|
||||
ipv4: Some("192.0.2.5".parse().unwrap()),
|
||||
ipv6: None,
|
||||
},
|
||||
"0".repeat(64),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use dns_lookup::{AddrFamily, AddrInfoHints, SockType, getaddrinfo};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::*;
|
||||
|
||||
const MAX_ADDRESSES: usize = 64;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Result<bool> {
|
||||
super::detection::validate_target(address, hostname)?;
|
||||
Ok(dns_lookup::lookup_addr(&address).is_ok_and(|name| name.eq_ignore_ascii_case(hostname)))
|
||||
}
|
||||
|
||||
pub(super) async fn detect(
|
||||
address: std::net::IpAddr,
|
||||
hostname: &str,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<bool> {
|
||||
super::detection::validate_target(address, hostname)?;
|
||||
let args = vec![
|
||||
"detect-internal-host".into(),
|
||||
"--address".into(),
|
||||
address.to_string(),
|
||||
"--hostname".into(),
|
||||
hostname.into(),
|
||||
];
|
||||
let output = run_helper(common::binary_paths::gpclient(), args, cancellation.clone()).await?;
|
||||
serde_json::from_slice(&output).context("Invalid internal detection helper response")
|
||||
}
|
||||
|
||||
/// Entry point for gpclient's isolated native resolver helper. This blocking
|
||||
/// function must run in the child process, never a connection runtime thread.
|
||||
#[doc(hidden)]
|
||||
pub fn lookup_in_helper(host: &str, port: u16, disable_ipv6: bool) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
validate_host(host, port)?;
|
||||
let hints = AddrInfoHints {
|
||||
address: if disable_ipv6 { AddrFamily::Inet.into() } else { 0 },
|
||||
socktype: SockType::Stream.into(),
|
||||
..AddrInfoHints::default()
|
||||
};
|
||||
let service = port.to_string();
|
||||
let mut addresses = Vec::new();
|
||||
for result in getaddrinfo(Some(host), Some(&service), Some(hints)).map_err(io::Error::from)? {
|
||||
let address = result?.sockaddr;
|
||||
if !addresses.contains(&address) {
|
||||
ensure!(
|
||||
addresses.len() < MAX_ADDRESSES,
|
||||
"Native resolver returned too many gateway addresses"
|
||||
);
|
||||
addresses.push(address);
|
||||
}
|
||||
}
|
||||
validate_addresses(&addresses, port, disable_ipv6)?;
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve(
|
||||
host: &str,
|
||||
port: u16,
|
||||
disable_ipv6: bool,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
validate_host(host, port)?;
|
||||
let mut args = vec!["resolve-gateway".into(), host.into(), "--port".into(), port.to_string()];
|
||||
if disable_ipv6 {
|
||||
args.push("--disable-ipv6".into());
|
||||
}
|
||||
run_resolver(
|
||||
common::binary_paths::gpclient(),
|
||||
args,
|
||||
port,
|
||||
disable_ipv6,
|
||||
cancellation.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_resolver(
|
||||
executable: PathBuf,
|
||||
args: Vec<String>,
|
||||
port: u16,
|
||||
disable_ipv6: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
let output = run_helper(executable, args, cancellation).await?;
|
||||
let addresses: Vec<SocketAddr> = serde_json::from_slice(&output).context("Invalid resolver helper response")?;
|
||||
validate_addresses(&addresses, port, disable_ipv6)?;
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
async fn run_helper(
|
||||
executable: PathBuf,
|
||||
args: Vec<String>,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
// Await the owned worker even on cancellation. CollectorCommands kills and
|
||||
// waits for the helper process and any descendants before returning.
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Gateway resolution cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
let args = args.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
let output = CollectorCommands::new(&check)
|
||||
.run_executable(&executable, &args)?
|
||||
.context("Native resolver helper is unavailable")?;
|
||||
check()?;
|
||||
ensure!(output.status.success(), "Native gateway resolution failed");
|
||||
Ok(output.stdout)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn validate_host(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
ensure!(port != 0, "Gateway port is zero");
|
||||
ensure!(
|
||||
!host.is_empty() && host.len() <= 253 && !host.contains('\0') && !host.contains(['/', ':']),
|
||||
"Invalid gateway hostname"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_addresses(addresses: &[SocketAddr], port: u16, disable_ipv6: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!addresses.is_empty() && addresses.len() <= MAX_ADDRESSES,
|
||||
"Invalid gateway address count"
|
||||
);
|
||||
ensure!(
|
||||
addresses.iter().all(|address| {
|
||||
address.port() == port && !address.ip().is_unspecified() && (!disable_ipv6 || address.is_ipv4())
|
||||
}),
|
||||
"Invalid gateway address from resolver helper"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_helper_output_is_validated_before_admission() {
|
||||
let addresses = run_resolver(
|
||||
"/bin/sh".into(),
|
||||
vec!["-c".into(), "printf '[\"192.0.2.1:443\"]'".into()],
|
||||
443,
|
||||
true,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(addresses, vec!["192.0.2.1:443".parse::<SocketAddr>().unwrap()]);
|
||||
assert!(
|
||||
run_resolver(
|
||||
"/bin/sh".into(),
|
||||
vec!["-c".into(), "printf '[\"192.0.2.1:444\"]'".into()],
|
||||
443,
|
||||
true,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_kills_and_joins_the_running_resolver_process() {
|
||||
let file = tempfile::NamedTempFile::new().unwrap();
|
||||
let path = file.path().to_owned();
|
||||
let cancellation = CancellationToken::new();
|
||||
let worker = tokio::spawn(run_resolver(
|
||||
"/bin/sh".into(),
|
||||
vec![
|
||||
"-c".into(),
|
||||
"printf '%s' \"$$\" > \"$1\"; sleep 30 & wait".into(),
|
||||
"resolver-test".into(),
|
||||
path.to_string_lossy().into_owned(),
|
||||
],
|
||||
443,
|
||||
false,
|
||||
cancellation.clone(),
|
||||
));
|
||||
let pid = tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
if let Ok(pid) = std::fs::read_to_string(&path).unwrap().parse::<i32>() {
|
||||
break pid;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
cancellation.cancel();
|
||||
let error = tokio::time::timeout(Duration::from_secs(1), worker)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
assert_eq!(
|
||||
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
|
||||
Err(nix::errno::Errno::ESRCH)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_lookup_preserves_port_and_ipv4_policy() {
|
||||
let addresses = lookup_in_helper("localhost", 444, true).unwrap();
|
||||
assert!(
|
||||
addresses
|
||||
.iter()
|
||||
.all(|address| address.is_ipv4() && address.ip().is_loopback() && address.port() == 444)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_response_validation_retains_ipv6_scope_and_rejects_wrong_port() {
|
||||
let addresses = vec!["[fe80::1%7]:443".parse().unwrap(), "192.0.2.1:443".parse().unwrap()];
|
||||
validate_addresses(&addresses, 443, false).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Vec<SocketAddr>>(&serde_json::to_string(&addresses).unwrap()).unwrap(),
|
||||
addresses
|
||||
);
|
||||
assert!(validate_addresses(&addresses, 444, false).is_err());
|
||||
assert!(validate_addresses(&addresses, 443, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_helper_requests_before_lookup() {
|
||||
assert!(lookup_in_helper("gateway.example/path", 443, false).is_err());
|
||||
assert!(lookup_in_helper("gateway.example", 0, false).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
use std::{
|
||||
future::Future,
|
||||
io,
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use tokio::task::JoinSet;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::{gateway::Gateway, process::collection::CollectionControl};
|
||||
|
||||
use super::{
|
||||
GatewaySession, GatewaySessionSummary, GatewaySessions, InternalSessionPolicy, MaintenanceState, SessionEndReason,
|
||||
SessionMode, transport::GatewayRequestError,
|
||||
};
|
||||
|
||||
const COLLECTION_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// This request is deliberately independent of OpenConnect's callback/FFI types.
|
||||
#[derive(Clone)]
|
||||
pub struct SessionHipRequest {
|
||||
pub gateway: Gateway,
|
||||
pub cookie: String,
|
||||
pub client_ip: Option<String>,
|
||||
pub client_ipv6: Option<String>,
|
||||
pub md5: String,
|
||||
pub collect_posture: bool,
|
||||
}
|
||||
|
||||
impl Drop for SessionHipRequest {
|
||||
fn drop(&mut self) {
|
||||
self.cookie.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SessionCollectionControl {
|
||||
cancellation: CancellationToken,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl CollectionControl for SessionCollectionControl {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "HIP collection cancelled"))
|
||||
} else if Instant::now() >= self.deadline {
|
||||
Err(io::Error::new(io::ErrorKind::TimedOut, "HIP collection timed out"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type SessionReportProducer =
|
||||
dyn Fn(&SessionHipRequest, &SessionCollectionControl) -> io::Result<String> + Send + Sync;
|
||||
pub type SessionReportObserver = dyn Fn(&SessionHipRequest, &str) + Send + Sync;
|
||||
pub type SessionStatusObserver = dyn Fn(GatewaySessionSummary) + Send + Sync;
|
||||
pub type SessionNetworkValidator =
|
||||
dyn Fn(CancellationToken) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> + Send + Sync;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SessionCallbacks {
|
||||
pub produce_report: Arc<SessionReportProducer>,
|
||||
pub report_submitted: Arc<SessionReportObserver>,
|
||||
pub status_changed: Arc<SessionStatusObserver>,
|
||||
pub validate_network: Arc<SessionNetworkValidator>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SessionExit {
|
||||
Disconnected,
|
||||
Failed(SessionEndReason),
|
||||
}
|
||||
|
||||
/// Owns maintenance workers until they have stopped. The session owner retains
|
||||
/// its ledger and logs out after joining every worker. Interactive authentication
|
||||
/// also belongs to that owner. Cancel and await this future, never abort/drop it:
|
||||
/// blocking collectors must finish before cleanup releases their resources.
|
||||
pub async fn maintain_non_tunnel_sessions(
|
||||
sessions: &mut GatewaySessions,
|
||||
policy: InternalSessionPolicy,
|
||||
mut callbacks: SessionCallbacks,
|
||||
cancellation: CancellationToken,
|
||||
network_change: impl Future<Output = SessionEndReason>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
anyhow::ensure!(!sessions.is_empty(), "Non-tunnel session set is empty");
|
||||
anyhow::ensure!(
|
||||
sessions
|
||||
.members()
|
||||
.iter()
|
||||
.all(|session| session.transport.authentication().mode() == SessionMode::NonTunnel),
|
||||
"Tunnel member supplied to non-tunnel runtime"
|
||||
);
|
||||
let workers_cancel = cancellation.child_token();
|
||||
let observer = callbacks.status_changed.clone();
|
||||
let status_gate = Arc::new(Mutex::new(()));
|
||||
let gate = status_gate.clone();
|
||||
let cancelled = workers_cancel.clone();
|
||||
let worker_observer = observer.clone();
|
||||
callbacks.status_changed = Arc::new(move |summary| {
|
||||
let _guard = gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if !cancelled.is_cancelled() {
|
||||
worker_observer(summary);
|
||||
}
|
||||
});
|
||||
let mut workers = JoinSet::new();
|
||||
for session in sessions.members() {
|
||||
let session = session.clone();
|
||||
let callbacks = callbacks.clone();
|
||||
let cancellation = workers_cancel.clone();
|
||||
workers.spawn(async move {
|
||||
let server = session.gateway.server().to_owned();
|
||||
(server, maintain_member(session, policy, callbacks, cancellation).await)
|
||||
});
|
||||
}
|
||||
tokio::pin!(network_change);
|
||||
let mut worker_failure = None;
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => break SessionExit::Disconnected,
|
||||
reason = &mut network_change => break SessionExit::Failed(reason),
|
||||
result = workers.join_next() => match result {
|
||||
Some(Ok((_, MemberExit::Terminal(reason)))) => break SessionExit::Failed(reason),
|
||||
Some(Ok((server, MemberExit::Rejected))) => {
|
||||
sessions.logout_gateway(&server).await;
|
||||
if workers.is_empty() { break SessionExit::Failed(SessionEndReason::AllMembersFailed); }
|
||||
},
|
||||
Some(Ok((_, MemberExit::Cancelled))) => {},
|
||||
Some(Err(error)) => { worker_failure = Some(error); break SessionExit::Disconnected; },
|
||||
None => break SessionExit::Failed(SessionEndReason::AllMembersFailed),
|
||||
},
|
||||
}
|
||||
};
|
||||
workers_cancel.cancel();
|
||||
if matches!(outcome, SessionExit::Failed(_)) || worker_failure.is_some() {
|
||||
// Invalidate advertised health before waiting for collectors or remote
|
||||
// cleanup. Cancellation prevents workers from publishing Healthy afterwards.
|
||||
let _guard = status_gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
for session in sessions.members() {
|
||||
observer(GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: SessionMode::NonTunnel,
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
maintenance: MaintenanceState::Rejected,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Do not abort workers: a blocking collector must observe cancellation and be
|
||||
// joined before approval/identity resources can be released by the caller.
|
||||
while let Some(result) = workers.join_next().await {
|
||||
if let Err(error) = result {
|
||||
worker_failure.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
if let Some(error) = worker_failure {
|
||||
return Err(error.into());
|
||||
}
|
||||
// Deliberate disconnect wins even when it arrives during coordinated cleanup.
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
Ok(outcome)
|
||||
}
|
||||
}
|
||||
|
||||
async fn maintain_member(
|
||||
session: Arc<GatewaySession>,
|
||||
policy: InternalSessionPolicy,
|
||||
callbacks: SessionCallbacks,
|
||||
cancellation: CancellationToken,
|
||||
) -> MemberExit {
|
||||
let request = SessionHipRequest {
|
||||
gateway: session.gateway.clone(),
|
||||
cookie: session.transport.authentication().cookie().into(),
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
md5: session.transport.hip_token(),
|
||||
collect_posture: policy.collect_hip_data(),
|
||||
};
|
||||
let status = |maintenance| {
|
||||
if !cancellation.is_cancelled() {
|
||||
(callbacks.status_changed)(GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: SessionMode::NonTunnel,
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
maintenance,
|
||||
});
|
||||
}
|
||||
};
|
||||
status(MaintenanceState::Authenticated);
|
||||
loop {
|
||||
if (callbacks.validate_network)(cancellation.clone()).await.is_err() {
|
||||
return MemberExit::Terminal(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
let sent_at = tokio::time::Instant::now();
|
||||
let check = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return MemberExit::Cancelled,
|
||||
result = session.transport.check_hip(session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result,
|
||||
};
|
||||
let (result, delay) = match check {
|
||||
Ok(check) => {
|
||||
let result = if check.report_needed {
|
||||
collect_and_submit(&session, &request, &callbacks, &cancellation).await
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
(result, check.delay)
|
||||
}
|
||||
Err(error) => (Err(MemberError::Gateway(error)), Duration::ZERO),
|
||||
};
|
||||
let next_check = match result {
|
||||
Ok(()) => {
|
||||
if cancellation.is_cancelled() {
|
||||
return MemberExit::Cancelled;
|
||||
}
|
||||
status(MaintenanceState::Healthy);
|
||||
let Some(next_check) = sent_at
|
||||
.checked_add(policy.hip_interval())
|
||||
.and_then(|time| time.checked_add(delay))
|
||||
else {
|
||||
status(MaintenanceState::Rejected);
|
||||
return MemberExit::Rejected;
|
||||
};
|
||||
next_check
|
||||
}
|
||||
Err(MemberError::Gateway(GatewayRequestError::InvalidCookie)) => {
|
||||
status(MaintenanceState::Rejected);
|
||||
return MemberExit::Terminal(SessionEndReason::InvalidCookie);
|
||||
}
|
||||
Err(MemberError::Network) => return MemberExit::Terminal(SessionEndReason::NetworkChanged),
|
||||
Err(MemberError::Authorization) => return MemberExit::Terminal(SessionEndReason::AuthorizationRevoked),
|
||||
Err(error) => {
|
||||
if cancellation.is_cancelled() {
|
||||
return MemberExit::Cancelled;
|
||||
}
|
||||
status(MaintenanceState::Rejected);
|
||||
log::warn!("Gateway maintenance failed: {error}");
|
||||
return MemberExit::Rejected;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return MemberExit::Cancelled,
|
||||
_ = tokio::time::sleep_until(next_check) => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum MemberExit {
|
||||
Cancelled,
|
||||
Rejected,
|
||||
Terminal(SessionEndReason),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum MemberError {
|
||||
#[error("{0}")]
|
||||
Gateway(#[from] GatewayRequestError),
|
||||
// Collector/script errors can contain user-provided text. Do not log payloads.
|
||||
#[error("HIP report collection failed")]
|
||||
Collection,
|
||||
#[error("Physical network validation failed")]
|
||||
Network,
|
||||
#[error("HIP report authorization was revoked")]
|
||||
Authorization,
|
||||
}
|
||||
|
||||
async fn collect_and_submit(
|
||||
session: &GatewaySession,
|
||||
request: &SessionHipRequest,
|
||||
callbacks: &SessionCallbacks,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), MemberError> {
|
||||
let producer = callbacks.produce_report.clone();
|
||||
let input = request.clone();
|
||||
let control = SessionCollectionControl {
|
||||
cancellation: cancellation.clone(),
|
||||
deadline: Instant::now() + COLLECTION_TIMEOUT,
|
||||
};
|
||||
let report = tokio::task::spawn_blocking(move || {
|
||||
control.check()?;
|
||||
let report = Zeroizing::new(producer(&input, &control)?);
|
||||
control.check()?;
|
||||
Ok::<_, io::Error>(report)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| MemberError::Collection)?
|
||||
.map_err(|error| {
|
||||
if error.kind() == io::ErrorKind::PermissionDenied {
|
||||
MemberError::Authorization
|
||||
} else {
|
||||
MemberError::Collection
|
||||
}
|
||||
})?;
|
||||
(callbacks.validate_network)(cancellation.clone())
|
||||
.await
|
||||
.map_err(|_| MemberError::Network)?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return Err(MemberError::Collection),
|
||||
result = session.transport.submit_hip(&report, session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result?,
|
||||
}
|
||||
if !cancellation.is_cancelled() {
|
||||
(callbacks.report_submitted)(request, &report);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,415 @@
|
||||
use std::{
|
||||
future::pending,
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::*;
|
||||
use crate::session::transport::GatewayTransport;
|
||||
use crate::session::{
|
||||
ClientAddresses, GatewaySessions,
|
||||
transport::tests::{gateway, response},
|
||||
};
|
||||
|
||||
async fn run_owned_sessions(
|
||||
members: Vec<GatewaySession>,
|
||||
policy: InternalSessionPolicy,
|
||||
callbacks: SessionCallbacks,
|
||||
cancellation: CancellationToken,
|
||||
network_change: impl Future<Output = SessionEndReason>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
let mut sessions = GatewaySessions::new(members);
|
||||
let result =
|
||||
maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation.clone(), network_change).await;
|
||||
sessions.logout().await;
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn member(name: &str, transport: GatewayTransport) -> GatewaySession {
|
||||
GatewaySession {
|
||||
gateway: Gateway::new(name.into(), format!("{name}.example")),
|
||||
transport,
|
||||
addresses: ClientAddresses {
|
||||
ipv4: Some("192.0.2.7".parse().unwrap()),
|
||||
ipv6: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn callbacks() -> SessionCallbacks {
|
||||
SessionCallbacks {
|
||||
produce_report: Arc::new(|_, _| Ok("<hip-report/>".into())),
|
||||
report_submitted: Arc::new(|_, _| {}),
|
||||
status_changed: Arc::new(|_| {}),
|
||||
validate_network: Arc::new(|_| Box::pin(async { Ok(()) })),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn network_uncertainty_prevents_hip_and_healthy_status() {
|
||||
let (transport, server) = gateway(vec![response("<response status='success'/>")]).await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.validate_network = Arc::new(|_| Box::pin(async { anyhow::bail!("Network changed") }));
|
||||
callbacks.status_changed = Arc::new(|summary| assert_ne!(summary.maintenance, MaintenanceState::Healthy));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
|
||||
assert_eq!(server.await.unwrap()[0].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoked_report_authorization_terminates_the_attempt() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.produce_report = Arc::new(|_, _| Err(io::ErrorKind::PermissionDenied.into()));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AuthorizationRevoked));
|
||||
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_cookie_terminates_only_after_logout() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks(),
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejection_preserves_healthy_members_and_cleanup_owns_all_members() {
|
||||
let (rejected, rejected_server) = gateway(vec![
|
||||
response("<response status='error'><error>Denied</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let (healthy, healthy_server) = gateway(vec![
|
||||
response("<response><hip-report-needed>no</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let ready = Arc::new(Notify::new());
|
||||
let states = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut callbacks = callbacks();
|
||||
let states_copy = states.clone();
|
||||
let ready_copy = ready.clone();
|
||||
callbacks.status_changed = Arc::new(move |summary| {
|
||||
if summary.maintenance != MaintenanceState::Authenticated {
|
||||
let mut states = states_copy.lock().unwrap();
|
||||
states.push((summary.gateway.name().to_owned(), summary.maintenance));
|
||||
if states.len() == 2 {
|
||||
ready_copy.notify_one();
|
||||
}
|
||||
}
|
||||
});
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("rejected", rejected), member("healthy", healthy)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
async {
|
||||
ready.notified().await;
|
||||
SessionEndReason::NetworkChanged
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
|
||||
let states = states.lock().unwrap();
|
||||
assert!(states.contains(&("rejected".into(), MaintenanceState::Rejected)));
|
||||
assert!(states.contains(&("healthy".into(), MaintenanceState::Healthy)));
|
||||
assert_eq!(rejected_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observes_reports_only_after_successful_submission() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let cancellation = CancellationToken::new();
|
||||
let submitted = Arc::new(AtomicUsize::new(0));
|
||||
let observed = submitted.clone();
|
||||
let stop = cancellation.clone();
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.report_submitted = Arc::new(move |request, report| {
|
||||
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.7"));
|
||||
assert_eq!(report, "<hip-report/>");
|
||||
observed.fetch_add(1, Ordering::SeqCst);
|
||||
stop.cancel();
|
||||
});
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
cancellation,
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Disconnected);
|
||||
assert_eq!(submitted.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(server.await.unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_collection_is_joined_before_runtime_returns() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let cancellation = CancellationToken::new();
|
||||
let entered = Arc::new(Notify::new());
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let mut callbacks = callbacks();
|
||||
let entered_copy = entered.clone();
|
||||
let stopped_copy = stopped.clone();
|
||||
callbacks.produce_report = Arc::new(move |_, control| {
|
||||
entered_copy.notify_one();
|
||||
loop {
|
||||
if let Err(error) = control.check() {
|
||||
stopped_copy.store(true, Ordering::SeqCst);
|
||||
return Err(error);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
});
|
||||
callbacks.report_submitted = Arc::new(|_, _| panic!("Cancelled report must not be observed"));
|
||||
let stop = cancellation.clone();
|
||||
let exit = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
cancellation,
|
||||
async {
|
||||
entered.notified().await;
|
||||
stop.cancel();
|
||||
pending().await
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Disconnected);
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn all_rejected_members_are_logged_out_before_terminal_failure() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response status='error'><error>Denied</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.produce_report = Arc::new(|_, _| panic!("Rejected member cannot collect a report"));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("rejected", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
|
||||
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_member_cookie_cancels_and_joins_another_members_collector() {
|
||||
let arrived = Arc::new(Notify::new());
|
||||
let release = Arc::new(Notify::new());
|
||||
let collecting = Arc::new(Notify::new());
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let (expired, expired_server) = crate::session::transport::tests::gateway_with_first_response_gate(
|
||||
vec![
|
||||
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
],
|
||||
arrived.clone(),
|
||||
release.clone(),
|
||||
)
|
||||
.await;
|
||||
let (healthy, healthy_server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
let collecting_copy = collecting.clone();
|
||||
let stopped_copy = stopped.clone();
|
||||
callbacks.produce_report = Arc::new(move |request, control| {
|
||||
assert_eq!(request.gateway.name(), "collecting");
|
||||
collecting_copy.notify_one();
|
||||
loop {
|
||||
if let Err(error) = control.check() {
|
||||
stopped_copy.store(true, Ordering::SeqCst);
|
||||
return Err(error);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
});
|
||||
callbacks.report_submitted = Arc::new(|_, _| panic!("Interrupted collection must not submit"));
|
||||
let exit = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
run_owned_sessions(
|
||||
vec![member("expired", expired), member("collecting", healthy)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
async {
|
||||
arrived.notified().await;
|
||||
collecting.notified().await;
|
||||
release.notify_one();
|
||||
pending().await
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert_eq!(expired_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_submission_is_terminal_without_retry_or_observation() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.report_submitted = Arc::new(|_, _| panic!("Failed report must not be retained"));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(
|
||||
requests.iter().map(|request| request.0.as_str()).collect::<Vec<_>>(),
|
||||
[
|
||||
"/ssl-vpn/hipreportcheck.esp",
|
||||
"/ssl-vpn/hipreport.esp",
|
||||
"/ssl-vpn/logout.esp"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn schedules_from_send_time_plus_interval_and_server_delay() {
|
||||
let arrived = Arc::new(Notify::new());
|
||||
let release = Arc::new(Notify::new());
|
||||
let (transport, server) = crate::session::transport::tests::gateway_with_first_response_gate(
|
||||
vec![
|
||||
response("<response><hip-report-needed>no</hip-report-needed><delay>7</delay></response>"),
|
||||
response("<response><hip-report-needed>no</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
],
|
||||
arrived.clone(),
|
||||
release.clone(),
|
||||
)
|
||||
.await;
|
||||
let cancellation = CancellationToken::new();
|
||||
let stop = cancellation.clone();
|
||||
let (sent, mut received) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.status_changed = Arc::new(move |summary| {
|
||||
if summary.maintenance == MaintenanceState::Healthy {
|
||||
sent.send(tokio::time::Instant::now()).unwrap();
|
||||
}
|
||||
});
|
||||
let runtime = tokio::spawn(run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::new(10, false).unwrap(),
|
||||
callbacks,
|
||||
cancellation,
|
||||
pending(),
|
||||
));
|
||||
arrived.notified().await;
|
||||
// Simulate three seconds spent waiting for the first response. The interval
|
||||
// must be anchored before that latency, rather than after completion.
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(3)).await;
|
||||
tokio::time::resume();
|
||||
release.notify_one();
|
||||
let first = received.recv().await.unwrap();
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(13)).await;
|
||||
tokio::time::resume();
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert!(received.try_recv().is_err(), "Server delay must extend the interval");
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
tokio::time::resume();
|
||||
let second = tokio::time::timeout(Duration::from_millis(500), received.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let elapsed = second.duration_since(first);
|
||||
assert!(
|
||||
elapsed >= Duration::from_millis(13_900) && elapsed < Duration::from_millis(14_500),
|
||||
"Unexpected anchored interval: {elapsed:?}"
|
||||
);
|
||||
stop.cancel();
|
||||
assert_eq!(runtime.await.unwrap().unwrap(), SessionExit::Disconnected);
|
||||
assert_eq!(server.await.unwrap().len(), 3);
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
use std::{net::IpAddr, time::Duration};
|
||||
|
||||
use reqwest::{Client, StatusCode, Url, redirect::Policy};
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{gp_params::GpParams, os_profile::OsProfile, utils::xml::ElementExt};
|
||||
|
||||
use super::{GatewayAuthentication, network::GatewayBinding};
|
||||
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub(crate) const MAX_GATEWAY_RESPONSE_BYTES: usize = 1024 * 1024;
|
||||
pub const MAX_HIP_REPORT_BYTES: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum GatewayRequestError {
|
||||
#[error("Gateway authentication cookie expired")]
|
||||
InvalidCookie,
|
||||
#[error("Gateway request failed: {0}")]
|
||||
Transport(#[from] reqwest::Error),
|
||||
#[error("Gateway returned HTTP {0}")]
|
||||
Http(StatusCode),
|
||||
#[error("Gateway rejected the request")]
|
||||
Rejected,
|
||||
#[error("Gateway returned a malformed response")]
|
||||
MalformedResponse,
|
||||
#[error("Gateway response exceeds its size limit")]
|
||||
ResponseTooLarge,
|
||||
#[error("HIP report is empty, contains NUL, or exceeds its size limit")]
|
||||
InvalidReport,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct HipCheck {
|
||||
pub report_needed: bool,
|
||||
pub delay: Duration,
|
||||
}
|
||||
|
||||
/// Authenticated HTTP requests retain the login identity. Non-tunnel maintenance
|
||||
/// uses a validated physical binding; pre-tunnel cleanup uses ordinary HTTP.
|
||||
pub struct GatewayTransport {
|
||||
client: Client,
|
||||
origin: Url,
|
||||
authentication: GatewayAuthentication,
|
||||
profile: OsProfile,
|
||||
}
|
||||
|
||||
impl GatewayTransport {
|
||||
pub fn new(
|
||||
server: &str,
|
||||
authentication: GatewayAuthentication,
|
||||
params: &GpParams,
|
||||
binding: Option<&GatewayBinding>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let origin = Url::parse(&crate::utils::normalize_server(server)?)?;
|
||||
let client = match binding {
|
||||
Some(binding) => bound_client(server, params, binding)?,
|
||||
None => Client::try_from(params)?,
|
||||
};
|
||||
Ok(Self {
|
||||
client,
|
||||
origin,
|
||||
authentication,
|
||||
profile: params.os_profile().clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The login client already validated and built this transport before issuing
|
||||
/// authentication. Registering its cleanup context cannot fail afterwards.
|
||||
pub(crate) fn from_authenticated_login(
|
||||
client: Client,
|
||||
origin: Url,
|
||||
authentication: GatewayAuthentication,
|
||||
profile: OsProfile,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
origin,
|
||||
authentication,
|
||||
profile,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn authentication(&self) -> &GatewayAuthentication {
|
||||
&self.authentication
|
||||
}
|
||||
|
||||
pub fn hip_token(&self) -> String {
|
||||
hip_token(self.authentication.cookie())
|
||||
}
|
||||
|
||||
pub async fn check_hip(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Result<HipCheck, GatewayRequestError> {
|
||||
let mut form = self.hip_form(ipv4, ipv6);
|
||||
form.push(("md5".into(), self.hip_token()));
|
||||
parse_hip_check(&self.post("hipreportcheck.esp", &form).await?)
|
||||
}
|
||||
|
||||
pub async fn submit_hip(
|
||||
&self,
|
||||
report: &str,
|
||||
ipv4: Option<IpAddr>,
|
||||
ipv6: Option<IpAddr>,
|
||||
) -> Result<(), GatewayRequestError> {
|
||||
if report.is_empty() || report.len() > MAX_HIP_REPORT_BYTES || report.contains('\0') {
|
||||
return Err(GatewayRequestError::InvalidReport);
|
||||
}
|
||||
let mut form = self.hip_form(ipv4, ipv6);
|
||||
form.push(("report".into(), report.into()));
|
||||
self.post("hipreport.esp", &form).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn logout(&self) -> Result<(), GatewayRequestError> {
|
||||
logout_cookie(&self.client, &self.origin, self.authentication.cookie(), &self.profile).await
|
||||
}
|
||||
|
||||
fn cookie_form(&self) -> Vec<(String, String)> {
|
||||
url::form_urlencoded::parse(self.authentication.cookie().as_bytes())
|
||||
.into_owned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hip_form(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Vec<(String, String)> {
|
||||
let mut form = self.cookie_form();
|
||||
set_form(&mut form, "client-role", "global-protect-full");
|
||||
set_form(&mut form, "computer", self.profile.computer());
|
||||
set_form(&mut form, "host-id", self.profile.host_id());
|
||||
set_form(&mut form, "serialno", self.profile.serialno());
|
||||
if let Some(ip) = ipv4 {
|
||||
set_form(&mut form, "client-ip", &ip.to_string());
|
||||
}
|
||||
if let Some(ip) = ipv6 {
|
||||
set_form(&mut form, "client-ipv6", &ip.to_string());
|
||||
}
|
||||
form
|
||||
}
|
||||
|
||||
async fn post(&self, endpoint: &str, form: &[(String, String)]) -> Result<Element, GatewayRequestError> {
|
||||
post(&self.client, &self.origin, endpoint, form).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleanup uses trustworthy issued cookie fields even when execution mode is
|
||||
/// invalid. It never creates a runnable authentication with a fabricated mode.
|
||||
pub(crate) async fn logout_cookie(
|
||||
client: &Client,
|
||||
origin: &Url,
|
||||
cookie: &str,
|
||||
profile: &OsProfile,
|
||||
) -> Result<(), GatewayRequestError> {
|
||||
let mut form = url::form_urlencoded::parse(cookie.as_bytes()).into_owned().collect();
|
||||
set_form(&mut form, "computer", profile.computer());
|
||||
set_form(&mut form, "clientos", profile.client_os().as_str());
|
||||
set_form(&mut form, "os-version", profile.os_version());
|
||||
post(client, origin, "logout.esp", &form).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn post(
|
||||
client: &Client,
|
||||
origin: &Url,
|
||||
endpoint: &str,
|
||||
form: &[(String, String)],
|
||||
) -> Result<Element, GatewayRequestError> {
|
||||
let mut url = origin.clone();
|
||||
url.set_path(&format!("/ssl-vpn/{endpoint}"));
|
||||
let response = client.post(url).form(form).send().await?;
|
||||
let status = response.status();
|
||||
let invalid_cookie = status.as_u16() == 512
|
||||
|| response
|
||||
.headers()
|
||||
.get("x-private-pan-globalprotect")
|
||||
.is_some_and(|value| value == "Invalid authentication cookie");
|
||||
if invalid_cookie {
|
||||
return Err(GatewayRequestError::InvalidCookie);
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(GatewayRequestError::Http(status));
|
||||
}
|
||||
let body = crate::utils::request::read_bounded_response(response, MAX_GATEWAY_RESPONSE_BYTES)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
|
||||
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
|
||||
})?;
|
||||
parse_response(&body)
|
||||
}
|
||||
|
||||
pub(crate) fn bound_client(server: &str, params: &GpParams, binding: &GatewayBinding) -> anyhow::Result<Client> {
|
||||
binding.validate_server(server)?;
|
||||
let origin = gateway_origin(server)?;
|
||||
let host = origin
|
||||
.host_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Gateway host is missing"))?;
|
||||
let builder = params
|
||||
.client_builder()?
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.local_address(binding.source().ip())
|
||||
.resolve(host, binding.endpoint())
|
||||
.timeout(REQUEST_TIMEOUT);
|
||||
let builder = bind_interface(builder, binding)?;
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
Ok(builder.interface(binding.interface()))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
if let std::net::SocketAddr::V6(source) = binding.source() {
|
||||
anyhow::ensure!(
|
||||
source.scope_id() == 0,
|
||||
"Scoped IPv6 source requires a native socket connector"
|
||||
);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_origin(server: &str) -> anyhow::Result<Url> {
|
||||
let server = if server.starts_with("https://") {
|
||||
server.to_owned()
|
||||
} else {
|
||||
format!("https://{server}")
|
||||
};
|
||||
let origin = Url::parse(&server)?;
|
||||
anyhow::ensure!(
|
||||
origin.scheme() == "https"
|
||||
&& origin.username().is_empty()
|
||||
&& origin.password().is_none()
|
||||
&& origin.path() == "/"
|
||||
&& origin.query().is_none()
|
||||
&& origin.fragment().is_none(),
|
||||
"Gateway endpoint must be an HTTPS origin"
|
||||
);
|
||||
Ok(origin)
|
||||
}
|
||||
|
||||
fn set_form(form: &mut Vec<(String, String)>, key: &str, value: &str) {
|
||||
form.retain(|(name, _)| name != key);
|
||||
form.push((key.into(), value.into()));
|
||||
}
|
||||
|
||||
/// Match gpst.c::build_csd_token without decoding or reordering cookie fields.
|
||||
pub fn hip_token(cookie: &str) -> String {
|
||||
let stable = cookie
|
||||
.split('&')
|
||||
.filter(|field| {
|
||||
let key = field.split('=').next().unwrap_or_default();
|
||||
!matches!(key, "authcookie" | "preferred-ip" | "preferred-ipv6")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
format!("{:x}", md5::compute(stable.as_bytes()))
|
||||
}
|
||||
|
||||
fn parse_response(body: &[u8]) -> Result<Element, GatewayRequestError> {
|
||||
let text = std::str::from_utf8(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
|
||||
let lower = text.to_ascii_lowercase();
|
||||
if lower.contains("<!doctype") || lower.contains("<!entity") {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
if let Some(error) = javascript_error(text) {
|
||||
return Err(error);
|
||||
}
|
||||
let root = Element::parse(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
|
||||
if root.name == "html" {
|
||||
return Err(
|
||||
root
|
||||
.descendant_text("body")
|
||||
.as_deref()
|
||||
.and_then(javascript_error)
|
||||
.unwrap_or(GatewayRequestError::MalformedResponse),
|
||||
);
|
||||
}
|
||||
if root.name == "prelogin-response" && root.child_text("status").as_deref() == Some("Error") {
|
||||
return Err(message_error(root.child_text("msg").as_deref()));
|
||||
}
|
||||
if root.name != "response" {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
match root.attr("status") {
|
||||
Some("error") => Err(message_error(root.child_text("error").as_deref())),
|
||||
None | Some("success") => Ok(root),
|
||||
_ => Err(GatewayRequestError::Rejected),
|
||||
}
|
||||
}
|
||||
|
||||
fn message_error(message: Option<&str>) -> GatewayRequestError {
|
||||
if message == Some("Invalid authentication cookie") {
|
||||
GatewayRequestError::InvalidCookie
|
||||
} else {
|
||||
GatewayRequestError::Rejected
|
||||
}
|
||||
}
|
||||
|
||||
fn javascript_error(text: &str) -> Option<GatewayRequestError> {
|
||||
static ERROR: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
|
||||
let regex = ERROR.get_or_init(|| {
|
||||
regex::Regex::new(r#"(?s)^\s*var\s+respStatus\s*=\s*"Error"\s*;\s*var\s+respMsg\s*=\s*("(?:\\.|[^"\\])*")"#)
|
||||
.expect("valid GlobalProtect error pattern")
|
||||
});
|
||||
let captures = regex.captures(text)?;
|
||||
match serde_json::from_str::<String>(&captures[1]) {
|
||||
Ok(message) => Some(message_error(Some(&message))),
|
||||
Err(_) => Some(GatewayRequestError::MalformedResponse),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_hip_check(root: &Element) -> Result<HipCheck, GatewayRequestError> {
|
||||
let report_needed = match root.child_text("hip-report-needed").as_deref() {
|
||||
Some("yes") => true,
|
||||
Some("no") => false,
|
||||
_ => return Err(GatewayRequestError::MalformedResponse),
|
||||
};
|
||||
let delay = match root.child_text("delay") {
|
||||
Some(value) => value
|
||||
.parse::<u32>()
|
||||
.map_err(|_| GatewayRequestError::MalformedResponse)?,
|
||||
None => 0,
|
||||
};
|
||||
// Limit this client's supported response delay to one hour. The official
|
||||
// registry scheduling cap is not evidence of a wire-protocol maximum.
|
||||
if delay > 3600 {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
Ok(HipCheck {
|
||||
report_needed,
|
||||
delay: Duration::from_secs(u64::from(delay)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -0,0 +1,246 @@
|
||||
use super::*;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpListener,
|
||||
task::JoinHandle,
|
||||
};
|
||||
|
||||
pub(crate) async fn gateway(responses: Vec<String>) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
|
||||
gateway_fixture(responses, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn login_gateway(responses: Vec<String>) -> (Client, Url, JoinHandle<Vec<(String, String)>>) {
|
||||
let (transport, server) = gateway(responses).await;
|
||||
(transport.client, transport.origin, server)
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_with_first_response_gate(
|
||||
responses: Vec<String>,
|
||||
arrived: std::sync::Arc<tokio::sync::Notify>,
|
||||
release: std::sync::Arc<tokio::sync::Notify>,
|
||||
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
|
||||
gateway_fixture(responses, Some((arrived, release))).await
|
||||
}
|
||||
|
||||
async fn gateway_fixture(
|
||||
responses: Vec<String>,
|
||||
gate: Option<(std::sync::Arc<tokio::sync::Notify>, std::sync::Arc<tokio::sync::Notify>)>,
|
||||
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut requests = Vec::new();
|
||||
for (index, response) in responses.into_iter().enumerate() {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
let (headers_end, length) = loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).await.unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
|
||||
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
key
|
||||
.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse::<usize>().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
break (position + 4, length);
|
||||
}
|
||||
};
|
||||
while bytes.len() < headers_end + length {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).await.unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
let path = std::str::from_utf8(&bytes[..headers_end])
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = String::from_utf8(bytes[headers_end..headers_end + length].to_vec()).unwrap();
|
||||
requests.push((path, body));
|
||||
if index == 0
|
||||
&& let Some((arrived, release)) = &gate
|
||||
{
|
||||
arrived.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
stream.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
requests
|
||||
});
|
||||
let transport = GatewayTransport {
|
||||
client: Client::builder()
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.build()
|
||||
.unwrap(),
|
||||
origin,
|
||||
authentication: GatewayAuthentication::new(
|
||||
"authcookie=test-cookie&portal=portal&user=alice&domain=example&computer=test".into(),
|
||||
"non-tunnel".into(),
|
||||
)
|
||||
.unwrap(),
|
||||
profile: OsProfile::builder(crate::os_profile::ClientOs::Linux)
|
||||
.computer_name_override("test")
|
||||
.build(),
|
||||
};
|
||||
(transport, server)
|
||||
}
|
||||
|
||||
pub(crate) fn response(body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_matches_c_protocol_golden_fixture() {
|
||||
for volatile in [
|
||||
"authcookie=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1",
|
||||
"authcookie=refreshed&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2",
|
||||
] {
|
||||
let cookie =
|
||||
format!("user=test&{volatile}&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&computer=test");
|
||||
assert_eq!(hip_token(&cookie), "20f30054f721fd212925866b5778447d");
|
||||
}
|
||||
assert_ne!(hip_token("user=alice%20bob"), hip_token("user=alice+bob"));
|
||||
assert_ne!(hip_token("user=alice&portal=a"), hip_token("portal=a&user=alice"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maintenance_uses_only_hip_and_logout_with_physical_identity() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed><delay>7</delay></response>"),
|
||||
response("<response status='success'/>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let ipv4 = Some("192.0.2.7".parse().unwrap());
|
||||
let ipv6 = Some("2001:db8::7".parse().unwrap());
|
||||
let check = transport.check_hip(ipv4, ipv6).await.unwrap();
|
||||
assert_eq!(
|
||||
check,
|
||||
HipCheck {
|
||||
report_needed: true,
|
||||
delay: Duration::from_secs(7)
|
||||
}
|
||||
);
|
||||
transport.submit_hip("<hip-report/>", ipv4, ipv6).await.unwrap();
|
||||
transport.logout().await.unwrap();
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(
|
||||
requests.iter().map(|(path, _)| path.as_str()).collect::<Vec<_>>(),
|
||||
[
|
||||
"/ssl-vpn/hipreportcheck.esp",
|
||||
"/ssl-vpn/hipreport.esp",
|
||||
"/ssl-vpn/logout.esp"
|
||||
]
|
||||
);
|
||||
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[0].1).unwrap();
|
||||
assert_eq!(form["authcookie"], "test-cookie");
|
||||
assert_eq!(form["client-ip"], "192.0.2.7");
|
||||
assert_eq!(form["client-ipv6"], "2001:db8::7");
|
||||
assert_eq!(form["md5"], transport.hip_token());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_redirects_without_forwarding_authentication() {
|
||||
let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (transport, server) = gateway(vec![format!(
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{}/stolen\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
destination.local_addr().unwrap()
|
||||
)])
|
||||
.await;
|
||||
assert!(
|
||||
matches!(transport.check_hip(None, None).await, Err(GatewayRequestError::Http(status)) if status.as_u16() == 307)
|
||||
);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), destination.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(server.await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distinguishes_expired_cookie_from_transport_and_protocol_errors() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
|
||||
"HTTP/1.1 512 Invalid Cookie\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
response("<response><hip-report-needed>maybe</hip-report-needed></response>"),
|
||||
response("<response status='error'><error>server-private-payload</error></response>"),
|
||||
])
|
||||
.await;
|
||||
for _ in 0..2 {
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await,
|
||||
Err(GatewayRequestError::InvalidCookie)
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await.unwrap_err(),
|
||||
GatewayRequestError::Http(StatusCode::SERVICE_UNAVAILABLE)
|
||||
));
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await,
|
||||
Err(GatewayRequestError::MalformedResponse)
|
||||
));
|
||||
let error = transport.check_hip(None, None).await.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains("server-private-payload"));
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bounds_response_size_before_reading_body() {
|
||||
let (transport, server) = gateway(vec![format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
MAX_GATEWAY_RESPONSE_BYTES + 1
|
||||
)])
|
||||
.await;
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await,
|
||||
Err(GatewayRequestError::ResponseTooLarge)
|
||||
));
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_delays_and_unsafe_response_xml() {
|
||||
for delay in ["-1", "3601", "4294967296", "invalid"] {
|
||||
let root = parse_response(
|
||||
format!("<response><hip-report-needed>no</hip-report-needed><delay>{delay}</delay></response>").as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(parse_hip_check(&root).is_err());
|
||||
}
|
||||
assert!(parse_response(b"<!DOCTYPE response><response/>").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_cookie_expiry_in_official_error_formats() {
|
||||
for body in [
|
||||
r#"var respStatus = "Error"; var respMsg = "Invalid authentication\u0020cookie"; thisForm.inputStr.value = "";"#,
|
||||
r#"<html><head/><body>var respStatus = "Error"; var respMsg = "Invalid authentication cookie";</body></html>"#,
|
||||
"<prelogin-response><status>Error</status><msg>Invalid authentication cookie</msg></prelogin-response>",
|
||||
] {
|
||||
assert!(matches!(
|
||||
parse_response(body.as_bytes()),
|
||||
Err(GatewayRequestError::InvalidCookie)
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
parse_response(b"<response status='error'><error>Denied</error></response>"),
|
||||
Err(GatewayRequestError::Rejected)
|
||||
));
|
||||
}
|
||||
@@ -1,42 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use log::info;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
pub fn persist_env_vars(extra: Option<HashMap<String, String>>) -> anyhow::Result<NamedTempFile> {
|
||||
let mut env_file = NamedTempFile::new()?;
|
||||
let content = env::vars()
|
||||
.map(|(key, value)| format!("{}={}", key, value))
|
||||
.chain(
|
||||
extra
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(key, value)| format!("{}={}", key, value)),
|
||||
)
|
||||
.collect::<Vec<String>>()
|
||||
.join("\n");
|
||||
|
||||
writeln!(env_file, "{}", content)?;
|
||||
|
||||
Ok(env_file)
|
||||
}
|
||||
|
||||
pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<String, String>> {
|
||||
let content = std::fs::read_to_string(env_file)?;
|
||||
let mut env_vars: HashMap<String, String> = HashMap::new();
|
||||
|
||||
for line in content.lines() {
|
||||
if let Some((key, value)) = line.split_once('=') {
|
||||
env_vars.insert(key.to_string(), value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(env_vars)
|
||||
}
|
||||
|
||||
pub fn patch_gui_runtime_env(hidpi: bool) {
|
||||
if is_wayland_session(
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use std::{borrow::Cow, fs};
|
||||
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::warn;
|
||||
use openssl::pkey::PKey;
|
||||
use pem::parse_many;
|
||||
use anyhow::{Context, ensure};
|
||||
use openssl::{pkey::PKey, x509::X509};
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
@@ -16,72 +15,419 @@ pub enum RequestIdentityError {
|
||||
DecryptError(&'static str),
|
||||
}
|
||||
|
||||
/// Create an identity object from a certificate and key
|
||||
/// The file is expected to be the PKCS#8 PEM or PKCS#12 format
|
||||
/// When using a PKCS#12 file, the key is NOT required, but a passphrase is required
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
if cert.ends_with(".p12") || cert.ends_with(".pfx") {
|
||||
create_identity_from_pkcs12(cert, passphrase)
|
||||
} else {
|
||||
create_identity_from_pem(cert, key, passphrase)
|
||||
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||
/// retains its original bytes and passphrase so each native backend imports the
|
||||
/// same identity and chain. Debug never exposes retained material.
|
||||
#[derive(Clone)]
|
||||
pub struct ClientIdentity {
|
||||
material: Arc<IdentityMaterial>,
|
||||
identity: Identity,
|
||||
}
|
||||
|
||||
struct IdentityMaterial {
|
||||
certificate: Zeroizing<Vec<u8>>,
|
||||
key: Option<Zeroizing<Vec<u8>>>,
|
||||
passphrase: Option<Zeroizing<String>>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ClientIdentity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ClientIdentity")
|
||||
.field("material", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn create_identity_from_pem(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
let cert_pem = fs::read(cert).map_err(|err| anyhow::anyhow!("Failed to read certificate file: {}", err))?;
|
||||
impl ClientIdentity {
|
||||
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
|
||||
let certificate_bytes = read_identity_file(certificate)?;
|
||||
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
|
||||
return Self::from_data(certificate_bytes, None, Some(passphrase));
|
||||
}
|
||||
let key_bytes = match key {
|
||||
Some(path) => read_identity_file(path)?,
|
||||
None => certificate_bytes.clone(),
|
||||
};
|
||||
// Keep the previous first-private-key rule: unrelated later blocks must not
|
||||
// change which key is selected or whether the caller is prompted.
|
||||
let key = pem::parse_many(&*key_bytes)?
|
||||
.into_iter()
|
||||
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
let key_pem = Zeroizing::new(pem::encode(&key));
|
||||
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
|
||||
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
|
||||
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
|
||||
} else {
|
||||
Zeroizing::new(key_pem.as_bytes().to_vec())
|
||||
};
|
||||
// Strip private-key blocks before importing the certificate chain: macOS
|
||||
// otherwise imports the same key twice for combined PEM files.
|
||||
let mut certificate = Zeroizing::new(Vec::new());
|
||||
for cert in X509::stack_from_pem(&certificate_bytes)? {
|
||||
certificate.extend(cert.to_pem()?);
|
||||
}
|
||||
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
|
||||
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
key: Some(key),
|
||||
passphrase: None,
|
||||
}),
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
// Use the certificate as the key if no key is provided
|
||||
let key_pem_file = match key {
|
||||
Some(key) => Cow::Owned(fs::read(key).map_err(|err| anyhow::anyhow!("Failed to read key file: {}", err))?),
|
||||
None => Cow::Borrowed(&cert_pem),
|
||||
};
|
||||
/// A separate key denotes decrypted PEM; no separate key denotes original
|
||||
/// PKCS#12 bytes. Input-size limits belong to the service transport boundary.
|
||||
pub fn from_data(
|
||||
certificate: Zeroizing<Vec<u8>>,
|
||||
key: Option<Zeroizing<Vec<u8>>>,
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
|
||||
None => {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
|
||||
(
|
||||
Identity::from_pkcs12_der(&certificate, passphrase)?,
|
||||
Some(Zeroizing::new(passphrase.to_owned())),
|
||||
)
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
key,
|
||||
passphrase,
|
||||
}),
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
// Find the private key in the pem file
|
||||
let key_pem = parse_many(key_pem_file.as_ref())?
|
||||
.into_iter()
|
||||
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
pub fn certificate_data(&self) -> &[u8] {
|
||||
&self.material.certificate
|
||||
}
|
||||
pub fn key_data(&self) -> Option<&[u8]> {
|
||||
self.material.key.as_ref().map(|key| key.as_slice())
|
||||
}
|
||||
pub fn key_password(&self) -> Option<&str> {
|
||||
self.material.passphrase.as_ref().map(|value| value.as_str())
|
||||
}
|
||||
pub(crate) fn request_identity(&self) -> Identity {
|
||||
self.identity.clone()
|
||||
}
|
||||
|
||||
// The key pem could be encrypted, so we need to decrypt it
|
||||
let decrypted_key_pem = if key_pem.tag().ends_with("ENCRYPTED PRIVATE KEY") {
|
||||
let passphrase = passphrase.ok_or_else(|| {
|
||||
warn!("Key is encrypted but no passphrase provided");
|
||||
RequestIdentityError::NoPassphrase("PEM")
|
||||
})?;
|
||||
let pem_content = pem::encode(&key_pem);
|
||||
let key = PKey::private_key_from_pem_passphrase(pem_content.as_bytes(), passphrase.as_bytes()).map_err(|err| {
|
||||
warn!("Failed to decrypt key: {}", err);
|
||||
RequestIdentityError::DecryptError("PEM")
|
||||
})?;
|
||||
|
||||
key.private_key_to_pem_pkcs8()?
|
||||
} else {
|
||||
pem::encode(&key_pem).into()
|
||||
};
|
||||
|
||||
let identity = Identity::from_pkcs8_pem(&cert_pem, &decrypted_key_pem)?;
|
||||
Ok(identity)
|
||||
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
|
||||
let suffix = if self.material.key.is_some() { ".pem" } else { ".p12" };
|
||||
let certificate = write_identity_file(self.certificate_data(), directory, suffix)?;
|
||||
let key = self
|
||||
.key_data()
|
||||
.map(|key| write_identity_file(key, directory, ".pem"))
|
||||
.transpose()?;
|
||||
Ok(ClientIdentityFiles { certificate, key })
|
||||
}
|
||||
}
|
||||
|
||||
fn create_identity_from_pkcs12(pkcs12: &str, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
let pkcs12 = fs::read(pkcs12)?;
|
||||
/// Named files are private and remain owned until native workers and logout
|
||||
/// finish. The original configured files are never reopened by these workers.
|
||||
pub struct ClientIdentityFiles {
|
||||
certificate: tempfile::NamedTempFile,
|
||||
key: Option<tempfile::NamedTempFile>,
|
||||
}
|
||||
|
||||
let Some(passphrase) = passphrase else {
|
||||
bail!(RequestIdentityError::NoPassphrase("PKCS#12"));
|
||||
impl ClientIdentityFiles {
|
||||
pub fn certificate(&self) -> &str {
|
||||
self.certificate.path().to_str().expect("identity path is UTF-8")
|
||||
}
|
||||
pub fn key(&self) -> Option<&str> {
|
||||
self
|
||||
.key
|
||||
.as_ref()
|
||||
.map(|key| key.path().to_str().expect("identity path is UTF-8"))
|
||||
}
|
||||
}
|
||||
|
||||
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
Ok(Zeroizing::new(
|
||||
fs::read(path).context("Failed to read client identity")?,
|
||||
))
|
||||
}
|
||||
|
||||
fn write_identity_file(
|
||||
bytes: &[u8],
|
||||
directory: Option<&Path>,
|
||||
suffix: &str,
|
||||
) -> anyhow::Result<tempfile::NamedTempFile> {
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix("gp-identity-").suffix(suffix);
|
||||
let mut file = match directory {
|
||||
Some(directory) => builder.tempfile_in(directory)?,
|
||||
None => builder.tempfile()?,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
file.as_file().set_permissions(fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
ensure!(file.path().to_str().is_some(), "Client identity path is not UTF-8");
|
||||
file.write_all(bytes)?;
|
||||
file.flush()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
let identity = Identity::from_pkcs12_der(&pkcs12, passphrase)?;
|
||||
Ok(identity)
|
||||
/// General request clients may load an identity directly. Session owners call
|
||||
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
|
||||
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
|
||||
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "identity-fixture").unwrap();
|
||||
let name = name.build();
|
||||
let mut certificate = X509::builder().unwrap();
|
||||
certificate.set_version(2).unwrap();
|
||||
certificate.set_subject_name(&name).unwrap();
|
||||
certificate.set_issuer_name(&name).unwrap();
|
||||
certificate.set_pubkey(&key).unwrap();
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
certificate.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
(
|
||||
certificate.build().to_pem().unwrap(),
|
||||
key.private_key_to_pem_pkcs8().unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let encrypted = PKey::private_key_from_pem(&key)
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
|
||||
.unwrap();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(&key).unwrap();
|
||||
source.write_all(&encrypted).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_without_key_reports_missing_key_even_with_passphrase() {
|
||||
let (certificate, _) = generated_identity();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
for passphrase in [None, Some("unused")] {
|
||||
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoKey)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_identity_loading_is_not_limited_by_service_message_size() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(&key).unwrap();
|
||||
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
|
||||
cert_file.write_all(&certificate).unwrap();
|
||||
let mut key_file = tempfile::NamedTempFile::new().unwrap();
|
||||
let encrypted = PKey::private_key_from_pem(&key)
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
|
||||
.unwrap();
|
||||
key_file.write_all(&encrypted).unwrap();
|
||||
let cert = cert_file.path().to_str().unwrap();
|
||||
let key_path = Some(key_file.path().to_str().unwrap());
|
||||
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
|
||||
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>().unwrap() {
|
||||
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
|
||||
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
|
||||
other => panic!("Unexpected identity error: {other}"),
|
||||
}
|
||||
}
|
||||
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
|
||||
assert_eq!(loaded.key_data().unwrap(), key);
|
||||
fs::write(key_file.path(), &key).unwrap();
|
||||
for passphrase in [None, Some("ignored for unencrypted key")] {
|
||||
assert_eq!(
|
||||
ClientIdentity::load(cert, key_path, passphrase)
|
||||
.unwrap()
|
||||
.key_data()
|
||||
.unwrap(),
|
||||
key
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (certificate, key) = generated_identity();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
let mut combined = certificate.clone();
|
||||
combined.extend(&key);
|
||||
fs::write(&source, &combined).unwrap();
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
|
||||
fs::write(&source, "changed after authentication").unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
|
||||
let files = identity.write_files(Some(directory.path())).unwrap();
|
||||
let certificate_path = files.certificate().to_owned();
|
||||
let key_path = files.key().unwrap().to_owned();
|
||||
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
|
||||
assert_eq!(fs::read(&key_path).unwrap(), key);
|
||||
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&certificate_path).exists());
|
||||
assert!(!Path::new(&key_path).exists());
|
||||
// The request identity remains valid after its original files disappear.
|
||||
fs::remove_file(&source).unwrap();
|
||||
reqwest::Client::builder()
|
||||
.identity(identity.request_identity())
|
||||
.build()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let certificate = X509::from_pem(&certificate).unwrap();
|
||||
let key = PKey::private_key_from_pem(&key).unwrap();
|
||||
let mut builder = Pkcs12::builder();
|
||||
builder.name("identity-fixture").pkey(&key).cert(&certificate);
|
||||
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
|
||||
for suffix in [".p12", ".pfx"] {
|
||||
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
|
||||
source.write_all(&encoded).unwrap();
|
||||
let path = source.path().to_str().unwrap();
|
||||
assert!(ClientIdentity::load(path, None, None).is_err());
|
||||
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
|
||||
// PKCS#12 has always ignored a separately configured key path.
|
||||
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
|
||||
fs::write(source.path(), b"replaced after login").unwrap();
|
||||
assert_eq!(identity.certificate_data(), encoded);
|
||||
assert!(identity.key_data().is_none());
|
||||
assert_eq!(identity.key_password(), Some("fixture-password"));
|
||||
assert!(!format!("{identity:?}").contains("fixture-password"));
|
||||
let files = identity.write_files(None).unwrap();
|
||||
assert!(files.certificate().ends_with(".p12"));
|
||||
assert!(files.key().is_none());
|
||||
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
|
||||
let owned_path = files.certificate().to_owned();
|
||||
drop(files);
|
||||
assert!(!Path::new(&owned_path).exists());
|
||||
}
|
||||
let empty_password = builder.build2("").unwrap().to_der().unwrap();
|
||||
// Empty-password support varies by native backend and PKCS#12 algorithms.
|
||||
// Match the previous native import instead of introducing another parser.
|
||||
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
|
||||
assert_eq!(
|
||||
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
|
||||
previously_accepted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
rsa::Rsa,
|
||||
stack::Stack,
|
||||
x509::{X509NameBuilder, extension::BasicConstraints},
|
||||
};
|
||||
fn certificate(
|
||||
name: &str,
|
||||
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
|
||||
ca: bool,
|
||||
) -> (X509, PKey<openssl::pkey::Private>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut subject = X509NameBuilder::new().unwrap();
|
||||
subject.append_entry_by_text("CN", name).unwrap();
|
||||
let subject = subject.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
|
||||
.unwrap()
|
||||
.to_asn1_integer()
|
||||
.unwrap();
|
||||
cert.set_serial_number(&serial).unwrap();
|
||||
cert.set_subject_name(&subject).unwrap();
|
||||
cert
|
||||
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
|
||||
.unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
if ca {
|
||||
cert
|
||||
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
cert
|
||||
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
|
||||
.unwrap();
|
||||
(cert.build(), key)
|
||||
}
|
||||
let (root, root_key) = certificate("root", None, true);
|
||||
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
|
||||
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
|
||||
// This is the reverse CA stack consumed by the previous native-tls path.
|
||||
let mut ca = Stack::new().unwrap();
|
||||
ca.push(root.clone()).unwrap();
|
||||
ca.push(intermediate.clone()).unwrap();
|
||||
let mut builder = Pkcs12::builder();
|
||||
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
|
||||
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
|
||||
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
|
||||
source.write_all(&encoded).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
assert_eq!(identity.certificate_data(), encoded);
|
||||
assert!(identity.key_data().is_none());
|
||||
ClientIdentity::from_data(
|
||||
Zeroizing::new(identity.certificate_data().to_vec()),
|
||||
None,
|
||||
identity.key_password(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_from_pem_requires_passphrase() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let identity = create_identity_from_pem(cert, None, None);
|
||||
let identity = create_identity(cert, None, None);
|
||||
|
||||
assert!(identity.is_err());
|
||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
||||
@@ -93,7 +439,7 @@ mod tests {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let passphrase = "badssl.com";
|
||||
|
||||
let identity = create_identity_from_pem(cert, None, Some(passphrase));
|
||||
let identity = create_identity(cert, None, Some(passphrase));
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
@@ -102,7 +448,7 @@ mod tests {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_unencrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client-unencrypted.pem";
|
||||
let identity = create_identity_from_pem(cert, None, None);
|
||||
let identity = create_identity(cert, None, None);
|
||||
println!("{:?}", identity);
|
||||
|
||||
assert!(identity.is_ok());
|
||||
@@ -115,7 +461,7 @@ mod tests {
|
||||
let key = "tests/files/badssl.com-client.pem";
|
||||
let passphrase = "badssl.com";
|
||||
|
||||
let identity = create_identity_from_pem(cert, Some(key), Some(passphrase));
|
||||
let identity = create_identity(cert, Some(key), Some(passphrase));
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
@@ -125,7 +471,7 @@ mod tests {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client.pem";
|
||||
|
||||
let identity = create_identity_from_pem(cert, Some(key), None);
|
||||
let identity = create_identity(cert, Some(key), None);
|
||||
|
||||
assert!(identity.is_err());
|
||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
||||
@@ -137,8 +483,33 @@ mod tests {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client-unencrypted.pem";
|
||||
|
||||
let identity = create_identity_from_pem(cert, Some(key), None);
|
||||
let identity = create_identity(cert, Some(key), None);
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum ResponseBodyError {
|
||||
#[error("Response read failed: {0}")]
|
||||
Transport(#[from] reqwest::Error),
|
||||
#[error("Response exceeds its size limit")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
pub(crate) async fn read_bounded_response(
|
||||
mut response: reqwest::Response,
|
||||
limit: usize,
|
||||
) -> Result<Vec<u8>, ResponseBodyError> {
|
||||
if response.content_length().is_some_and(|length| length > limit as u64) {
|
||||
return Err(ResponseBodyError::TooLarge);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
if chunk.len() > limit.saturating_sub(body.len()) {
|
||||
return Err(ResponseBodyError::TooLarge);
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
@@ -10,7 +10,6 @@ gpapi = { path = "../gpapi" }
|
||||
anyhow.workspace = true
|
||||
askama.workspace = true
|
||||
chrono.workspace = true
|
||||
log.workspace = true
|
||||
netdev.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
+231
-169
@@ -1,10 +1,11 @@
|
||||
use anyhow::{bail, ensure};
|
||||
use askama::Template;
|
||||
use gpapi::os_profile::{ClientOs, OsProfile};
|
||||
use log::debug;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::process::Command;
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use gpapi::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
|
||||
use xmltree::Element;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -82,49 +83,62 @@ fn unique_child<'a>(parent: &'a Element, name: &str) -> anyhow::Result<&'a Eleme
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
|
||||
"md5-sum",
|
||||
"user-name",
|
||||
"domain",
|
||||
"host-name",
|
||||
"host-id",
|
||||
"ip-address",
|
||||
"ipv6-address",
|
||||
"generate-time",
|
||||
];
|
||||
|
||||
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
|
||||
|
||||
/// Refresh only session and current-host fields in a saved HIP report.
|
||||
/// User-edited categories, products, and network-interface entries remain intact.
|
||||
/// Refresh current identity/session values without running product collectors.
|
||||
pub fn refresh_edited_report(edited_xml: &str, input: &ReportInput) -> anyhow::Result<String> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
refresh_edited_report_with_control(edited_xml, input, &budget)
|
||||
}
|
||||
|
||||
pub fn refresh_edited_report_with_control(
|
||||
edited_xml: &str,
|
||||
input: &ReportInput,
|
||||
control: &dyn CollectionControl,
|
||||
) -> anyhow::Result<String> {
|
||||
control.check()?;
|
||||
let mut edited = validate_edited_report(edited_xml)?;
|
||||
let current = validate_edited_report(&generate_report(input)?)?;
|
||||
|
||||
for field in CURRENT_TOP_LEVEL_FIELDS {
|
||||
copy_field(&mut edited, ¤t, field)?;
|
||||
let cookie_params = cookie_params(input);
|
||||
let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity();
|
||||
control.check()?;
|
||||
let domain = format!("{}.internal", identity.domain);
|
||||
let generate_time = get_current_time_components().0;
|
||||
for (name, value) in [
|
||||
("md5-sum", input.context.md5()),
|
||||
("user-name", report_user_name(input, &cookie_params)),
|
||||
("domain", domain.as_str()),
|
||||
("host-name", identity.host_name.as_str()),
|
||||
("host-id", identity.host_id.as_str()),
|
||||
("ip-address", identity.default_ipv4()),
|
||||
("ipv6-address", identity.default_ipv6()),
|
||||
("generate-time", generate_time.as_str()),
|
||||
] {
|
||||
set_field(&mut edited, name, value)?;
|
||||
}
|
||||
|
||||
let edited_host = host_info_mut(&mut edited)?;
|
||||
let current_host = host_info(¤t)?;
|
||||
for field in CURRENT_HOST_INFO_FIELDS {
|
||||
copy_field(edited_host, current_host, field)?;
|
||||
let host_info = host_info_mut(&mut edited)?;
|
||||
for (name, value) in [
|
||||
("client-version", input.profile.client_version()),
|
||||
("os", identity.os_version.as_str()),
|
||||
("os-vendor", identity.os_vendor.as_str()),
|
||||
("domain", domain.as_str()),
|
||||
("host-name", identity.host_name.as_str()),
|
||||
("host-id", identity.host_id.as_str()),
|
||||
] {
|
||||
set_field(host_info, name, value)?;
|
||||
}
|
||||
|
||||
let refreshed = write_xml(&edited)?;
|
||||
validate_edited_report(&refreshed)?;
|
||||
control.check()?;
|
||||
Ok(refreshed)
|
||||
}
|
||||
|
||||
fn copy_field(target: &mut Element, source: &Element, name: &str) -> anyhow::Result<()> {
|
||||
let value = unique_child(source, name)?.children.clone();
|
||||
fn set_field(target: &mut Element, name: &str, value: &str) -> anyhow::Result<()> {
|
||||
let field = target
|
||||
.get_mut_child(name)
|
||||
.ok_or_else(|| anyhow::anyhow!("HIP report is missing <{name}>"))?;
|
||||
field.children = value;
|
||||
field.children = vec![xmltree::XMLNode::Text(value.to_owned())];
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn host_info(root: &Element) -> anyhow::Result<&Element> {
|
||||
unique_child(root, "categories")?
|
||||
.children
|
||||
@@ -194,24 +208,66 @@ pub struct ReportInput {
|
||||
|
||||
/// Generate the same XML report used by `gpclient hip`.
|
||||
pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
let cookie_params: HashMap<String, String> = serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default();
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
generate_report_with_control(input, &budget)
|
||||
}
|
||||
|
||||
/// Identity-only maintenance report. This deliberately does not enumerate the
|
||||
/// machine or execute posture collectors; addresses come from the session owner.
|
||||
pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
let params = cookie_params(input);
|
||||
let mut report = Element::new("hip-report");
|
||||
for (name, value) in [
|
||||
("md5-sum", input.context.md5()),
|
||||
("user-name", report_user_name(input, ¶ms)),
|
||||
("domain", params.get("domain").map(String::as_str).unwrap_or_default()),
|
||||
("host-name", input.profile.computer()),
|
||||
("host-id", input.profile.host_id()),
|
||||
("ip-address", input.context.client_ip().unwrap_or_default()),
|
||||
("ipv6-address", input.context.client_ipv6().unwrap_or_default()),
|
||||
("hip-report-version", "4"),
|
||||
] {
|
||||
let mut field = Element::new(name);
|
||||
field.children.push(xmltree::XMLNode::Text(value.to_owned()));
|
||||
report.children.push(xmltree::XMLNode::Element(field));
|
||||
}
|
||||
let mut timestamp = Element::new("generate-time");
|
||||
timestamp
|
||||
.children
|
||||
.push(xmltree::XMLNode::Text(get_current_time_components().0));
|
||||
report.children.push(xmltree::XMLNode::Element(timestamp));
|
||||
write_xml(&report)
|
||||
}
|
||||
|
||||
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
control.check()?;
|
||||
let cookie_params = cookie_params(input);
|
||||
let (generate_time, day, month, year) = get_current_time_components();
|
||||
let user_name = match input.context {
|
||||
ReportContext::Preview => "[available after connection]",
|
||||
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
|
||||
};
|
||||
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect();
|
||||
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?;
|
||||
let template = HipReportTemplate {
|
||||
client_version: input.profile.client_version(),
|
||||
generate_time,
|
||||
day,
|
||||
month,
|
||||
year,
|
||||
user_name,
|
||||
user_name: report_user_name(input, &cookie_params),
|
||||
host_info,
|
||||
md5: input.context.md5(),
|
||||
};
|
||||
format_xml(&template.render()?)
|
||||
let report = format_xml(&template.render()?)?;
|
||||
control.check()?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
fn cookie_params(input: &ReportInput) -> HashMap<String, String> {
|
||||
serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn report_user_name<'a>(input: &ReportInput, cookie_params: &'a HashMap<String, String>) -> &'a str {
|
||||
match input.context {
|
||||
ReportContext::Preview => "[available after connection]",
|
||||
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
@@ -397,7 +453,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
|
||||
/// Single entry point for collecting host info — dispatches per-OS
|
||||
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
|
||||
fn collect(&self) -> HostInfo {
|
||||
fn collect_identity(&self) -> HostInfo {
|
||||
let runtime_iface = self.collect_network_interface();
|
||||
let primary = self.adapt_primary_interface(&runtime_iface);
|
||||
|
||||
@@ -412,10 +468,10 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
software_version: self.profile.software_version().to_string(),
|
||||
domain: self.domain_for_profile(),
|
||||
network_interfaces: interfaces,
|
||||
defender: self.defender_for_profile(),
|
||||
clamav: self.clamav_for_profile(),
|
||||
sentinel: self.sentinel_for_profile(),
|
||||
ufw: self.ufw_for_profile(),
|
||||
defender: None,
|
||||
clamav: None,
|
||||
sentinel: None,
|
||||
ufw: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,102 +519,81 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn defender_for_profile(&self) -> Option<DefenderInfo> {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Linux => detect_microsoft_defender_blocking(),
|
||||
ClientOs::Mac | ClientOs::Windows => None,
|
||||
fn collect(&self, control: &dyn CollectionControl) -> io::Result<HostInfo> {
|
||||
control.check()?;
|
||||
let mut info = self.collect_identity();
|
||||
control.check()?;
|
||||
let commands = CollectorCommands::new(control);
|
||||
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
|
||||
info.defender = detect_microsoft_defender(&commands)?;
|
||||
info.clamav = detect_clamav(&commands)?;
|
||||
info.ufw = detect_ufw(&commands)?;
|
||||
}
|
||||
}
|
||||
|
||||
fn clamav_for_profile(&self) -> Option<ClamAvInfo> {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Linux => detect_clamav(),
|
||||
ClientOs::Mac | ClientOs::Windows => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ufw_for_profile(&self) -> Option<UfwInfo> {
|
||||
match self.profile.client_os() {
|
||||
ClientOs::Linux => detect_ufw(),
|
||||
ClientOs::Mac | ClientOs::Windows => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn sentinel_for_profile(&self) -> Option<SentinelInfo> {
|
||||
#[cfg(target_os = "macos")]
|
||||
if self.profile.client_os() == ClientOs::Mac && self.profile.is_native() {
|
||||
return sentinel_macos::detect();
|
||||
info.sentinel = sentinel_macos::detect(&commands)?;
|
||||
}
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
|
||||
return sentinel_unix::detect();
|
||||
info.sentinel = sentinel_unix::detect(&commands)?;
|
||||
}
|
||||
None
|
||||
control.check()?;
|
||||
Ok(info)
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_clamav() -> Option<ClamAvInfo> {
|
||||
let version_out = Command::new("clamscan").arg("--version").output().ok()?;
|
||||
if !version_out.status.success() {
|
||||
debug!("clamscan not found or failed");
|
||||
return None;
|
||||
}
|
||||
|
||||
let version_str = String::from_utf8(version_out.stdout).ok()?;
|
||||
let (version, definitions_version) = parse_clamav_version(&version_str)?;
|
||||
|
||||
let rtp_out = Command::new("systemctl")
|
||||
.args(["is-active", "clamav-onaccess.service"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
let real_time_protection = rtp_out.status.success();
|
||||
|
||||
Some(ClamAvInfo {
|
||||
fn detect_clamav(commands: &CollectorCommands<'_>) -> io::Result<Option<ClamAvInfo>> {
|
||||
let Some(version_str) = command_text(commands, "clamscan", &["--version"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some((version, definitions_version)) = parse_clamav_version(&version_str) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let real_time_protection = commands
|
||||
.run("systemctl", &["is-active", "clamav-onaccess.service"])?
|
||||
.is_some_and(|output| output.status.success());
|
||||
Ok(Some(ClamAvInfo {
|
||||
version,
|
||||
definitions_version,
|
||||
real_time_protection,
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fn detect_ufw() -> Option<UfwInfo> {
|
||||
let version_out = Command::new("ufw").arg("version").output().ok()?;
|
||||
if !version_out.status.success() {
|
||||
debug!("ufw not found or failed");
|
||||
return None;
|
||||
}
|
||||
|
||||
let version_str = String::from_utf8(version_out.stdout).ok()?;
|
||||
let version = parse_ufw_version(&version_str)?;
|
||||
|
||||
let is_root = uzers::get_effective_uid() == 0;
|
||||
let status_out = ufw_status_command(is_root).output().ok()?;
|
||||
if !status_out.status.success() {
|
||||
if is_root {
|
||||
log::warn!("ufw status failed while running as root");
|
||||
} else {
|
||||
log::warn!("sudo -n ufw status failed. You may need to configure sudoers to allow execution without a password.");
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let status_str = String::from_utf8(status_out.stdout).ok()?;
|
||||
let is_enabled = parse_ufw_status(&status_str)?;
|
||||
|
||||
Some(UfwInfo { version, is_enabled })
|
||||
}
|
||||
|
||||
fn ufw_status_command(is_root: bool) -> Command {
|
||||
let mut command = if is_root {
|
||||
Command::new("ufw")
|
||||
} else {
|
||||
let mut command = Command::new("sudo");
|
||||
command.args(["-n", "ufw"]);
|
||||
command
|
||||
fn detect_ufw(commands: &CollectorCommands<'_>) -> io::Result<Option<UfwInfo>> {
|
||||
let Some(version_str) = command_text(commands, "ufw", &["version"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(version) = parse_ufw_version(&version_str) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(ufw) = commands.resolve("ufw") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let output = if uzers::get_effective_uid() == 0 {
|
||||
commands.run_path(&ufw, &["status"])?
|
||||
} else {
|
||||
commands.run("sudo", &["-n", &ufw.to_string_lossy(), "status"])?
|
||||
};
|
||||
let Some(output) = output.filter(|output| output.status.success()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(is_enabled) = String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.as_deref()
|
||||
.and_then(parse_ufw_status)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(UfwInfo { version, is_enabled }))
|
||||
}
|
||||
|
||||
command.arg("status").env("LC_ALL", "C");
|
||||
command
|
||||
fn command_text(commands: &CollectorCommands<'_>, name: &str, args: &[&str]) -> io::Result<Option<String>> {
|
||||
Ok(
|
||||
commands
|
||||
.run(name, args)?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok()),
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_clamav_version(output: &str) -> Option<(String, Option<String>)> {
|
||||
@@ -603,24 +638,11 @@ fn parse_ufw_status(output: &str) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
|
||||
let output = Command::new("mdatp")
|
||||
.arg("health")
|
||||
.arg("--output")
|
||||
.arg("json")
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
debug!("mdatp health command failed");
|
||||
return None;
|
||||
}
|
||||
|
||||
let json = String::from_utf8(output.stdout).ok()?;
|
||||
let defender = parse_defender_info(&json)?;
|
||||
|
||||
debug!("Detected Microsoft Defender: {:?}", defender);
|
||||
Some(defender)
|
||||
fn detect_microsoft_defender(commands: &CollectorCommands<'_>) -> io::Result<Option<DefenderInfo>> {
|
||||
let Some(json) = command_text(commands, "mdatp", &["health", "--output", "json"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(parse_defender_info(&json))
|
||||
}
|
||||
|
||||
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
|
||||
@@ -702,9 +724,19 @@ fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> Strin
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
|
||||
"md5-sum",
|
||||
"user-name",
|
||||
"domain",
|
||||
"host-name",
|
||||
"host-id",
|
||||
"ip-address",
|
||||
"ipv6-address",
|
||||
"generate-time",
|
||||
];
|
||||
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
|
||||
use super::*;
|
||||
use gpapi::os_profile::OsProfileBuilder;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
fn make_input(profile: OsProfile) -> ReportInput {
|
||||
ReportInput {
|
||||
@@ -722,13 +754,50 @@ mod tests {
|
||||
OsProfileBuilder::new(client_os).build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_report_contains_session_identity_without_posture() {
|
||||
for os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
|
||||
let mut input = make_input(make_profile(os));
|
||||
input.context = ReportContext::Connected {
|
||||
cookie: "user=alice%26bob&domain=example".into(),
|
||||
client_ip: Some("192.0.2.7".into()),
|
||||
client_ipv6: Some("2001:db8::7".into()),
|
||||
md5: "identity-token".into(),
|
||||
};
|
||||
let xml = generate_identity_report(&input).unwrap();
|
||||
let root = Element::parse(xml.as_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
unique_child(&root, "user-name").unwrap().get_text().unwrap(),
|
||||
"alice&bob"
|
||||
);
|
||||
assert_eq!(
|
||||
unique_child(&root, "ip-address").unwrap().get_text().unwrap(),
|
||||
"192.0.2.7"
|
||||
);
|
||||
assert_eq!(
|
||||
unique_child(&root, "ipv6-address").unwrap().get_text().unwrap(),
|
||||
"2001:db8::7"
|
||||
);
|
||||
assert_eq!(
|
||||
unique_child(&root, "host-id").unwrap().get_text().unwrap(),
|
||||
input.profile.host_id()
|
||||
);
|
||||
assert_eq!(
|
||||
unique_child(&root, "md5-sum").unwrap().get_text().unwrap(),
|
||||
"identity-token"
|
||||
);
|
||||
assert!(root.get_child("categories").is_none());
|
||||
assert!(!xml.contains("ProductInfo"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_info_os_vendor_is_linux_for_linux_profile() {
|
||||
let input = make_input(make_profile(ClientOs::Linux));
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
|
||||
assert_eq!(info.os_vendor, "Linux");
|
||||
}
|
||||
@@ -739,7 +808,7 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Mac);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
|
||||
assert_eq!(info.os_vendor, "Apple");
|
||||
}
|
||||
@@ -750,7 +819,7 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Windows);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
|
||||
assert_eq!(info.os_vendor, "Microsoft");
|
||||
}
|
||||
@@ -761,7 +830,7 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
@@ -775,7 +844,7 @@ mod tests {
|
||||
let profile = make_profile(client_os);
|
||||
let cookie_params: HashMap<String, String> = HashMap::new();
|
||||
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
|
||||
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
|
||||
|
||||
assert_eq!(info.host_id, profile.host_id());
|
||||
}
|
||||
@@ -800,7 +869,7 @@ mod tests {
|
||||
fn mac_report_renders_detected_sentinel_products() {
|
||||
let input = make_input(make_profile(ClientOs::Mac));
|
||||
let cookie_params = HashMap::new();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
|
||||
host_info.sentinel = Some(SentinelInfo {
|
||||
version: "25.3.4.8365".to_string(),
|
||||
real_time_protection: true,
|
||||
@@ -831,7 +900,7 @@ mod tests {
|
||||
fn linux_report_renders_detected_sentinel_antimalware() {
|
||||
let input = make_input(make_profile(ClientOs::Linux));
|
||||
let cookie_params = HashMap::new();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect();
|
||||
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
|
||||
host_info.sentinel = Some(SentinelInfo {
|
||||
version: "25.2.2.14".to_string(),
|
||||
real_time_protection: true,
|
||||
@@ -911,9 +980,22 @@ mod tests {
|
||||
.children
|
||||
.push(xmltree::XMLNode::Element(custom_category));
|
||||
|
||||
let earliest = chrono::Local::now().naive_local().and_utc().timestamp();
|
||||
let refreshed_xml = refresh_edited_report(&write_xml(&saved).unwrap(), &input).unwrap();
|
||||
let latest = chrono::Local::now().naive_local().and_utc().timestamp();
|
||||
let refreshed = validate_edited_report(&refreshed_xml).unwrap();
|
||||
for field in CURRENT_TOP_LEVEL_FIELDS {
|
||||
let timestamp = chrono::NaiveDateTime::parse_from_str(
|
||||
&unique_child(&refreshed, "generate-time").unwrap().get_text().unwrap(),
|
||||
"%m/%d/%Y %H:%M:%S",
|
||||
)
|
||||
.unwrap()
|
||||
.and_utc()
|
||||
.timestamp();
|
||||
assert!((earliest..=latest).contains(×tamp));
|
||||
for field in CURRENT_TOP_LEVEL_FIELDS
|
||||
.iter()
|
||||
.filter(|field| **field != "generate-time")
|
||||
{
|
||||
assert_eq!(
|
||||
unique_child(&refreshed, field).unwrap().get_text(),
|
||||
unique_child(¤t, field).unwrap().get_text()
|
||||
@@ -992,24 +1074,4 @@ mod tests {
|
||||
assert_eq!(parse_ufw_status("Status: inactive\n"), Some(false));
|
||||
assert_eq!(parse_ufw_status("Status: unknown\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_ufw_status_directly_as_root() {
|
||||
let command = ufw_status_command(true);
|
||||
|
||||
assert_eq!(command.get_program(), OsStr::new("ufw"));
|
||||
assert!(command.get_args().eq(["status"].into_iter().map(OsStr::new)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_ufw_status_through_non_interactive_sudo_as_non_root() {
|
||||
let command = ufw_status_command(false);
|
||||
|
||||
assert_eq!(command.get_program(), OsStr::new("sudo"));
|
||||
assert!(
|
||||
command
|
||||
.get_args()
|
||||
.eq(["-n", "ufw", "status"].into_iter().map(OsStr::new))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,44 @@
|
||||
use std::{
|
||||
fs,
|
||||
fs, io,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::Path,
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use gpapi::process::collection::CollectorCommands;
|
||||
|
||||
use super::SentinelInfo;
|
||||
|
||||
const SENTINELCTL: &str = "/Library/Sentinel/sentinel-agent.bundle/Contents/MacOS/sentinelctl";
|
||||
|
||||
pub(super) fn detect() -> Option<SentinelInfo> {
|
||||
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
|
||||
if !trusted_cli(Path::new(SENTINELCTL)) {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let status = run(&["status"])?;
|
||||
let status = parse_status(&status)?;
|
||||
let Some(status) = run(commands, &["status"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(status) = parse_status(&status) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let real_time_protection = if status.active {
|
||||
let scan_status = run(&["scan-on-write"])?;
|
||||
parse_yes_no(scan_status.trim().strip_prefix("scan-on-write:")?)?
|
||||
let Some(scan_status) = run(commands, &["scan-on-write"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(enabled) = scan_status.trim().strip_prefix("scan-on-write:").and_then(parse_yes_no) else {
|
||||
return Ok(None);
|
||||
};
|
||||
enabled
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let firewall_enabled = run(&["firewall", "enabled"]).as_deref().and_then(parse_yes_no);
|
||||
|
||||
Some(SentinelInfo {
|
||||
let firewall_enabled = run(commands, &["firewall", "enabled"])?
|
||||
.as_deref()
|
||||
.and_then(parse_yes_no);
|
||||
Ok(Some(SentinelInfo {
|
||||
version: status.version,
|
||||
real_time_protection,
|
||||
firewall_enabled,
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fn trusted_cli(path: &Path) -> bool {
|
||||
@@ -47,17 +57,13 @@ fn trusted_cli(path: &Path) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> Option<String> {
|
||||
let output = Command::new(SENTINELCTL)
|
||||
.args(args)
|
||||
.env("LC_ALL", "C")
|
||||
.env_remove("SENTINEL_OUTPUT_JSON")
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(output.stdout).ok()
|
||||
fn run(commands: &CollectorCommands<'_>, args: &[&str]) -> io::Result<Option<String>> {
|
||||
Ok(
|
||||
commands
|
||||
.run_path(Path::new(SENTINELCTL), args)?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok()),
|
||||
)
|
||||
}
|
||||
|
||||
struct AgentStatus {
|
||||
|
||||
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user