mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6cf639887 | ||
|
|
197cd5748d | ||
|
|
907e161b12 | ||
|
|
b26a416f45 | ||
|
|
0212b7ff91 | ||
|
|
9001b768c1 | ||
|
|
a02dfd10ab | ||
|
|
6ebffad3c8 | ||
|
|
c84bfcc13a | ||
|
|
aa92251d47 | ||
|
|
b15bc2bfa5 | ||
|
|
d825e2b9c8 | ||
|
|
dcc74d805b | ||
|
|
43eda033e5 | ||
|
|
54b4d810d9 | ||
|
|
e108ce50dc | ||
|
|
18ce000640 | ||
|
|
14c4e24e0e | ||
|
|
37c88c7adb | ||
|
|
f2ec8c7770 | ||
|
|
1698397af3 | ||
|
|
eb8f919121 | ||
|
|
b4529398b0 | ||
|
|
c53911e7b8 | ||
|
|
580438e8eb | ||
|
|
92943e0a9d | ||
|
|
6f2f8e1265 | ||
|
|
f643180b59 | ||
|
|
3a643fe6ff | ||
|
|
66b1cf3c47 | ||
|
|
472806ca73 | ||
|
|
d7de2df53b | ||
|
|
6ef2f0497d | ||
|
|
0436a18e42 | ||
|
|
56489a4e90 | ||
|
|
6316f8d68e | ||
|
|
d9e00bc3c9 | ||
|
|
e284840d89 | ||
|
|
0df25fbd28 | ||
|
|
8e3bb8ff11 | ||
|
|
a7c571a2c1 | ||
|
|
2b38de10f6 | ||
|
|
4aa7b66313 | ||
|
|
ce5a19c131 | ||
|
|
e7ddc2ca2a | ||
|
|
4635b1b4b8 | ||
|
|
0cb246b0c5 | ||
|
|
fabc7d4461 | ||
|
|
d2fcf66be8 | ||
|
|
ae504dfbbe | ||
|
|
fca3076b64 | ||
|
|
c29c57639a | ||
|
|
da90bc80e3 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# Keep source and build scripts consistent on every platform.
|
||||
* text=auto eol=lf
|
||||
@@ -1,186 +0,0 @@
|
||||
name: Build Windows package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gp_ref:
|
||||
type: string
|
||||
required: true
|
||||
gpgui_ref:
|
||||
type: string
|
||||
required: true
|
||||
channel:
|
||||
type: choice
|
||||
options: [snapshot, stable]
|
||||
default: snapshot
|
||||
build:
|
||||
type: string
|
||||
required: true
|
||||
architecture:
|
||||
type: choice
|
||||
options: [x64, arm64]
|
||||
required: true
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
type: string
|
||||
required: true
|
||||
gpgui_ref:
|
||||
type: string
|
||||
required: true
|
||||
channel:
|
||||
type: string
|
||||
required: true
|
||||
build:
|
||||
type: string
|
||||
required: true
|
||||
architecture:
|
||||
type: string
|
||||
required: true
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
WINDOWS_UPDATE_PRIVATE_KEY:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ inputs.architecture == 'arm64' && 'windows-11-arm' || 'windows-2022' }}
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
BUILD_ARCHITECTURE: ${{ inputs.architecture }}
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/target-windows
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.channel == 'snapshot' && inputs.build || '' }}
|
||||
GPGUI_WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
steps:
|
||||
- name: Select native build tools
|
||||
id: native
|
||||
shell: pwsh
|
||||
run: |
|
||||
if ($env:BUILD_ARCHITECTURE -eq 'arm64') {
|
||||
'msystem=CLANGARM64' >> $env:GITHUB_OUTPUT
|
||||
'subsystem=clangarm64' >> $env:GITHUB_OUTPUT
|
||||
'packages=mingw-w64-clang-aarch64-clang mingw-w64-clang-aarch64-pkgconf mingw-w64-clang-aarch64-gnutls mingw-w64-clang-aarch64-libxml2 mingw-w64-clang-aarch64-lz4' >> $env:GITHUB_OUTPUT
|
||||
} elseif ($env:BUILD_ARCHITECTURE -eq 'x64') {
|
||||
'msystem=UCRT64' >> $env:GITHUB_OUTPUT
|
||||
'subsystem=ucrt64' >> $env:GITHUB_OUTPUT
|
||||
'packages=mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-pkgconf mingw-w64-ucrt-x86_64-gnutls mingw-w64-ucrt-x86_64-libxml2 mingw-w64-ucrt-x86_64-lz4' >> $env:GITHUB_OUTPUT
|
||||
} else { throw 'Unsupported Windows architecture.' }
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
path: .ci
|
||||
persist-credentials: false
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.gp_ref }}
|
||||
path: source/gp
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
- uses: ./.ci/.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: source/gpgui
|
||||
- uses: dtolnay/[email protected]
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- uses: msys2/setup-msys2@v2
|
||||
id: msys2
|
||||
with:
|
||||
msystem: ${{ steps.native.outputs.msystem }}
|
||||
update: true
|
||||
install: >-
|
||||
base-devel autoconf automake libtool gettext git
|
||||
${{ steps.native.outputs.packages }}
|
||||
- name: Prepare pinned installer and driver inputs
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (!$env:GPGUI_WINDOWS_UPDATE_PUBLIC_KEY -or !$env:GPGUI_LICENSE_SIGNING_KEYS) { throw 'Configure the Windows update and licensing public keys.' }
|
||||
$tools = Join-Path $env:RUNNER_TEMP 'windows-tools'
|
||||
New-Item -ItemType Directory -Force $tools | Out-Null
|
||||
choco install nsis --version=3.12.0 --yes --no-progress
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Installing NSIS 3.12 failed.' }
|
||||
$wintun = Join-Path $tools 'wintun.zip'
|
||||
Invoke-WebRequest 'https://www.wintun.net/builds/wintun-0.14.1.zip' -OutFile $wintun
|
||||
if ((Get-FileHash $wintun).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') { throw 'Wintun checksum mismatch.' }
|
||||
Expand-Archive $wintun $tools
|
||||
Remove-Item $wintun
|
||||
"WINDOWS_BUILD_TOOLS=$tools" >> $env:GITHUB_ENV
|
||||
- name: Build OpenConnect and test native packet transport
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$prefix = Join-Path $env:RUNNER_TEMP 'native-windows'
|
||||
& ./source/gp/scripts/build-openconnect-windows.ps1 -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} -Prefix $prefix
|
||||
& ./source/gp/scripts/test-openconnect-windows.ps1 -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} -Prefix $prefix
|
||||
"OPENCONNECT_WINDOWS_PREFIX=$prefix" >> $env:GITHUB_ENV
|
||||
- name: Build and package the matching Windows runtime
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$log = Join-Path $env:RUNNER_TEMP 'windows-package.log'
|
||||
# Compiler diagnostics may contain private GUI source. Keep them on the runner.
|
||||
try {
|
||||
& ./source/gpgui/scripts/build-windows.ps1 -Profile Release `
|
||||
-NativePrefix $env:OPENCONNECT_WINDOWS_PREFIX -MsysRoot $env:MSYS_ROOT -MsysSubsystem ${{ steps.native.outputs.subsystem }} `
|
||||
-WintunDirectory (Join-Path $env:WINDOWS_BUILD_TOOLS 'wintun') `
|
||||
-MakeNsis (Join-Path ${env:ProgramFiles(x86)} 'NSIS/makensis.exe') `
|
||||
-OutputDirectory "$env:GITHUB_WORKSPACE/artifacts" *> $log
|
||||
} catch {
|
||||
python ./.ci/scripts/private-ci-diagnostics.py compile $log
|
||||
throw 'Windows compilation or packaging failed; private diagnostics remain on the runner.'
|
||||
}
|
||||
Write-Host 'Windows compilation and packaging passed.'
|
||||
- name: Sign and verify update payload
|
||||
id: sign
|
||||
shell: pwsh
|
||||
env:
|
||||
UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$key = Join-Path $env:RUNNER_TEMP 'windows-update.key'
|
||||
try {
|
||||
[IO.File]::WriteAllText($key, $env:UPDATE_PRIVATE_KEY.Trim())
|
||||
. ./source/gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools "$env:GITHUB_WORKSPACE/artifacts/tools" -Architecture $env:BUILD_ARCHITECTURE
|
||||
$installer = @(Get-ChildItem artifacts -Filter '*-setup.exe')
|
||||
if ($installer.Count -ne 1) { throw 'Expected exactly one Windows installer.' }
|
||||
$signature = (& $tools.Tool sign -f $key $installer[0].FullName | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows update signing failed.' }
|
||||
& $tools.Tool verify -p $env:GPGUI_WINDOWS_UPDATE_PUBLIC_KEY -s $signature $installer[0].FullName
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows update signature verification failed.' }
|
||||
$signature | Set-Content ($installer[0].FullName + '.sig') -Encoding ascii
|
||||
} finally {
|
||||
Remove-Item $key -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item artifacts/tools -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
- name: Test native installer and uninstaller
|
||||
shell: pwsh
|
||||
run: |
|
||||
$installer = @(Get-ChildItem artifacts -Filter '*-setup.exe')
|
||||
if ($installer.Count -ne 1) { throw 'Expected exactly one Windows installer.' }
|
||||
& ./source/gp/scripts/test-windows-installer.ps1 -Installer $installer[0].FullName -Architecture $env:BUILD_ARCHITECTURE -Build $env:GPGUI_BUILD_VERSION
|
||||
- uses: actions/upload-artifact@v7
|
||||
if: ${{ !cancelled() && steps.sign.outcome == 'success' }}
|
||||
with:
|
||||
name: artifact-gpgui-windows-${{ inputs.architecture }}
|
||||
path: |
|
||||
artifacts/*.exe
|
||||
artifacts/*.exe.sig
|
||||
artifacts/*.exe.sha256
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
@@ -42,11 +42,6 @@ on:
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_windows:
|
||||
description: 'Build Windows x64 and ARM64 NSH installers'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
push:
|
||||
paths-ignore:
|
||||
- LICENSE
|
||||
@@ -470,24 +465,6 @@ jobs:
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
|
||||
build-windows:
|
||||
needs: validate-inputs
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_windows) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_WINDOWS_ON_TAG == 'true') }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
architecture: [x64, arm64]
|
||||
uses: ./.github/workflows/build-windows.yaml
|
||||
with:
|
||||
architecture: ${{ matrix.architecture }}
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
build: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
WINDOWS_UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
|
||||
|
||||
nix-source:
|
||||
needs: [validate-inputs, build-gpgui-glibc]
|
||||
strategy:
|
||||
@@ -1214,7 +1191,6 @@ jobs:
|
||||
- build-gpgui-glibc
|
||||
- build-gpgui-musl
|
||||
- build-gpgui-nsh
|
||||
- build-windows
|
||||
- setup-bsd-matrix
|
||||
- build-gpgui-frontend
|
||||
- build-bsd
|
||||
@@ -1225,7 +1201,6 @@ jobs:
|
||||
NEEDS_JSON: ${{ toJson(needs) }}
|
||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
BUILD_WINDOWS: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_windows) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_WINDOWS_ON_TAG == 'true') }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
@@ -1245,8 +1220,6 @@ jobs:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
elif name == "build-windows" and result == "skipped" and os.environ["BUILD_WINDOWS"] != "true":
|
||||
continue
|
||||
elif result == "skipped":
|
||||
failed.append(f"{name}: {result}")
|
||||
|
||||
|
||||
@@ -34,10 +34,6 @@ on:
|
||||
highlights:
|
||||
required: false
|
||||
type: string
|
||||
unix_snapshot_build:
|
||||
description: Verified Unix snapshot build when it differs from the macOS retry
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
required: false
|
||||
default: linux,freebsd,openbsd
|
||||
@@ -79,10 +75,6 @@ on:
|
||||
description: Stable release highlights, one per line
|
||||
required: false
|
||||
type: string
|
||||
unix_snapshot_build:
|
||||
description: Verified Unix snapshot build; omit when it matches the macOS build
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
|
||||
required: true
|
||||
@@ -95,8 +87,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
# Feed verification runs host tools, so it can use Intel runner capacity.
|
||||
runs-on: macos-26-intel
|
||||
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -112,7 +103,6 @@ jobs:
|
||||
SPARKLE_VERSION: 2.9.2
|
||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
|
||||
UNIX_SNAPSHOT_BUILD: ${{ inputs.unix_snapshot_build }}
|
||||
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
@@ -135,12 +125,6 @@ jobs:
|
||||
echo "unix_platforms must list published Unix targets separated by commas" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -n "$UNIX_SNAPSHOT_BUILD" ]]; then
|
||||
if [[ "$CHANNEL" != "snapshot" || ! "$UNIX_SNAPSHOT_BUILD" =~ ^(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*)){0,2}$ ]]; then
|
||||
echo "unix_snapshot_build requires a snapshot channel and one to three numeric components" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
|
||||
echo "The snapshot channel must publish to the snapshot release" >&2
|
||||
exit 1
|
||||
@@ -359,7 +343,6 @@ jobs:
|
||||
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Prepare Unix update manifest
|
||||
id: unix_manifest
|
||||
env:
|
||||
RELEASED_AT: ${{ steps.release.outputs.released_at }}
|
||||
run: |
|
||||
@@ -400,8 +383,7 @@ jobs:
|
||||
else
|
||||
printf 'Development snapshot after %s.\n' \
|
||||
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
|
||||
unix_build="${UNIX_SNAPSHOT_BUILD:-${{ steps.bundle.outputs.version }}}"
|
||||
generate_args+=(--build "$unix_build")
|
||||
generate_args+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
released_at="$(date -u +%F)"
|
||||
fi
|
||||
|
||||
@@ -410,9 +392,6 @@ jobs:
|
||||
--released-at "$released_at" \
|
||||
--highlights-file "$highlights" \
|
||||
--output "$manifest"
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
echo "build=$unix_build" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Fetch current appcast
|
||||
id: current-appcast
|
||||
@@ -548,13 +527,6 @@ jobs:
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
|
||||
|
||||
- name: Preserve other platform feeds
|
||||
run: |
|
||||
python3 scripts/preserve-update-feeds.py \
|
||||
--base-url "${FEED_URL%/appcast.xml}" \
|
||||
--directory gpgui/apps/update-feed-worker/public \
|
||||
--exclude appcast.xml --exclude latest.json
|
||||
|
||||
- name: Deploy update feed worker
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
@@ -608,7 +580,7 @@ jobs:
|
||||
--version "${{ steps.bundle.outputs.short_version }}"
|
||||
)
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
expected+=(--build "${{ steps.unix_manifest.outputs.build }}")
|
||||
expected+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
fi
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl --fail --location --silent --show-error \
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
name: Publish Windows update feed
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
description: gpgui ref containing the update Worker and pinned WinSparkle tools
|
||||
required: true
|
||||
default: main
|
||||
type: string
|
||||
release_tag:
|
||||
description: GitHub release containing both tested native installers and signatures
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
description: Base product version (x.y.z)
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
description: Update channel
|
||||
required: true
|
||||
type: choice
|
||||
options: [stable, snapshot]
|
||||
build:
|
||||
description: Numeric snapshot build; empty for stable
|
||||
type: string
|
||||
highlights:
|
||||
description: Release highlights, one per line
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: update-feeds
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: windows-latest
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
REPOSITORY: yuezk/GlobalProtect-openconnect
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
PRODUCT_VERSION: ${{ inputs.version }}
|
||||
UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
BUILD_VERSION: ${{ inputs.build }}
|
||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||
WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
UPDATES_WORKER_NAME: ${{ vars.UPDATES_WORKER_NAME || 'gp-updates' }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Checkout update Worker and build helpers
|
||||
uses: ./.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 9.15.1
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
- name: Verify both tested native installers
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:PRODUCT_VERSION -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid product version.' }
|
||||
if ($env:UPDATE_CHANNEL -eq 'stable') {
|
||||
if ($env:RELEASE_TAG -ne "v$env:PRODUCT_VERSION" -or $env:BUILD_VERSION) { throw 'Stable release identity does not match.' }
|
||||
} elseif ($env:RELEASE_TAG -ne 'snapshot' -or $env:BUILD_VERSION -notmatch '^\d+(\.\d+){0,2}$') { throw 'Snapshot release identity does not match.' }
|
||||
$displayVersion = $env:PRODUCT_VERSION
|
||||
if ($env:UPDATE_CHANNEL -eq 'snapshot') { $displayVersion += "-snapshot.$env:BUILD_VERSION" }
|
||||
if (!$env:WINDOWS_UPDATE_PUBLIC_KEY) { throw 'Configure the Windows public update key before promotion.' }
|
||||
$downloads = Join-Path $env:RUNNER_TEMP 'windows-update'
|
||||
New-Item -ItemType Directory -Force $downloads | Out-Null
|
||||
. ./gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools (Join-Path $env:RUNNER_TEMP 'signing-tools')
|
||||
foreach ($architecture in @('x64','arm64')) {
|
||||
$name = "GPConnect_${displayVersion}_windows-$architecture-setup.exe"
|
||||
foreach ($asset in @($name, "$name.sig", "$name.sha256")) {
|
||||
gh release download $env:RELEASE_TAG --repo $env:REPOSITORY --pattern $asset --dir $downloads
|
||||
if ($LASTEXITCODE -ne 0) { throw "Missing release asset: $asset" }
|
||||
}
|
||||
$installer = Join-Path $downloads $name
|
||||
$sum = (Get-Content "$installer.sha256" -Raw).Trim()
|
||||
if ($sum -notmatch '^([a-fA-F0-9]{64}) (.+)$' -or $Matches[2] -ne $name) { throw 'Invalid installer checksum file.' }
|
||||
if ((Get-FileHash $installer).Hash -ne $Matches[1]) { throw 'Installer checksum mismatch.' }
|
||||
if ($env:WINDOWS_SIGNING_PUBLISHER) {
|
||||
$authenticode = Get-AuthenticodeSignature $installer
|
||||
if ($authenticode.Status -ne 'Valid' -or $authenticode.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false) -ne $env:WINDOWS_SIGNING_PUBLISHER) { throw 'Installer publisher signature is invalid.' }
|
||||
}
|
||||
if ([Diagnostics.FileVersionInfo]::GetVersionInfo($installer).ProductVersion -ne $displayVersion) { throw 'Installer product version/build mismatch.' }
|
||||
$signature = (Get-Content "$installer.sig" -Raw).Trim()
|
||||
& $tools.Tool verify -p $env:WINDOWS_UPDATE_PUBLIC_KEY -s $signature $installer
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Installer update signature is invalid.' }
|
||||
}
|
||||
"WINDOWS_DISPLAY_VERSION=$displayVersion" >> $env:GITHUB_ENV
|
||||
- name: Preserve other feeds and generate Windows metadata
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$public = 'gpgui/apps/update-feed-worker/public'
|
||||
python scripts/preserve-update-feeds.py --base-url https://updates.gpgui.com --directory $public
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not preserve published feeds.' }
|
||||
$notes = Join-Path $env:RUNNER_TEMP 'windows-highlights.txt'
|
||||
$env:UPDATE_HIGHLIGHTS | Set-Content $notes -Encoding utf8NoBOM
|
||||
$output = Join-Path $public 'windows'
|
||||
$previous = Join-Path $output 'latest.json'
|
||||
$arguments = @('scripts/windows-update-feed.py', '--version', $env:PRODUCT_VERSION,
|
||||
'--channel', $env:UPDATE_CHANNEL, '--released-at', [DateTime]::UtcNow.ToString('yyyy-MM-dd'),
|
||||
'--highlights-file', $notes, '--output', $output)
|
||||
foreach ($architecture in @('x64','arm64')) {
|
||||
$name = "GPConnect_$($env:WINDOWS_DISPLAY_VERSION)_windows-$architecture-setup.exe"
|
||||
$installer = Join-Path (Join-Path $env:RUNNER_TEMP 'windows-update') $name
|
||||
$arguments += @('--payload', $architecture, $installer,
|
||||
"https://github.com/$env:REPOSITORY/releases/download/$env:RELEASE_TAG/$name", "$installer.sig")
|
||||
}
|
||||
if (Test-Path $previous) { $arguments += @('--input', $previous) }
|
||||
if ($env:BUILD_VERSION) { $arguments += @('--build', $env:BUILD_VERSION) }
|
||||
python @arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Invalid Windows metadata.' }
|
||||
- name: Deploy complete feed set
|
||||
shell: pwsh
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
pnpm --dir gpgui/apps/update-feed-worker install --frozen-lockfile --ignore-scripts
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Worker dependency installation failed.' }
|
||||
pnpm --dir gpgui/apps/update-feed-worker exec wrangler deploy --config wrangler.jsonc --name $env:UPDATES_WORKER_NAME
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Feed deployment failed.' }
|
||||
- name: Verify published Windows metadata
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$windows = 'gpgui/apps/update-feed-worker/public/windows'
|
||||
$feeds = @('latest.json', 'stable/appcast.xml', 'snapshot/appcast.xml') | Where-Object { Test-Path (Join-Path $windows $_) }
|
||||
foreach ($relative in $feeds) {
|
||||
$expected = [IO.File]::ReadAllBytes((Join-Path 'gpgui/apps/update-feed-worker/public/windows' $relative))
|
||||
$downloaded = Join-Path $env:RUNNER_TEMP ('published-' + ($relative -replace '/', '-'))
|
||||
$matched = $false
|
||||
foreach ($attempt in 1..10) {
|
||||
try {
|
||||
Invoke-WebRequest "https://updates.gpgui.com/windows/$relative" -UserAgent 'GPConnectReleasePublisher/1.0' -OutFile $downloaded
|
||||
$actual = [IO.File]::ReadAllBytes($downloaded)
|
||||
$matched = [Convert]::ToBase64String($expected) -eq [Convert]::ToBase64String($actual)
|
||||
} catch {
|
||||
Write-Host "Waiting for published feed: $relative ($attempt/10)"
|
||||
}
|
||||
if ($matched) { break }
|
||||
if ($attempt -lt 10) { Start-Sleep -Seconds 3 }
|
||||
}
|
||||
if (!$matched) { throw "Published feed does not match: $relative" }
|
||||
}
|
||||
@@ -16,6 +16,3 @@ gen
|
||||
|
||||
# Nix files
|
||||
result
|
||||
|
||||
# Packages & test assets
|
||||
*.ipa
|
||||
Generated
+24
-85
@@ -292,13 +292,11 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "auth"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"block2",
|
||||
"browser-launcher",
|
||||
"common",
|
||||
"dunce",
|
||||
"gpapi",
|
||||
"gtk",
|
||||
"html-escape",
|
||||
@@ -309,7 +307,6 @@ dependencies = [
|
||||
"objc2-security",
|
||||
"objc2-web-kit",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tempfile",
|
||||
"tiny_http",
|
||||
@@ -319,9 +316,6 @@ dependencies = [
|
||||
"uuid",
|
||||
"uzers",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"winreg 0.55.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -553,14 +547,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "browser-launcher"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"log",
|
||||
"open",
|
||||
"webbrowser",
|
||||
"which",
|
||||
"winreg 0.55.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -918,7 +911,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
@@ -1558,7 +1551,7 @@ dependencies = [
|
||||
"rustc_version",
|
||||
"toml 1.1.8+spec-1.1.0",
|
||||
"vswhom",
|
||||
"winreg 0.56.0",
|
||||
"winreg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1662,16 +1655,6 @@ dependencies = [
|
||||
"rustc_version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "file-rotate"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e8e2fa049328a1f3295991407a88585805d126dfaadf74b9fe8c194c730aafc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"flate2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filedescriptor"
|
||||
version = "0.8.3"
|
||||
@@ -2132,7 +2115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpapi"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2141,7 +2124,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
"clap-verbosity-flag",
|
||||
"cms",
|
||||
"common",
|
||||
"directories",
|
||||
"dns-lookup",
|
||||
@@ -2160,7 +2142,6 @@ dependencies = [
|
||||
"oslog",
|
||||
"p12-keystore",
|
||||
"pem",
|
||||
"pkcs12",
|
||||
"pkcs8",
|
||||
"pkg-config",
|
||||
"proptest",
|
||||
@@ -2168,7 +2149,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-pemfile",
|
||||
"rustls-platform-verifier",
|
||||
"sec1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
@@ -2186,7 +2167,6 @@ dependencies = [
|
||||
"uuid",
|
||||
"uzers",
|
||||
"whoami",
|
||||
"windows-sys 0.61.2",
|
||||
"x509-cert",
|
||||
"xmltree",
|
||||
"zeroize",
|
||||
@@ -2194,7 +2174,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpauth"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"auth",
|
||||
@@ -2213,7 +2193,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpclient"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2244,7 +2224,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpgui-helper"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2265,7 +2245,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gphip"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
@@ -2282,7 +2262,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpservice"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -2291,7 +2271,6 @@ dependencies = [
|
||||
"common",
|
||||
"compile-time",
|
||||
"env_logger",
|
||||
"file-rotate",
|
||||
"futures",
|
||||
"getrandom 0.4.3",
|
||||
"gpapi",
|
||||
@@ -2312,15 +2291,13 @@ dependencies = [
|
||||
"tokio-tungstenite 0.30.0",
|
||||
"tokio-util",
|
||||
"uuid",
|
||||
"windows-service",
|
||||
"windows-sys 0.61.2",
|
||||
"xz2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gptunnel"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"gpapi",
|
||||
"log",
|
||||
@@ -2332,17 +2309,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpvpnc"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"ipnet",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"winreg 0.56.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2844,9 +2813,6 @@ name = "ipnet"
|
||||
version = "2.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-docker"
|
||||
@@ -3857,7 +3823,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openconnect"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"autotools",
|
||||
"cc",
|
||||
@@ -3867,7 +3833,6 @@ dependencies = [
|
||||
"log",
|
||||
"pkg-config",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4915,6 +4880,16 @@ dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"
|
||||
dependencies = [
|
||||
"der",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -6763,12 +6738,6 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "widestring"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
@@ -6919,17 +6888,6 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-service"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"widestring",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
@@ -6957,15 +6915,6 @@ dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
@@ -7132,16 +7081,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.55.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.56.0"
|
||||
|
||||
+2
-1
@@ -11,7 +11,7 @@ members = [
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
@@ -24,6 +24,7 @@ base64 = { version = "0.23", default-features = false, features = ["std"] }
|
||||
chrono = "0.4"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap-verbosity-flag = "3"
|
||||
ctrlc = "3.4"
|
||||
directories = "6.0"
|
||||
dns-lookup = "4.0.2"
|
||||
env_logger = "0.11"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A GlobalProtect VPN client built on OpenConnect. It provides command-line tools (`gpclient`) and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
|
||||
> **Disclaimer**: GP Connect is an independent third-party client for GlobalProtect VPN networks. It is not affiliated with or endorsed by Palo Alto Networks, Inc.
|
||||
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">
|
||||
<picture>
|
||||
@@ -24,89 +22,147 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
- [Fedora / RHEL](#fedora--rhel)
|
||||
- [openSUSE](#opensuse)
|
||||
- [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)
|
||||
- [Docker](#docker)
|
||||
- [Official Docker Image](#official-docker-image)
|
||||
- [Other Distributions](#other-distributions)
|
||||
- [Building from Source](#building-from-source)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||
- [NetworkManager Integration](#networkmanager-integration)
|
||||
- [Licensing](#licensing)
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**)
|
||||
- **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
|
||||
- **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
|
||||
- **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
|
||||
- **Automated HIP Reports** – Built-in HIP report generation or custom scripts
|
||||
- **Multi-Portal & Direct Gateway** – Manage multiple saved portals or connect directly to a gateway
|
||||
- **Desktop Integration** – Theme-aware system tray icon, auto-connect on launch, and reconnect on wake
|
||||
- **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
|
||||
- **Multi-Portal Support** – Connect to multiple portals and gateways
|
||||
- **Direct Gateway Connection** – Bypass portal selection when needed
|
||||
- **Auto-Connect** – Automatically connect on system startup
|
||||
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME)
|
||||
|
||||
## Usage
|
||||
|
||||
### Command-Line Interface
|
||||
|
||||
The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
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
|
||||
|
||||
```bash
|
||||
# Connect to a portal server
|
||||
sudo gpclient connect <portal>
|
||||
Usage: gpclient [OPTIONS] <COMMAND>
|
||||
|
||||
# Connect using browser authentication (SSO / SAML)
|
||||
sudo gpclient connect <portal> --browser
|
||||
Commands:
|
||||
connect Connect to a portal server
|
||||
disconnect Disconnect from the server
|
||||
launch-gui Launch the GUI
|
||||
hip Generate HIP report
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
# Connect directly to a gateway server
|
||||
sudo gpclient connect <gateway> --as-gateway
|
||||
|
||||
# Connect with automatic HIP report generation
|
||||
sudo gpclient connect <portal> --hip
|
||||
|
||||
# Headless / remote server authentication (prints auth URL to open in any browser)
|
||||
sudo gpclient connect <portal> --browser manual
|
||||
|
||||
# Disconnect
|
||||
sudo gpclient disconnect
|
||||
Options:
|
||||
--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
|
||||
-h, --help Print help (see more with '--help')
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
Run `gpclient --help` or `gpclient <command> --help` to view all available commands and options.
|
||||
|
||||
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
|
||||
|
||||
#### HIP reports
|
||||
|
||||
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --hip
|
||||
```
|
||||
|
||||
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
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
For standalone CLI installations, use `--browser manual` (`--browser remote` before v3.0.6): open the printed URL and paste the resulting `globalprotectcallback:…` data into the terminal.
|
||||
|
||||
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 automatically select an available browser
|
||||
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
|
||||
- Use `--browser manual` for standalone CLI installations or headless servers
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
- **macOS**: Open **GP Connect** from Applications.
|
||||
- **Linux / BSD**: Launch GP Connect from your application menu or run:
|
||||
```bash
|
||||
gpclient launch-gui
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **On Linux, try Native Shell for lower memory usage.** Switch between Native Shell and Tauri in **Settings → General → Interface**.
|
||||
> **On Linux, try Native Shell for lower memory usage.** Switch to it in **Settings → General → Interface**.
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> The GUI version is partially open source. The background service ([gpservice](./apps/gpservice/)) is open source, while the GUI wrapper is proprietary.
|
||||
|
||||
## Installation
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
|
||||
|
||||
### macOS
|
||||
|
||||
Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
|
||||
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: Homebrew (Recommended)
|
||||
#### Option 1: Install with Homebrew
|
||||
|
||||
```bash
|
||||
brew install --cask yuezk/gp-connect/gp-connect
|
||||
```
|
||||
|
||||
#### Option 2: DMG Installer
|
||||
Open GP Connect from Applications, or connect from the terminal:
|
||||
|
||||
Download the `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page and drag GP Connect into Applications.
|
||||
```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: PPA (Recommended)
|
||||
#### Option 1: Install from PPA (Recommended)
|
||||
|
||||
```bash
|
||||
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
|
||||
@@ -114,152 +170,392 @@ sudo apt-get update
|
||||
sudo apt-get install globalprotect-openconnect
|
||||
```
|
||||
|
||||
#### Option 2: DEB Package
|
||||
> [!Note]
|
||||
>
|
||||
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually:
|
||||
> ```bash
|
||||
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
|
||||
> ```
|
||||
|
||||
Download the latest `.deb` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
#### Option 2: Install from DEB Package
|
||||
|
||||
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo apt install ./globalprotect-openconnect_*.deb
|
||||
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb
|
||||
```
|
||||
|
||||
### Arch Linux / Manjaro
|
||||
|
||||
```bash
|
||||
# Official Extra repository
|
||||
sudo pacman -S globalprotect-openconnect
|
||||
#### Option 1: Install from AUR
|
||||
|
||||
# AUR (git main)
|
||||
Package: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
|
||||
|
||||
You can install it using an AUR helper like [`yay`](https://github.com/Jguer/yay):
|
||||
|
||||
```bash
|
||||
yay -S globalprotect-openconnect-git
|
||||
```
|
||||
|
||||
### Fedora / RHEL
|
||||
#### Option 2: Install from the Official Extra Repository
|
||||
|
||||
Enable the COPR repository:
|
||||
The package is also available in the official Arch Linux Extra repository.
|
||||
|
||||
Package: [globalprotect-openconnect](https://archlinux.org/packages/extra/x86_64/globalprotect-openconnect/)
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> Since the official package does not include the system tray support dependency, you need to install `libappindicator` manually:
|
||||
|
||||
```bash
|
||||
sudo pacman -S libappindicator globalprotect-openconnect
|
||||
```
|
||||
|
||||
#### Option 3: Install from Package
|
||||
|
||||
Download the latest package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
|
||||
```
|
||||
|
||||
### Fedora 38+ / Rawhide
|
||||
|
||||
#### Install from COPR
|
||||
|
||||
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for RPM-based distributions:
|
||||
|
||||
```bash
|
||||
sudo dnf copr enable yuezk/globalprotect-openconnect
|
||||
sudo dnf install globalprotect-openconnect
|
||||
```
|
||||
|
||||
### openSUSE
|
||||
### openSUSE Leap 15.6+ / Tumbleweed
|
||||
|
||||
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [OBS instructions](https://software.opensuse.org/download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
||||
#### Install from OBS (openSUSE Build Service)
|
||||
|
||||
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [installation instructions](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
||||
|
||||
### Other RPM-based Distributions
|
||||
|
||||
#### Install from RPM Package
|
||||
|
||||
Download the latest RPM package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
```bash
|
||||
sudo rpm -i globalprotect-openconnect-*.rpm
|
||||
```
|
||||
|
||||
### Alpine Linux
|
||||
|
||||
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
|
||||
```
|
||||
|
||||
*(Requires `community` repository enabled for WebKitGTK and AppIndicator dependencies).*
|
||||
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
|
||||
```
|
||||
|
||||
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
|
||||
### OpenBSD
|
||||
|
||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
|
||||
```
|
||||
|
||||
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
|
||||
### Gentoo
|
||||
|
||||
Available via the `guru` repository:
|
||||
Available via the `guru` and `lamdness` overlays:
|
||||
|
||||
```bash
|
||||
sudo eselect repository enable guru
|
||||
sudo emerge --sync guru
|
||||
sudo emerge --ask net-vpn/GlobalProtect-openconnect
|
||||
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
|
||||
```
|
||||
|
||||
### NixOS
|
||||
|
||||
Add the flake to your `flake.nix`:
|
||||
This repository includes a flake for NixOS integration.
|
||||
|
||||
#### Installation Steps
|
||||
|
||||
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
|
||||
{
|
||||
inputs.globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
||||
inputs = {
|
||||
# ... other inputs
|
||||
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, globalprotect-openconnect, ... }: {
|
||||
nixosConfigurations.<hostname> = nixpkgs.lib.nixosSystem {
|
||||
modules = [
|
||||
globalprotect-openconnect.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
}
|
||||
];
|
||||
outputs = { self, nixpkgs, globalprotect-openconnect, ... }:
|
||||
let
|
||||
system = "x86_64-linux"; # or "aarch64-linux" for ARM64
|
||||
hostname = "<your-host>";
|
||||
in {
|
||||
nixosConfigurations.${hostname} = nixpkgs.lib.nixosSystem {
|
||||
inherit system;
|
||||
|
||||
modules = [
|
||||
./configuration.nix
|
||||
globalprotect-openconnect.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
|
||||
environment.systemPackages = [
|
||||
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Apply changes:
|
||||
Apply:
|
||||
|
||||
```bash
|
||||
sudo nixos-rebuild switch
|
||||
loginctl terminate-user "$USER"
|
||||
```
|
||||
|
||||
### Docker
|
||||
After logging back in to GNOME, enable AppIndicator support if needed:
|
||||
|
||||
Run the CLI client in an official Alpine container:
|
||||
```bash
|
||||
gnome-extensions enable [email protected]
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Source builds also support downloading either desktop interface on NixOS. The
|
||||
downloader packages the verified Tauri or Native Shell archive with Nix, including
|
||||
its runtime libraries. Each installed interface has a garbage-collection root
|
||||
under `/var/lib/gpclient/nix-gui`, so its dependencies remain available after
|
||||
system upgrades. No Rust compilation or NixOS rebuild is needed for GUI downloads.
|
||||
Prebuilt packages gain this support when their release includes the updated
|
||||
service; adding the flake installer alone does not change older service binaries.
|
||||
|
||||
### Official Docker Image
|
||||
|
||||
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
||||
|
||||
```bash
|
||||
docker pull yuezk/globalprotect-openconnect:<version>
|
||||
```
|
||||
|
||||
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
|
||||
|
||||
Run it with access to the TUN device:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:latest \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal>
|
||||
```
|
||||
|
||||
For browser authentication in a headless environment, use manual browser authentication:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
*(Add `--network host` on Linux if VPN routes should apply to the host network).*
|
||||
On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine:
|
||||
|
||||
```bash
|
||||
gpclient connect <portal> --browser manual --browser-listen 192.168.107.15
|
||||
```
|
||||
|
||||
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
|
||||
|
||||
### Other Distributions
|
||||
|
||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
#### Manual Installation
|
||||
|
||||
```bash
|
||||
tar -xJf globalprotect-openconnect_*.bin.tar.xz
|
||||
cd globalprotect-openconnect_*
|
||||
sudo make install
|
||||
```
|
||||
1. **Install dependencies:**
|
||||
- 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:**
|
||||
```bash
|
||||
sudo make install
|
||||
```
|
||||
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites (Linux)
|
||||
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).
|
||||
|
||||
- [Rust](https://www.rust-lang.org/tools/install) 1.91 or later
|
||||
- Build tools: `make`, `pkg-config`, `autoconf`, `automake`, `libtool`, `gettext`
|
||||
- Libraries: `gmp`, `gnutls`, `nettle`, `libxml2`, `zlib`, `lz4`, `p11-kit`, `libsecret`, and `webkit2gtk-4.1` (or GTK 4 for Native Shell)
|
||||
- Polkit (`pkexec`) for privileged tunnel setup
|
||||
### Method 1: Using DevContainer
|
||||
|
||||
*(For FreeBSD and OpenBSD instructions, see [Building from Source on FreeBSD and OpenBSD](docs/bsd-source-build.md)).*
|
||||
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.
|
||||
|
||||
### Build Steps
|
||||
#### Prerequisites
|
||||
|
||||
- [Docker](https://docs.docker.com/get-docker/)
|
||||
- [Visual Studio Code](https://code.visualstudio.com/) (optional, for IDE support)
|
||||
- [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (if using VS Code)
|
||||
|
||||
#### Build Steps
|
||||
|
||||
1. **Clone the repository:**
|
||||
```bash
|
||||
git clone https://github.com/yuezk/GlobalProtect-openconnect.git
|
||||
cd GlobalProtect-openconnect
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
2. **Build the DevContainer image:**
|
||||
```bash
|
||||
docker build -t gpoc-devcontainer .devcontainer/
|
||||
```
|
||||
|
||||
3. **Build the project:**
|
||||
|
||||
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 \
|
||||
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
|
||||
```
|
||||
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
|
||||
|
||||
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
|
||||
|
||||
1. Open the project in VS Code
|
||||
2. When prompted, click "Reopen in Container" (or run **Dev Containers: Reopen in Container**)
|
||||
3. Once the container is ready, open a terminal and run:
|
||||
```bash
|
||||
make build
|
||||
```
|
||||
|
||||
### Method 2: Local Development Build
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
- [Rust 1.91 or later](https://www.rust-lang.org/tools/install)
|
||||
- [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)
|
||||
- Node.js and pnpm if rebuilding the GUI helper frontend
|
||||
|
||||
#### Build Steps
|
||||
|
||||
1. **Download source code:**
|
||||
|
||||
Download `globalprotect-openconnect-${version}.tar.gz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
|
||||
|
||||
2. **Extract and build:**
|
||||
```bash
|
||||
tar -xzf globalprotect-openconnect-${version}.tar.gz
|
||||
cd globalprotect-openconnect-${version}
|
||||
make build
|
||||
```
|
||||
|
||||
3. **Install:**
|
||||
```bash
|
||||
sudo make install
|
||||
```
|
||||
|
||||
To stage the files for packaging instead of installing them into the system, use `make install DESTDIR=/absolute/path/to/staging`.
|
||||
|
||||
### Testing Your Build
|
||||
|
||||
Verify the CLI client is working correctly:
|
||||
|
||||
```bash
|
||||
git clone --recursive https://github.com/yuezk/GlobalProtect-openconnect.git
|
||||
cd GlobalProtect-openconnect
|
||||
make build
|
||||
sudo make install
|
||||
./target/release/gpclient --help
|
||||
```
|
||||
|
||||
**Build Options:**
|
||||
### Build Options
|
||||
|
||||
- `INCLUDE_GUI=1` – Download and install the matching desktop application bundle.
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication (uses external browser or manual mode).
|
||||
- `BUILD_GUI_HELPER=0` – Skip building the helper UI.
|
||||
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external browser or manual authentication
|
||||
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
|
||||
- `OFFLINE=1` – Build in offline mode using vendored dependencies
|
||||
|
||||
## Troubleshooting
|
||||
## Frequently Asked Questions
|
||||
|
||||
- **Headless / Remote Login**: When running without a desktop display or over SSH, use `--browser manual`. Open the printed URL in any browser and paste the callback URL back into the terminal.
|
||||
- **Diagnostics**: If you encounter issues, run `gpclient diagnostics` or follow the [diagnostics guide](docs/diagnostics.md) when opening an issue.
|
||||
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?
|
||||
|
||||
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.
|
||||
|
||||
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?
|
||||
|
||||
Run the client from a terminal in your normal desktop session and use an external browser:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
On a headless server, use `--browser manual` and complete authentication from another machine.
|
||||
|
||||
## NetworkManager Integration
|
||||
|
||||
@@ -268,10 +564,14 @@ sudo make install
|
||||
|
||||
## Licensing
|
||||
|
||||
- **CLI (`gpclient`)**: Free and open source (GPL-3.0).
|
||||
- **GUI (GP Connect)**: Commercial desktop application with a free trial.
|
||||
### Trial and Pricing
|
||||
|
||||
### Open Source Components
|
||||
The **CLI version** is completely free and open source.
|
||||
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
|
||||
|
||||
This project consists of multiple components, each with its own license:
|
||||
|
||||
| Component | Type | License |
|
||||
|-----------|------|---------|
|
||||
|
||||
@@ -16,9 +16,6 @@ fn main() {
|
||||
resolve_commit(&repo_root, &source_commit)
|
||||
);
|
||||
|
||||
#[cfg(all(windows, feature = "webview-auth"))]
|
||||
println!("cargo:rerun-if-changed=icons/windows/icon.ico");
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 47 KiB |
@@ -1,8 +1,8 @@
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use auth::forward_auth_callback;
|
||||
use auth::{BrowserAuthenticator, auth_prelogin};
|
||||
use clap::Parser;
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use clap::Subcommand;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
@@ -49,7 +49,7 @@ See 'gpauth -h' for more information.
|
||||
"
|
||||
)]
|
||||
struct Cli {
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[command(subcommand)]
|
||||
command: Option<CliCommand>,
|
||||
|
||||
@@ -134,7 +134,7 @@ struct Cli {
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[derive(Subcommand)]
|
||||
enum CliCommand {
|
||||
#[command(hide = true)]
|
||||
@@ -272,7 +272,7 @@ fn init_logger(cli: &Cli) {
|
||||
pub async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
|
||||
if let Err(err) = forward_auth_callback(callback).await {
|
||||
eprintln!("Failed to forward authentication callback: {err}");
|
||||
@@ -382,7 +382,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn callback_arguments_parse_separately() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpauth",
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"bundle": {
|
||||
"icon": ["icons/windows/icon.ico"]
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
#![cfg(windows)]
|
||||
|
||||
use auth::AuthCallbackReceiver;
|
||||
use std::{process::Stdio, time::Duration};
|
||||
|
||||
#[tokio::test]
|
||||
async fn callback_command_forwards_between_processes() {
|
||||
let receiver = AuthCallbackReceiver::bind().unwrap();
|
||||
let child = tokio::process::Command::new(env!("CARGO_BIN_EXE_gpauth"))
|
||||
.args([
|
||||
"auth-callback",
|
||||
"globalprotectcallback:cas-as=1&un=windows-fixture&token=callback-command-test",
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let (data, output) = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
tokio::join!(receiver.receive(), child.wait_with_output())
|
||||
})
|
||||
.await
|
||||
.expect("callback executable did not complete");
|
||||
let output = output.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
let data = data.unwrap();
|
||||
assert_eq!(data.username(), "windows-fixture");
|
||||
assert_eq!(data.token(), Some("callback-command-test"));
|
||||
}
|
||||
@@ -511,62 +511,3 @@ printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_and_malformed_identities_fail_before_password_prompt_or_network_connection() {
|
||||
use gpapi::utils::request::RequestIdentityError;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let malformed = directory.path().join("invalid.p12");
|
||||
std::fs::write(&malformed, b"not a certificate archive").unwrap();
|
||||
let fixtures =
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/gpapi/tests/files/client-identity");
|
||||
|
||||
for (certificate, key, expected) in [
|
||||
(
|
||||
fixtures.join("rsa-pss-cert.pem"),
|
||||
Some(fixtures.join("rsa-pss.pem")),
|
||||
"algorithm",
|
||||
),
|
||||
(fixtures.join("legacy-RC2-128.p12"), None, "encryption"),
|
||||
(malformed, None, "malformed"),
|
||||
] {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let server = format!("https://{}", listener.local_addr().unwrap());
|
||||
let mut argv = vec![
|
||||
"test".to_owned(),
|
||||
server,
|
||||
"--as-gateway".to_owned(),
|
||||
"--certificate".to_owned(),
|
||||
certificate.to_string_lossy().into_owned(),
|
||||
];
|
||||
if let Some(key) = key {
|
||||
argv.extend(["--sslkey".to_owned(), key.to_string_lossy().into_owned()]);
|
||||
}
|
||||
let args = TestArgs::parse_from(argv).connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: false,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
let error = tokio::time::timeout(Duration::from_secs(2), handler.handle_attempt())
|
||||
.await
|
||||
.expect("identity failure must not wait for a password or server")
|
||||
.unwrap_err();
|
||||
match (expected, error.downcast_ref::<RequestIdentityError>()) {
|
||||
("algorithm", Some(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"))) => {}
|
||||
("encryption", Some(RequestIdentityError::UnsupportedEncryption)) => {}
|
||||
("malformed", Some(RequestIdentityError::InvalidPkcs12(_) | RequestIdentityError::InvalidCertificate)) => {}
|
||||
_ => panic!("{expected}: unexpected failure {error:#}"),
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(20), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"{expected}: local identity failure must precede network access"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -785,8 +785,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn explicit_hip_user_resolves_to_the_selected_account() {
|
||||
// Build sandboxes may use a UID without an entry in the user database.
|
||||
assert_eq!(get_uid(&Some("root".to_string())).unwrap(), Some(0));
|
||||
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(), Some(current.uid()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -186,8 +186,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
match identity_error {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
| RequestIdentityError::UnsupportedKeyFormat
|
||||
| RequestIdentityError::UnsupportedKeyAlgorithm(_)
|
||||
| RequestIdentityError::KeyMismatch
|
||||
| RequestIdentityError::InvalidKey
|
||||
| RequestIdentityError::InvalidCertificate
|
||||
| RequestIdentityError::IncompletePkcs12
|
||||
@@ -208,12 +206,8 @@ impl<'a> ConnectHandler<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||
let message = if *cert_type == "PKCS#12" {
|
||||
"Enter the certificate file password:"
|
||||
} else {
|
||||
"Enter the private key password:"
|
||||
};
|
||||
let password = Password::new(message)
|
||||
let message = format!("Enter the {} passphrase:", cert_type);
|
||||
let password = Password::new(&message)
|
||||
.without_confirmation()
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
.prompt()?;
|
||||
|
||||
@@ -30,24 +30,14 @@ uuid = { workspace = true, features = ["v4"] }
|
||||
zeroize.workspace = true
|
||||
tempfile.workspace = true
|
||||
getrandom = "0.4"
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
mac_address = "1.2.1"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
|
||||
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
file-rotate = "0.8.0"
|
||||
windows-service = "0.8.1"
|
||||
windows-sys = { version = "0.61", features = ["Win32_System_Pipes"] }
|
||||
@@ -6,7 +6,7 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use clap::Parser;
|
||||
use common::paths::service_lock_file;
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use gpapi::clap::InfoLevelVerbosity;
|
||||
use gpapi::logger;
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -25,7 +25,14 @@ use crate::{
|
||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
||||
};
|
||||
|
||||
use crate::VERSION;
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (",
|
||||
env!("GPSERVICE_GIT_COMMIT"),
|
||||
" ",
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
struct RedactingMacosLogger {
|
||||
@@ -264,7 +271,7 @@ impl Cli {
|
||||
return Ok(dev_service_lock_file_path(socket));
|
||||
}
|
||||
|
||||
Ok(service_lock_file())
|
||||
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
|
||||
}
|
||||
|
||||
fn init_logger(&self) -> Arc<Redaction> {
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
use clap::Parser;
|
||||
use gpapi::clap::InfoLevelVerbosity;
|
||||
#[derive(Parser)]
|
||||
#[command(version = crate::VERSION)]
|
||||
struct Cli {
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
pub fn run() -> anyhow::Result<()> {
|
||||
let cli = Cli::parse();
|
||||
crate::windows_service::dispatch(cli.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info))
|
||||
}
|
||||
@@ -75,7 +75,7 @@ impl DesktopClient {
|
||||
loop {
|
||||
match self.read_control().await? {
|
||||
Some(DESKTOP_GUI_INSTALLER) => {
|
||||
self.write_all(&[u8::from(crate::gui_installation::installer().is_some())]).await?;
|
||||
self.write_all(&[u8::from(crate::request_dispatcher::gui_installer().is_some())]).await?;
|
||||
}
|
||||
Some(DESKTOP_SWITCH_BEGIN) => {
|
||||
ensure!(pending.is_none(), "A GUI switch is already pending");
|
||||
@@ -299,7 +299,10 @@ mod tests {
|
||||
let mut reader = reader;
|
||||
let mut capability = [0];
|
||||
reader.read_exact(&mut capability).unwrap();
|
||||
assert_eq!(capability[0], u8::from(crate::gui_installation::installer().is_some()));
|
||||
assert_eq!(
|
||||
capability[0],
|
||||
u8::from(crate::request_dispatcher::gui_installer().is_some())
|
||||
);
|
||||
reader
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -366,7 +366,7 @@ mod tests {
|
||||
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
|
||||
);
|
||||
|
||||
for source in [0, u8::MAX] {
|
||||
for source in [0, 4] {
|
||||
let json = serde_json::json!({
|
||||
"version": 1,
|
||||
"anchor": {
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
use gpapi::utils::checksum::verify_checksum;
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions, Permissions},
|
||||
io::{BufReader, Read, Write},
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
use tar::Archive;
|
||||
use tempfile::NamedTempFile;
|
||||
use xz2::read::XzDecoder;
|
||||
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;
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum InstallError {
|
||||
Checksum(anyhow::Error),
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
pub(crate) fn installer() -> Option<std::path::PathBuf> {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|executable| {
|
||||
executable
|
||||
.parent()?
|
||||
.parent()
|
||||
.map(|prefix| prefix.join("libexec/gpclient/gp-gui-installer"))
|
||||
})
|
||||
.filter(|path| path.is_file())
|
||||
}
|
||||
|
||||
pub(crate) fn install(src: &Path, checksum: &str, target: &Path) -> Result<(), InstallError> {
|
||||
let installer = installer();
|
||||
install_gui_with_installer(src, checksum, target, installer.as_deref())
|
||||
}
|
||||
|
||||
fn install_gui_with_installer(
|
||||
src: &Path,
|
||||
checksum: &str,
|
||||
target: &Path,
|
||||
installer: Option<&Path>,
|
||||
) -> Result<(), InstallError> {
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"Failed to get parent directory of GUI binary"
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(dir).map_err(|err| InstallError::Install(err.into()))?;
|
||||
|
||||
let staged_archive = stage_gui_archive(src, dir)?;
|
||||
let archive_path = staged_archive.path().to_string_lossy();
|
||||
verify_checksum(&archive_path, checksum).map_err(InstallError::Checksum)?;
|
||||
|
||||
// A package may need to prepare downloaded executables for its runtime.
|
||||
// Resolve this helper beside the running service, never from the request or PATH.
|
||||
if let Some(installer) = installer {
|
||||
let status = std::process::Command::new(installer)
|
||||
.arg(staged_archive.path())
|
||||
.arg(checksum)
|
||||
.arg(target)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.status()
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
return if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI package installation failed: {status}"
|
||||
)))
|
||||
};
|
||||
}
|
||||
|
||||
let tar = XzDecoder::new(BufReader::new(
|
||||
staged_archive
|
||||
.reopen()
|
||||
.map_err(|err| InstallError::Install(err.into()))?,
|
||||
))
|
||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
||||
let mut archive = Archive::new(tar);
|
||||
let binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
|
||||
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
|
||||
file
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(0o755))
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
file
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
file.persist(&target).map_err(|err| InstallError::Install(err.into()))?;
|
||||
File::open(dir)
|
||||
.and_then(|directory| directory.sync_all())
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, InstallError> {
|
||||
let mut source = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
|
||||
.open(src)
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
let metadata = source.metadata().map_err(|err| InstallError::Install(err.into()))?;
|
||||
let source_size = metadata.len();
|
||||
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut staged = NamedTempFile::new_in(dir).map_err(|err| InstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
if copied != source_size {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive changed while it was being read"
|
||||
)));
|
||||
}
|
||||
staged.flush().map_err(|err| InstallError::Install(err.into()))?;
|
||||
staged
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| InstallError::Install(err.into()))?;
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn extract_gui_binary<R: Read>(
|
||||
archive: &mut Archive<R>,
|
||||
dir: &Path,
|
||||
binary_name: &str,
|
||||
) -> Result<NamedTempFile, InstallError> {
|
||||
for entry in archive.entries().map_err(|err| InstallError::Install(err.into()))? {
|
||||
let mut entry = entry.map_err(|err| InstallError::Install(err.into()))?;
|
||||
let is_gui = entry
|
||||
.path()
|
||||
.map_err(|err| InstallError::Install(err.into()))?
|
||||
.file_name()
|
||||
.is_some_and(|name| name == binary_name);
|
||||
if is_gui && entry.header().entry_type().is_file() {
|
||||
let declared_size = entry.size();
|
||||
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
let mut file = NamedTempFile::new_in(dir).map_err(|err| InstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| InstallError::Install(err.into()))?;
|
||||
if copied != declared_size {
|
||||
return Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary size does not match its archive header"
|
||||
)));
|
||||
}
|
||||
file.flush().map_err(|err| InstallError::Install(err.into()))?;
|
||||
return Ok(file);
|
||||
}
|
||||
}
|
||||
Err(InstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive does not contain a non-empty regular {binary_name} file"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
use tar::{Builder, EntryType, Header};
|
||||
use xz2::write::XzEncoder;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
{
|
||||
let mut builder = Builder::new(&mut data);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(entry_type);
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
builder.append_data(&mut header, "gpgui", contents).unwrap();
|
||||
builder.finish().unwrap();
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn compressed_gui_archive(contents: &[u8]) -> NamedTempFile {
|
||||
let tar = archive_with_entry(EntryType::Regular, contents);
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 6);
|
||||
encoder.write_all(&tar).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&compressed).unwrap();
|
||||
archive.flush().unwrap();
|
||||
archive
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_file_and_empty_gui_entries() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
|
||||
let data = archive_with_entry(entry_type, contents);
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_non_empty_regular_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let data = archive_with_entry(EntryType::Regular, b"gui binary");
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
let extracted = extract_gui_binary(&mut archive, output.path(), "gpgui").unwrap();
|
||||
let contents = std::fs::read(extracted.path()).unwrap();
|
||||
assert_eq!(contents, b"gui binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_archive_sources() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
assert!(stage_gui_archive(output.path(), output.path()).is_err());
|
||||
|
||||
let oversized = output.path().join("oversized.tar.xz");
|
||||
File::create(&oversized)
|
||||
.unwrap()
|
||||
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
|
||||
.unwrap();
|
||||
assert!(stage_gui_archive(&oversized, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(EntryType::Regular);
|
||||
header.set_size(MAX_GUI_BINARY_SIZE + 1);
|
||||
header.set_mode(0o755);
|
||||
header.set_path("gpgui").unwrap();
|
||||
header.set_cksum();
|
||||
let mut data = header.as_bytes().to_vec();
|
||||
data.resize(512 * 3, 0);
|
||||
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
install(archive.path(), &checksum, &target).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"gui binary");
|
||||
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_nsh_beside_tauri_without_replacing_it() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let tauri = output.path().join("gpgui");
|
||||
std::fs::write(&tauri, b"tauri").unwrap();
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 1);
|
||||
{
|
||||
let mut archive = Builder::new(&mut encoder);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_size(3);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
archive
|
||||
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
|
||||
.unwrap();
|
||||
archive.finish().unwrap();
|
||||
}
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&encoder.finish().unwrap()).unwrap();
|
||||
archive.flush().unwrap();
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let nsh = output.path().join("gpgui-nsh");
|
||||
install(archive.path(), &checksum, &nsh).unwrap();
|
||||
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
|
||||
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
|
||||
assert!(install(archive.path(), "invalid", &target).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installer_receives_a_verified_staged_archive() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui-nsh");
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(
|
||||
&installer,
|
||||
"#!/bin/sh\nset -eu\ntest -f \"$1\"\nprintf '%s' \"$2\" > \"$3\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), "invalid", &target, Some(&installer)).is_err());
|
||||
assert!(!target.exists());
|
||||
install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), checksum);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installation_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui");
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(&installer, "#!/bin/sh\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
|
||||
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
|
||||
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
|
||||
let archive = compressed_gui_archive(&binary);
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| temporary.path().to_owned());
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let target = output.join("gpclient/gpgui");
|
||||
for upgrade in [false, true] {
|
||||
if upgrade {
|
||||
std::fs::write(&target, b"old GUI").unwrap();
|
||||
}
|
||||
install(archive.path(), &checksum, &target).unwrap();
|
||||
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read(&target).unwrap(), binary);
|
||||
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
|
||||
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
|
||||
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{io, sync::Arc};
|
||||
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
@@ -6,17 +6,7 @@ use gpapi::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput};
|
||||
use openconnect::HipRequest;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use openconnect::HipScript;
|
||||
#[cfg(unix)]
|
||||
#[path = "hip_source/unix.rs"]
|
||||
mod scripts;
|
||||
#[cfg(windows)]
|
||||
#[path = "hip_source/windows.rs"]
|
||||
mod scripts;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use scripts::script_environment;
|
||||
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
|
||||
|
||||
pub(crate) struct HipExecution {
|
||||
pub source: openconnect::HipSource,
|
||||
@@ -46,7 +36,7 @@ impl HipApproval {
|
||||
pub(crate) fn resolve(
|
||||
source: &HipSource,
|
||||
desktop_uid: Option<u32>,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
edited_report: Option<Arc<str>>,
|
||||
profile: Option<OsProfile>,
|
||||
) -> anyhow::Result<HipExecution> {
|
||||
@@ -73,11 +63,22 @@ pub(crate) fn resolve(
|
||||
}
|
||||
HipSource::UserScript { path } => {
|
||||
approval = None;
|
||||
ensure_custom_available(restricted_desktop)?;
|
||||
scripts::user_script(path, desktop_uid)?
|
||||
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"
|
||||
);
|
||||
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 } => {
|
||||
ensure_custom_available(restricted_desktop)?;
|
||||
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")?;
|
||||
@@ -112,10 +113,10 @@ pub(crate) fn resolve(
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_custom_available(restricted_desktop: bool) -> anyhow::Result<()> {
|
||||
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!cfg!(target_os = "macos") && !restricted_desktop,
|
||||
"Custom HIP scripts are unavailable on this platform"
|
||||
!cfg!(target_os = "macos") && !brokered_macos,
|
||||
"Custom HIP scripts are unavailable on macOS"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -148,6 +149,27 @@ pub(crate) fn generate(
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn profile(
|
||||
identity: &HostIdentity,
|
||||
os: ClientOs,
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
use anyhow::{Context, ensure};
|
||||
use openconnect::{HipScript, HipScriptEnvironment};
|
||||
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
|
||||
pub(super) fn user_script(path: &str, desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
|
||||
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"
|
||||
);
|
||||
let script =
|
||||
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
|
||||
Ok(openconnect::HipSource::Script(script))
|
||||
}
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
pub(super) fn user_script(_path: &str, _desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
|
||||
anyhow::bail!("Custom HIP scripts are unavailable on Windows")
|
||||
}
|
||||
@@ -1,15 +1,11 @@
|
||||
#[cfg_attr(windows, path = "cli/windows.rs")]
|
||||
mod cli;
|
||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||
mod credential_lease;
|
||||
#[cfg(unix)]
|
||||
mod desktop_client;
|
||||
#[cfg(all(debug_assertions, unix))]
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev_bootstrap;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||
mod device_anchor;
|
||||
#[cfg(unix)]
|
||||
mod gui_installation;
|
||||
mod handlers;
|
||||
mod hip_preview;
|
||||
mod hip_source;
|
||||
@@ -17,7 +13,6 @@ mod hip_source;
|
||||
mod macos_broker;
|
||||
mod request_dispatcher;
|
||||
mod routes;
|
||||
#[cfg(unix)]
|
||||
mod runtime_user;
|
||||
mod session_registry;
|
||||
mod vpn_script;
|
||||
@@ -25,31 +20,7 @@ mod vpn_task;
|
||||
mod ws_connection;
|
||||
mod ws_server;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_service;
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (",
|
||||
env!("GPSERVICE_GIT_COMMIT"),
|
||||
" ",
|
||||
compile_time::date_str!(),
|
||||
")"
|
||||
);
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
cli::run().await;
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn main() -> std::process::ExitCode {
|
||||
match cli::run() {
|
||||
Ok(()) => std::process::ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("{error:#}");
|
||||
std::process::ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,27 @@
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions, Permissions},
|
||||
io::{BufReader, Read, Write},
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
utils::redact::Redaction,
|
||||
utils::{checksum::verify_checksum, redact::Redaction},
|
||||
};
|
||||
use log::{info, warn};
|
||||
#[cfg(unix)]
|
||||
use tar::Archive;
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::sync::Mutex;
|
||||
use xz2::read::XzDecoder;
|
||||
|
||||
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>,
|
||||
@@ -63,10 +75,9 @@ pub struct RequestDispatcher {
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
#[cfg(unix)]
|
||||
install_lock: Mutex<()>,
|
||||
gui_management_enabled: bool,
|
||||
restricted_desktop: bool,
|
||||
externally_brokered: bool,
|
||||
}
|
||||
|
||||
impl RequestDispatcher {
|
||||
@@ -78,16 +89,15 @@ impl RequestDispatcher {
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
gui_management_enabled: bool,
|
||||
restricted_desktop: bool,
|
||||
externally_brokered: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle,
|
||||
gui_restart_requested,
|
||||
redaction,
|
||||
#[cfg(unix)]
|
||||
install_lock: Mutex::new(()),
|
||||
gui_management_enabled,
|
||||
restricted_desktop,
|
||||
externally_brokered,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +202,7 @@ impl RequestDispatcher {
|
||||
edited_report,
|
||||
} => {
|
||||
let prepared =
|
||||
crate::vpn_task::prepare_connection(*request, self.restricted_desktop, preparation.cancellation()).await;
|
||||
crate::vpn_task::prepare_connection(*request, self.externally_brokered, preparation.cancellation()).await;
|
||||
return match prepared {
|
||||
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||
Err(error) => {
|
||||
@@ -269,25 +279,24 @@ impl RequestDispatcher {
|
||||
}
|
||||
|
||||
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
if !self.restricted_desktop {
|
||||
if !self.externally_brokered {
|
||||
return Ok(());
|
||||
}
|
||||
if request.args().vpnc_script().is_some() {
|
||||
return Err("Custom VPN scripts are unavailable on this platform");
|
||||
return Err("macOS does not support custom VPN scripts");
|
||||
}
|
||||
if matches!(
|
||||
request.args().hip_source(),
|
||||
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
|
||||
) {
|
||||
return Err("Custom HIP scripts are unavailable on this platform");
|
||||
return Err("macOS does not support custom HIP scripts");
|
||||
}
|
||||
if request.args().certificate().is_some() || request.args().sslkey().is_some() {
|
||||
return Err("Client identity must be provided as certificate data");
|
||||
return Err("macOS client identity must be provided as protected data, not root-readable paths");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
||||
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
|
||||
return ServiceResult::rejected(
|
||||
@@ -299,17 +308,14 @@ impl RequestDispatcher {
|
||||
let path = request.path;
|
||||
let checksum = request.checksum;
|
||||
let target = request.variant.update_target();
|
||||
let installed = tokio::task::spawn_blocking(move || {
|
||||
crate::gui_installation::install(std::path::Path::new(&path), &checksum, &target)
|
||||
})
|
||||
.await;
|
||||
let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await;
|
||||
match installed {
|
||||
Ok(Ok(())) => ServiceResult::Accepted,
|
||||
Ok(Err(crate::gui_installation::InstallError::Checksum(err))) => {
|
||||
Ok(Err(GuiInstallError::Checksum(err))) => {
|
||||
warn!("Failed to verify GUI update checksum: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
|
||||
}
|
||||
Ok(Err(crate::gui_installation::InstallError::Install(err))) => {
|
||||
Ok(Err(GuiInstallError::Install(err))) => {
|
||||
warn!("Failed to install GUI update: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
||||
}
|
||||
@@ -319,20 +325,335 @@ impl RequestDispatcher {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
async fn update_gui(&self, _request: UpdateGuiRequest) -> ServiceResult {
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Use the Windows installer to update GP Connect",
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GuiInstallError {
|
||||
Checksum(anyhow::Error),
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
pub(crate) fn gui_installer() -> Option<std::path::PathBuf> {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|executable| {
|
||||
executable
|
||||
.parent()?
|
||||
.parent()
|
||||
.map(|prefix| prefix.join("libexec/gpclient/gp-gui-installer"))
|
||||
})
|
||||
.filter(|path| path.is_file())
|
||||
}
|
||||
|
||||
fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiInstallError> {
|
||||
let installer = gui_installer();
|
||||
install_gui_with_installer(src, checksum, target, installer.as_deref())
|
||||
}
|
||||
|
||||
fn install_gui_with_installer(
|
||||
src: &Path,
|
||||
checksum: &str,
|
||||
target: &Path,
|
||||
installer: Option<&Path>,
|
||||
) -> Result<(), GuiInstallError> {
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"Failed to get parent directory of GUI binary"
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
|
||||
let staged_archive = stage_gui_archive(src, dir)?;
|
||||
let archive_path = staged_archive.path().to_string_lossy();
|
||||
verify_checksum(&archive_path, checksum).map_err(GuiInstallError::Checksum)?;
|
||||
|
||||
// A package may need to prepare downloaded executables for its runtime.
|
||||
// Resolve this helper beside the running service, never from the request or PATH.
|
||||
if let Some(installer) = installer {
|
||||
let status = std::process::Command::new(installer)
|
||||
.arg(staged_archive.path())
|
||||
.arg(checksum)
|
||||
.arg(target)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.status()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
return if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI package installation failed: {status}"
|
||||
)))
|
||||
};
|
||||
}
|
||||
|
||||
let tar = XzDecoder::new(BufReader::new(
|
||||
staged_archive
|
||||
.reopen()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?,
|
||||
))
|
||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
||||
let mut archive = Archive::new(tar);
|
||||
let binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
|
||||
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
|
||||
file
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(0o755))
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
file
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
file
|
||||
.persist(&target)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
File::open(dir)
|
||||
.and_then(|directory| directory.sync_all())
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
||||
let mut source = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
|
||||
.open(src)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let metadata = source.metadata().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let source_size = metadata.len();
|
||||
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut staged = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
if copied != source_size {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive changed while it was being read"
|
||||
)));
|
||||
}
|
||||
staged.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
staged
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn extract_gui_binary<R: Read>(
|
||||
archive: &mut Archive<R>,
|
||||
dir: &Path,
|
||||
binary_name: &str,
|
||||
) -> Result<NamedTempFile, GuiInstallError> {
|
||||
for entry in archive.entries().map_err(|err| GuiInstallError::Install(err.into()))? {
|
||||
let mut entry = entry.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let is_gui = entry
|
||||
.path()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?
|
||||
.file_name()
|
||||
.is_some_and(|name| name == binary_name);
|
||||
if is_gui && entry.header().entry_type().is_file() {
|
||||
let declared_size = entry.size();
|
||||
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
let mut file = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
if copied != declared_size {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary size does not match its archive header"
|
||||
)));
|
||||
}
|
||||
file.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
return Ok(file);
|
||||
}
|
||||
}
|
||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive does not contain a non-empty regular {binary_name} file"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::vpn_task::test_connect_request as test_request;
|
||||
use gpapi::gateway::Gateway;
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::transport::{ServiceErrorCode, ServiceResult},
|
||||
};
|
||||
use tar::{Builder, EntryType, Header};
|
||||
use xz2::write::XzEncoder;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
{
|
||||
let mut builder = Builder::new(&mut data);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(entry_type);
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
builder.append_data(&mut header, "gpgui", contents).unwrap();
|
||||
builder.finish().unwrap();
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn compressed_gui_archive(contents: &[u8]) -> NamedTempFile {
|
||||
let tar = archive_with_entry(EntryType::Regular, contents);
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 6);
|
||||
encoder.write_all(&tar).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&compressed).unwrap();
|
||||
archive.flush().unwrap();
|
||||
archive
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_file_and_empty_gui_entries() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
|
||||
let data = archive_with_entry(entry_type, contents);
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_non_empty_regular_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let data = archive_with_entry(EntryType::Regular, b"gui binary");
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
let extracted = extract_gui_binary(&mut archive, output.path(), "gpgui").unwrap();
|
||||
let contents = std::fs::read(extracted.path()).unwrap();
|
||||
assert_eq!(contents, b"gui binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_archive_sources() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
assert!(stage_gui_archive(output.path(), output.path()).is_err());
|
||||
|
||||
let oversized = output.path().join("oversized.tar.xz");
|
||||
File::create(&oversized)
|
||||
.unwrap()
|
||||
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
|
||||
.unwrap();
|
||||
assert!(stage_gui_archive(&oversized, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(EntryType::Regular);
|
||||
header.set_size(MAX_GUI_BINARY_SIZE + 1);
|
||||
header.set_mode(0o755);
|
||||
header.set_path("gpgui").unwrap();
|
||||
header.set_cksum();
|
||||
let mut data = header.as_bytes().to_vec();
|
||||
data.resize(512 * 3, 0);
|
||||
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
install_gui_at(archive.path(), &checksum, &target).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"gui binary");
|
||||
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_nsh_beside_tauri_without_replacing_it() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let tauri = output.path().join("gpgui");
|
||||
std::fs::write(&tauri, b"tauri").unwrap();
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 1);
|
||||
{
|
||||
let mut archive = Builder::new(&mut encoder);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_size(3);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
archive
|
||||
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
|
||||
.unwrap();
|
||||
archive.finish().unwrap();
|
||||
}
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&encoder.finish().unwrap()).unwrap();
|
||||
archive.flush().unwrap();
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let nsh = output.path().join("gpgui-nsh");
|
||||
install_gui_at(archive.path(), &checksum, &nsh).unwrap();
|
||||
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
|
||||
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
|
||||
assert!(install_gui_at(archive.path(), "invalid", &target).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installer_receives_a_verified_staged_archive() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui-nsh");
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(
|
||||
&installer,
|
||||
"#!/bin/sh\nset -eu\ntest -f \"$1\"\nprintf '%s' \"$2\" > \"$3\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), "invalid", &target, Some(&installer)).is_err());
|
||||
assert!(!target.exists());
|
||||
install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), checksum);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_installation_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpgui");
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
let installer = output.path().join("installer");
|
||||
std::fs::write(&installer, "#!/bin/sh\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
@@ -379,7 +700,7 @@ mod tests {
|
||||
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("Custom VPN scripts are unavailable on this platform")
|
||||
Err("macOS does not support custom VPN scripts")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -388,7 +709,32 @@ mod tests {
|
||||
});
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_request(&custom),
|
||||
Err("Custom HIP scripts are unavailable on this platform")
|
||||
Err("macOS does not support custom HIP scripts")
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
|
||||
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
|
||||
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
|
||||
let archive = compressed_gui_archive(&binary);
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| temporary.path().to_owned());
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let target = output.join("gpclient/gpgui");
|
||||
for upgrade in [false, true] {
|
||||
if upgrade {
|
||||
std::fs::write(&target, b"old GUI").unwrap();
|
||||
}
|
||||
install_gui_at(archive.path(), &checksum, &target).unwrap();
|
||||
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read(&target).unwrap(), binary);
|
||||
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
|
||||
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
|
||||
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,8 +62,6 @@ enum SessionStatus {
|
||||
}
|
||||
|
||||
struct SessionRecord {
|
||||
#[cfg(windows)]
|
||||
windows_identity: Option<Arc<gpapi::windows::PipeClientIdentity>>,
|
||||
non_tunnel: Option<AttachmentAttempt>,
|
||||
closed_attachment: Option<Uuid>,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
@@ -257,8 +255,6 @@ impl SessionRegistry {
|
||||
sessions.insert(
|
||||
credential.session_id(),
|
||||
SessionRecord {
|
||||
#[cfg(windows)]
|
||||
windows_identity: None,
|
||||
non_tunnel: None,
|
||||
closed_attachment: None,
|
||||
secret: Zeroizing::new(*credential.secret()),
|
||||
@@ -277,38 +273,6 @@ impl SessionRegistry {
|
||||
Ok(credential)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn issue_windows(
|
||||
&self,
|
||||
product_version: &str,
|
||||
identity: Arc<gpapi::windows::PipeClientIdentity>,
|
||||
) -> Result<Arc<SessionCredential>, SessionError> {
|
||||
let credential = self.issue(product_version, None)?;
|
||||
// The credential is not published until its Windows owner is retained.
|
||||
self
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| SessionError::Unavailable)?
|
||||
.get_mut(&credential.session_id())
|
||||
.ok_or(SessionError::Unauthorized)?
|
||||
.windows_identity = Some(identity);
|
||||
Ok(credential)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn windows_identity(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
) -> Result<Arc<gpapi::windows::PipeClientIdentity>, SessionError> {
|
||||
self
|
||||
.sessions
|
||||
.lock()
|
||||
.map_err(|_| SessionError::Unavailable)?
|
||||
.get(&session_id)
|
||||
.and_then(|record| record.windows_identity.clone())
|
||||
.ok_or(SessionError::Unauthorized)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows.rs"]
|
||||
mod platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "macos.rs"]
|
||||
mod platform;
|
||||
@@ -11,8 +8,7 @@ mod platform;
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "macos",
|
||||
windows
|
||||
target_os = "macos"
|
||||
)))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
@@ -20,5 +16,3 @@ mod platform;
|
||||
mod selection;
|
||||
|
||||
pub(crate) use platform::builder;
|
||||
#[cfg(windows)]
|
||||
pub(crate) use platform::recover_network;
|
||||
@@ -1,24 +0,0 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
use std::sync::Mutex;
|
||||
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
|
||||
|
||||
pub(crate) fn recover_network() -> std::io::Result<()> {
|
||||
gpvpnc::windows::recover(RECOVERY_KEY)
|
||||
}
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
anyhow::ensure!(
|
||||
args.vpnc_script().is_none(),
|
||||
"Windows does not support custom VPN scripts"
|
||||
);
|
||||
let network = Mutex::new(gpvpnc::windows::NetworkConfigurator::new(RECOVERY_KEY)?);
|
||||
Ok(
|
||||
Vpn::builder(server, cookie).network_configuration_handler(move |configuration| {
|
||||
network
|
||||
.lock()
|
||||
.map_err(|_| std::io::Error::other("Windows network state is unavailable"))?
|
||||
.configure(&configuration.reason, &configuration.environment)
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -126,7 +126,6 @@ impl LifecycleHandle {
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
|
||||
#[cfg(any(unix, test))]
|
||||
pub async fn disconnect_and_wait(&self) -> bool {
|
||||
let completion = {
|
||||
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||
@@ -448,7 +447,7 @@ pub(crate) struct VpnTask {
|
||||
events: mpsc::Receiver<LifecycleEvent>,
|
||||
lifecycle: LifecycleHandle,
|
||||
vpn_state_tx: watch::Sender<VpnState>,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
active: Option<ActiveAttempt>,
|
||||
cancel_token: CancellationToken,
|
||||
@@ -457,7 +456,7 @@ pub(crate) struct VpnTask {
|
||||
impl VpnTask {
|
||||
pub fn new(
|
||||
vpn_state_tx: watch::Sender<VpnState>,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
) -> (Self, LifecycleHandle) {
|
||||
let (events_tx, events) = mpsc::channel(4);
|
||||
@@ -471,7 +470,7 @@ impl VpnTask {
|
||||
events,
|
||||
lifecycle: lifecycle.clone(),
|
||||
vpn_state_tx,
|
||||
restricted_desktop,
|
||||
brokered_macos,
|
||||
registry,
|
||||
active: None,
|
||||
cancel_token: CancellationToken::new(),
|
||||
@@ -618,7 +617,7 @@ impl VpnTask {
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
session_id,
|
||||
restricted_desktop: self.restricted_desktop,
|
||||
brokered_macos: self.brokered_macos,
|
||||
registry: self.registry.clone(),
|
||||
lifecycle: self.lifecycle.clone(),
|
||||
},
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(super) struct ConnectionResources {
|
||||
/// the complete ledger and its retained identity resources to the service.
|
||||
pub(crate) async fn prepare_connection(
|
||||
request: ConnectRequest,
|
||||
restricted_desktop: bool,
|
||||
brokered_macos: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<PreparedConnection> {
|
||||
let mode = request.args().packet_delivery().clone();
|
||||
@@ -77,16 +77,11 @@ pub(crate) async fn prepare_connection(
|
||||
};
|
||||
check()?;
|
||||
let args = setup_request.args();
|
||||
let identity = super::prepare_identity(args, restricted_desktop || non_tunnel)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
let directory = restricted_desktop.then(|| std::path::PathBuf::from("/var/run/com.yuezk.gpgui"));
|
||||
#[cfg(windows)]
|
||||
let directory = Some(common::paths::service_private_dir());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let directory: Option<std::path::PathBuf> = None;
|
||||
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.as_deref()))
|
||||
.map(|identity| identity.write_files(directory))
|
||||
.transpose()?;
|
||||
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||
let profile = crate::hip_source::profile(
|
||||
@@ -186,8 +181,8 @@ mod tests {
|
||||
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||
|
||||
#[tokio::test]
|
||||
async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() {
|
||||
for (restricted_desktop, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||
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()));
|
||||
@@ -197,7 +192,7 @@ mod tests {
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
}
|
||||
let request = serde_json::from_value(wire).unwrap();
|
||||
let error = prepare_connection(request, restricted_desktop, CancellationToken::new())
|
||||
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(super) struct AttemptInput {
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub session_id: Option<Uuid>,
|
||||
pub restricted_desktop: bool,
|
||||
pub brokered_macos: bool,
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub lifecycle: LifecycleHandle,
|
||||
}
|
||||
@@ -31,7 +31,6 @@ struct TunnelInput {
|
||||
source: Arc<openconnect::HipSource>,
|
||||
session_id: Option<Uuid>,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
#[cfg(unix)]
|
||||
desktop_uid: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -56,7 +55,7 @@ pub(super) fn spawn(
|
||||
let request = input.connection.request.clone();
|
||||
let resources = input.connection.resources.clone();
|
||||
let desktop_uid = input.desktop_uid;
|
||||
let brokered = input.restricted_desktop;
|
||||
let brokered = input.brokered_macos;
|
||||
let edited = input.edited_report.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let execution = tokio::task::spawn_blocking(move || {
|
||||
@@ -106,7 +105,6 @@ pub(super) fn spawn(
|
||||
source,
|
||||
session_id: input.session_id,
|
||||
registry: input.registry.clone(),
|
||||
#[cfg(unix)]
|
||||
desktop_uid: input.desktop_uid,
|
||||
};
|
||||
input.connection.request.release_script_tun_bootstrap();
|
||||
@@ -255,14 +253,12 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
|
||||
),
|
||||
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
|
||||
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
|
||||
#[cfg(unix)]
|
||||
let owner = input.desktop_uid.context("Desktop identity is unavailable")?;
|
||||
#[cfg(windows)]
|
||||
let owner = input
|
||||
.registry
|
||||
.windows_identity(input.session_id.context("Desktop session is unavailable")?)?;
|
||||
let (builder, script_tun) =
|
||||
super::script_tun::builder(member.gateway.server(), member.authentication.cookie(), request, owner)?;
|
||||
let (builder, script_tun) = super::script_tun::builder(
|
||||
member.gateway.server(),
|
||||
member.authentication.cookie(),
|
||||
request,
|
||||
input.desktop_uid.context("Desktop identity is unavailable")?,
|
||||
)?;
|
||||
(builder, Some(script_tun))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,19 +1,40 @@
|
||||
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
|
||||
use super::{LifecycleEvent, LifecycleHandle};
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message};
|
||||
use openconnect::{Vpn, tunnel::Event};
|
||||
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
|
||||
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use tokio::{sync::mpsc, time::Instant};
|
||||
use tokio::{net::UnixStream, sync::mpsc, time::Instant};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "script_tun/unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(windows)]
|
||||
#[path = "script_tun/windows.rs"]
|
||||
mod platform;
|
||||
pub(super) use platform::{PreparedScriptTun, builder};
|
||||
pub(super) struct PreparedScriptTun {
|
||||
pub control: std::os::unix::net::UnixStream,
|
||||
pub bootstrap: Bootstrap,
|
||||
}
|
||||
|
||||
pub(super) fn builder(
|
||||
server: &str,
|
||||
cookie: &str,
|
||||
request: &ScriptTunRequest,
|
||||
uid: u32,
|
||||
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
|
||||
request.validate()?;
|
||||
ensure!(uid != 0, "Script-tun worker requires a desktop user");
|
||||
let (control, child) = std::os::unix::net::UnixStream::pair()?;
|
||||
let builder = Vpn::builder(server, cookie).script_tun_program(
|
||||
request.program.to_str().context("Program is not UTF-8")?,
|
||||
&request.args,
|
||||
uid,
|
||||
child.into(),
|
||||
)?;
|
||||
Ok((
|
||||
builder,
|
||||
PreparedScriptTun {
|
||||
control,
|
||||
bootstrap: request.bootstrap.clone(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct NetworkChanged;
|
||||
@@ -32,7 +53,7 @@ enum Native {
|
||||
pub(super) async fn run(
|
||||
identity: Identity,
|
||||
vpn: Arc<Vpn>,
|
||||
mut prepared: PreparedScriptTun,
|
||||
prepared: PreparedScriptTun,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
lifecycle: &LifecycleHandle,
|
||||
cancellation: CancellationToken,
|
||||
@@ -41,8 +62,6 @@ pub(super) async fn run(
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
sessions: &mut gpapi::session::desktop::GatewaySessions,
|
||||
) -> anyhow::Result<()> {
|
||||
let channel = prepared.connect().await?;
|
||||
let mut control = ConsumerControl::new(channel);
|
||||
let attempt = identity.attempt;
|
||||
let (native_tx, native) = mpsc::channel(64);
|
||||
let observed = native_tx.clone();
|
||||
@@ -58,7 +77,7 @@ pub(super) async fn run(
|
||||
monitor: monitor.clone(),
|
||||
})
|
||||
.await;
|
||||
if event_result.is_err() || cancellation.is_cancelled() {
|
||||
if event_result.is_err() {
|
||||
monitor.stop().await;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -72,50 +91,31 @@ pub(super) async fn run(
|
||||
tokio::pin!(worker);
|
||||
let mut worker_done = false;
|
||||
let stop = cancellation.child_token();
|
||||
let result = {
|
||||
let supervisor = supervise(
|
||||
identity,
|
||||
&mut control,
|
||||
std::mem::take(&mut prepared.bootstrap),
|
||||
native,
|
||||
stop.clone(),
|
||||
events,
|
||||
);
|
||||
tokio::pin!(supervisor);
|
||||
let mut supervisor_done = false;
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut supervisor => { supervisor_done = true; break result; }
|
||||
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
|
||||
_ = approval_poll.tick() => {
|
||||
if !approval.approval_is_valid() || !registry.has_session(session_id) {
|
||||
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
}
|
||||
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
|
||||
tokio::pin!(supervisor);
|
||||
let mut supervisor_done = false;
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut supervisor => { supervisor_done = true; break result; }
|
||||
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
|
||||
_ = approval_poll.tick() => {
|
||||
if !approval.approval_is_valid() || !registry.has_session(session_id) {
|
||||
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
}
|
||||
}
|
||||
};
|
||||
stop.cancel();
|
||||
// Keep the consumer's control and packet endpoints alive until OpenConnect
|
||||
// consumes cancellation and logs out. Early EOF would interrupt that logout.
|
||||
vpn.disconnect();
|
||||
if !worker_done {
|
||||
let _ = worker.await;
|
||||
}
|
||||
if !supervisor_done {
|
||||
let _ = supervisor.await;
|
||||
}
|
||||
result
|
||||
};
|
||||
control.stop().await;
|
||||
let cleanup = prepared.stop_worker();
|
||||
monitor.stop().await;
|
||||
if result.is_ok() {
|
||||
cleanup?;
|
||||
} else if let Err(error) = cleanup {
|
||||
log::warn!("Could not stop packet worker: {error:#}");
|
||||
stop.cancel();
|
||||
if !supervisor_done {
|
||||
let _ = supervisor.await;
|
||||
}
|
||||
vpn.disconnect();
|
||||
if !worker_done {
|
||||
let _ = worker.await;
|
||||
}
|
||||
monitor.stop().await;
|
||||
result
|
||||
}
|
||||
|
||||
@@ -128,113 +128,93 @@ enum WorkerState {
|
||||
Suspending,
|
||||
}
|
||||
|
||||
// Own the channel independently of its supervision future so run() can drain
|
||||
// the native VPN before telling the consumer to stop or closing its endpoints.
|
||||
struct ConsumerControl {
|
||||
output: tokio::io::WriteHalf<platform::ControlStream>,
|
||||
messages: mpsc::Receiver<std::io::Result<Message>>,
|
||||
reader: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl ConsumerControl {
|
||||
fn new(channel: platform::ControlStream) -> Self {
|
||||
let (mut input, output) = tokio::io::split(channel);
|
||||
let (messages_tx, messages) = mpsc::channel(8);
|
||||
let reader = tokio::spawn(async move {
|
||||
loop {
|
||||
let message = receive(&mut input).await;
|
||||
let failed = message.is_err();
|
||||
if messages_tx.send(message).await.is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Self {
|
||||
output,
|
||||
messages,
|
||||
reader,
|
||||
}
|
||||
}
|
||||
async fn stop(&mut self) {
|
||||
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut self.output, &Message::Stop)).await;
|
||||
self.reader.abort();
|
||||
let _ = (&mut self.reader).await;
|
||||
}
|
||||
}
|
||||
impl Drop for ConsumerControl {
|
||||
fn drop(&mut self) {
|
||||
self.reader.abort();
|
||||
}
|
||||
}
|
||||
|
||||
// Production and generic-consumer tests exercise this same state machine.
|
||||
// The same control loop runs against native observations in production and a
|
||||
// generic socket consumer in tests; VPN ownership stays in run().
|
||||
async fn supervise(
|
||||
identity: Identity,
|
||||
control: &mut ConsumerControl,
|
||||
mut bootstrap: Bootstrap,
|
||||
mut prepared: PreparedScriptTun,
|
||||
mut native: mpsc::Receiver<Native>,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let attempt = identity.attempt;
|
||||
let ConsumerControl { output, messages, .. } = control;
|
||||
prepared.control.set_nonblocking(true)?;
|
||||
let control = UnixStream::from_std(prepared.control)?;
|
||||
let (mut input, mut output) = control.into_split();
|
||||
let (messages_tx, mut messages) = mpsc::channel(8);
|
||||
let reader = tokio::spawn(async move {
|
||||
loop {
|
||||
let message = receive(&mut input).await;
|
||||
let failed = message.is_err();
|
||||
if messages_tx.send(message).await.is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut network = None;
|
||||
let mut session = None;
|
||||
let mut worker = WorkerState::Preparing;
|
||||
let mut online = false;
|
||||
let mut was_connected = false;
|
||||
let mut deadline: Option<Instant> = None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => break,
|
||||
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
|
||||
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
|
||||
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
|
||||
worker = WorkerState::Ready;
|
||||
}
|
||||
Message::Activated if worker == WorkerState::Activating => {
|
||||
ensure!(online, "Script-tun activation completed while VPN was offline");
|
||||
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
|
||||
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
|
||||
worker = WorkerState::Active; was_connected = true; deadline = None;
|
||||
}
|
||||
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
|
||||
Message::Error { message } => bail!("Script-tun worker: {message}"),
|
||||
_ => bail!("Unexpected script-tun consumer message"),
|
||||
},
|
||||
event = native.recv() => match event.context("Native event stream ended")? {
|
||||
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
|
||||
Native::Event(Event::Configuration(config)) => {
|
||||
let observed = config.context("VPN configuration is absent").and_then(observed_network);
|
||||
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
|
||||
let observed = observed?;
|
||||
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
|
||||
else {
|
||||
send(output, &Message::Configure { identity, bootstrap: std::mem::take(&mut bootstrap), network: observed.clone() }).await?;
|
||||
network = Some(observed);
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
let result = async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => break,
|
||||
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
|
||||
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
|
||||
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
|
||||
worker = WorkerState::Ready;
|
||||
}
|
||||
}
|
||||
Native::Event(Event::Reconnecting) => {
|
||||
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
|
||||
online = false;
|
||||
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
|
||||
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
|
||||
send(output, &Message::Suspend).await?; worker = WorkerState::Suspending;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
Message::Activated if worker == WorkerState::Activating => {
|
||||
ensure!(online, "Script-tun activation completed while VPN was offline");
|
||||
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
|
||||
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
|
||||
worker = WorkerState::Active; was_connected = true; deadline = None;
|
||||
}
|
||||
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
|
||||
Message::Error { message } => bail!("Script-tun worker: {message}"),
|
||||
_ => bail!("Unexpected script-tun consumer message"),
|
||||
},
|
||||
event = native.recv() => match event.context("Native event stream ended")? {
|
||||
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
|
||||
Native::Event(Event::Configuration(config)) => {
|
||||
let observed = config.context("VPN configuration is absent").and_then(observed_network);
|
||||
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
|
||||
let observed = observed?;
|
||||
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
|
||||
else {
|
||||
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
|
||||
network = Some(observed);
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
Native::Event(Event::Reconnecting) => {
|
||||
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
|
||||
online = false;
|
||||
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
|
||||
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
|
||||
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
Native::Event(Event::Reconnected) => online = true,
|
||||
Native::Event(_) => {},
|
||||
}
|
||||
Native::Event(Event::Reconnected) => online = true,
|
||||
Native::Event(_) => {},
|
||||
}
|
||||
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
|
||||
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
|
||||
send(output, &Message::Activate).await?;
|
||||
worker = WorkerState::Activating;
|
||||
deadline = Some(Instant::now() + Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(())
|
||||
}.await;
|
||||
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await;
|
||||
drop(output);
|
||||
reader.abort();
|
||||
let _ = reader.await;
|
||||
result
|
||||
}
|
||||
|
||||
fn observed_network(
|
||||
@@ -263,5 +243,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,8 +1,6 @@
|
||||
use super::*;
|
||||
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
|
||||
use openconnect::{VpnSessionInfo, tunnel::Configuration};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
// A generic consumer, with no proxy settings or private worker protocol.
|
||||
struct Consumer {
|
||||
@@ -25,26 +23,16 @@ impl Consumer {
|
||||
launch_id: uuid::Uuid::new_v4(),
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let stopped = cancel.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut prepared = PreparedScriptTun {
|
||||
control: Some(control),
|
||||
let task = tokio::spawn(supervise(
|
||||
identity,
|
||||
PreparedScriptTun {
|
||||
control,
|
||||
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
|
||||
};
|
||||
let channel = prepared.connect().await?;
|
||||
let mut control = ConsumerControl::new(channel);
|
||||
let result = supervise(
|
||||
identity,
|
||||
&mut control,
|
||||
prepared.bootstrap,
|
||||
observations,
|
||||
stopped,
|
||||
events,
|
||||
)
|
||||
.await;
|
||||
control.stop().await;
|
||||
result
|
||||
});
|
||||
},
|
||||
observations,
|
||||
cancel.clone(),
|
||||
events,
|
||||
));
|
||||
Self {
|
||||
control: UnixStream::from_std(child).unwrap(),
|
||||
native,
|
||||
@@ -303,36 +291,3 @@ async fn reconnect_during_activation_returns_clear_error_without_connected() {
|
||||
);
|
||||
assert!(consumer.events.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn supervision_completion_keeps_consumer_alive_until_owner_stops_it() {
|
||||
let (channel, mut peer) = UnixStream::pair().unwrap();
|
||||
let mut control = ConsumerControl::new(channel);
|
||||
let (_native, observations) = mpsc::channel(1);
|
||||
let (events, _notifications) = mpsc::channel(1);
|
||||
let cancellation = CancellationToken::new();
|
||||
cancellation.cancel();
|
||||
supervise(
|
||||
Identity {
|
||||
service_instance: uuid::Uuid::new_v4(),
|
||||
attempt: 1,
|
||||
launch_id: uuid::Uuid::new_v4(),
|
||||
},
|
||||
&mut control,
|
||||
Bootstrap::default(),
|
||||
observations,
|
||||
cancellation,
|
||||
events,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(30), receive(&mut peer))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
control.stop().await;
|
||||
assert!(matches!(receive(&mut peer).await.unwrap(), Message::Stop));
|
||||
drop(control);
|
||||
assert!(receive(&mut peer).await.is_err());
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
pub(super) type ControlStream = tokio::net::UnixStream;
|
||||
pub(crate) struct PreparedScriptTun {
|
||||
pub(super) control: Option<std::os::unix::net::UnixStream>,
|
||||
pub bootstrap: Bootstrap,
|
||||
}
|
||||
|
||||
pub(crate) fn builder(
|
||||
server: &str,
|
||||
cookie: &str,
|
||||
request: &ScriptTunRequest,
|
||||
uid: u32,
|
||||
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
|
||||
request.validate()?;
|
||||
ensure!(uid != 0, "Script-tun worker requires a desktop user");
|
||||
let (control, child) = std::os::unix::net::UnixStream::pair()?;
|
||||
let builder = Vpn::builder(server, cookie).script_tun_program(
|
||||
request.program.to_str().context("Program is not UTF-8")?,
|
||||
&request.args,
|
||||
uid,
|
||||
child.into(),
|
||||
)?;
|
||||
Ok((
|
||||
builder,
|
||||
PreparedScriptTun {
|
||||
control: Some(control),
|
||||
bootstrap: request.bootstrap.clone(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
impl PreparedScriptTun {
|
||||
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
|
||||
let control = self.control.take().context("Worker control pipe is unavailable")?;
|
||||
control.set_nonblocking(true)?;
|
||||
Ok(tokio::net::UnixStream::from_std(control)?)
|
||||
}
|
||||
// The native OpenConnect Unix launcher owns/reaps its child on disconnect.
|
||||
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
process::user_process::UserProcess,
|
||||
script_tun::{Bootstrap, ScriptTunRequest},
|
||||
windows::PipeClientIdentity,
|
||||
};
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
use std::{os::windows::io::AsRawHandle, sync::Arc, time::Duration};
|
||||
use tokio::net::windows::named_pipe::NamedPipeServer;
|
||||
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
|
||||
pub(super) type ControlStream = NamedPipeServer;
|
||||
|
||||
pub(crate) struct PreparedScriptTun {
|
||||
control: Option<NamedPipeServer>,
|
||||
worker: UserProcess,
|
||||
pub(super) bootstrap: Bootstrap,
|
||||
}
|
||||
pub(crate) fn builder(
|
||||
server: &str,
|
||||
cookie: &str,
|
||||
request: &ScriptTunRequest,
|
||||
owner: Arc<PipeClientIdentity>,
|
||||
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
|
||||
request.validate()?;
|
||||
let attempt = uuid::Uuid::new_v4();
|
||||
let control_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Control");
|
||||
let packet_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Packets");
|
||||
let control = owner.create_control_pipe(&control_name)?;
|
||||
let mut packets = owner.create_packet_pipe(&packet_name)?;
|
||||
let worker = UserProcess::launch(
|
||||
owner.primary_token(),
|
||||
&request.program,
|
||||
&request.args,
|
||||
&[
|
||||
("OPENCONNECT_SCRIPT_TUN_CONTROL_PIPE", &control_name),
|
||||
("VPN_PIPE", &packet_name),
|
||||
],
|
||||
)
|
||||
.context("Could not launch the user-session packet worker")?;
|
||||
packets.connect(worker.id(), Duration::from_secs(10))?;
|
||||
// PacketPipe creates only raw overlapped Win32 I/O and never registers IOCP.
|
||||
let builder = unsafe { Vpn::builder(server, cookie).script_tun_pipe(packets.into_handle()) };
|
||||
Ok((
|
||||
builder,
|
||||
PreparedScriptTun {
|
||||
control: Some(control),
|
||||
worker,
|
||||
bootstrap: request.bootstrap.clone(),
|
||||
},
|
||||
))
|
||||
}
|
||||
impl PreparedScriptTun {
|
||||
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
|
||||
ensure!(!self.worker.has_exited()?, "The packet worker exited during startup");
|
||||
let control = self.control.take().context("Worker control pipe is unavailable")?;
|
||||
tokio::time::timeout(Duration::from_secs(10), control.connect())
|
||||
.await
|
||||
.context("Packet control connection timed out")??;
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeClientProcessId(control.as_raw_handle(), &mut pid) } == 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
ensure!(pid == self.worker.id(), "Unexpected packet control client");
|
||||
Ok(control)
|
||||
}
|
||||
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
|
||||
Ok(self.worker.stop()?)
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
//! A credential lease binds the existing desktop session to its Windows token.
|
||||
use crate::session_registry::SessionRegistry;
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
service::transport::WINDOWS_ADMISSION_REQUEST,
|
||||
windows::{PipeClientIdentity, create_service_admission_pipe},
|
||||
};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::windows::named_pipe::NamedPipeServer,
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(super) struct Admission {
|
||||
listener: NamedPipeServer,
|
||||
registry: Arc<SessionRegistry>,
|
||||
}
|
||||
struct Lease {
|
||||
registry: Arc<SessionRegistry>,
|
||||
session: uuid::Uuid,
|
||||
}
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
self.registry.revoke(self.session);
|
||||
}
|
||||
}
|
||||
impl Admission {
|
||||
pub fn new(registry: Arc<SessionRegistry>) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
listener: create_service_admission_pipe(true)?,
|
||||
registry,
|
||||
})
|
||||
}
|
||||
pub async fn run(mut self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
let mut clients = JoinSet::new();
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break Ok(()),
|
||||
result = self.listener.connect() => {
|
||||
if let Err(error) = result { break Err(error.into()); }
|
||||
let next = match create_service_admission_pipe(false) { Ok(next) => next, Err(error) => break Err(error.into()) };
|
||||
let pipe = std::mem::replace(&mut self.listener, next);
|
||||
let registry = self.registry.clone();
|
||||
let cancel = cancel.clone();
|
||||
clients.spawn(async move {
|
||||
if let Err(error) = serve(pipe, registry, cancel).await { log::warn!("Desktop credential lease ended: {error:#}"); }
|
||||
});
|
||||
}
|
||||
_ = clients.join_next(), if !clients.is_empty() => {},
|
||||
}
|
||||
};
|
||||
// Drop each lease before the shared registry and service runtime disappear.
|
||||
clients.abort_all();
|
||||
while clients.join_next().await.is_some() {}
|
||||
result
|
||||
}
|
||||
}
|
||||
async fn serve(
|
||||
mut pipe: NamedPipeServer,
|
||||
registry: Arc<SessionRegistry>,
|
||||
cancel: CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut request = [0; WINDOWS_ADMISSION_REQUEST.len()];
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return Ok(()),
|
||||
result = tokio::time::timeout(Duration::from_secs(10), pipe.read_exact(&mut request)) => { result.context("Desktop admission timed out")??; }
|
||||
}
|
||||
ensure!(
|
||||
request == WINDOWS_ADMISSION_REQUEST,
|
||||
"Invalid desktop admission request"
|
||||
);
|
||||
// This synchronous call impersonates, duplicates and reverts before any await.
|
||||
let identity = Arc::new(PipeClientIdentity::from_pipe(&pipe)?);
|
||||
let credential = registry.issue_windows(env!("CARGO_PKG_VERSION"), identity)?;
|
||||
let _lease = Lease {
|
||||
registry,
|
||||
session: credential.session_id(),
|
||||
};
|
||||
let frame = credential.encode_frame()?;
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return Ok(()),
|
||||
result = tokio::time::timeout(Duration::from_secs(10), pipe.write_all(&frame)) => { result.context("Desktop credential delivery timed out")??; }
|
||||
}
|
||||
let mut byte = [0];
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => {},
|
||||
result = pipe.read(&mut byte) => { ensure!(result? == 0, "Unexpected desktop lease message"); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
use std::{fs::OpenOptions, io, path::Path};
|
||||
|
||||
use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount};
|
||||
|
||||
const ROTATE_BYTES: usize = 5 * 1024 * 1024;
|
||||
const ARCHIVE_COUNT: usize = 3;
|
||||
|
||||
pub(super) fn writer(path: &Path) -> io::Result<FileRotate<AppendCount>> {
|
||||
// Keep startup failure explicit: FileRotate's constructor suppresses open errors.
|
||||
OpenOptions::new().create(true).read(true).append(true).open(path)?;
|
||||
Ok(FileRotate::new(
|
||||
path,
|
||||
AppendCount::new(ARCHIVE_COUNT),
|
||||
ContentLimit::BytesSurpassed(ROTATE_BYTES),
|
||||
Compression::None,
|
||||
None,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{fs, io::Write};
|
||||
|
||||
#[test]
|
||||
fn keeps_the_latest_three_archives_and_complete_current_entry() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("gpservice.log");
|
||||
fs::write(dir.path().join("unrelated.log"), "keep").unwrap();
|
||||
let mut log = writer(&path).unwrap();
|
||||
for marker in b'0'..=b'5' {
|
||||
log.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
|
||||
}
|
||||
log.flush().unwrap();
|
||||
drop(log);
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
|
||||
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
|
||||
let archive = dir.path().join(format!("gpservice.log.{suffix}"));
|
||||
assert_eq!(fs::read(archive).unwrap(), vec![marker; ROTATE_BYTES + 1]);
|
||||
}
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 5);
|
||||
assert_eq!(fs::read_to_string(dir.path().join("unrelated.log")).unwrap(), "keep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_appends_and_accounts_for_existing_file_size() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("gpservice.log");
|
||||
fs::write(&path, "before restart\n").unwrap();
|
||||
{
|
||||
let mut log = writer(&path).unwrap();
|
||||
log.write_all(b"after restart\n").unwrap();
|
||||
}
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "before restart\nafter restart\n");
|
||||
|
||||
let entry = vec![b'x'; ROTATE_BYTES + 1];
|
||||
fs::write(&path, &entry).unwrap();
|
||||
{
|
||||
let mut log = writer(&path).unwrap();
|
||||
log.write_all(b"new entry\n").unwrap();
|
||||
}
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new entry\n");
|
||||
assert_eq!(fs::read(dir.path().join("gpservice.log.1")).unwrap(), entry);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_log_path_remains_a_startup_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert!(writer(dir.path()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
//! Service Control Manager hosting; the GUI remains in the user's desktop session.
|
||||
mod admission;
|
||||
mod logging;
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
||||
};
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
service::vpn_state::VpnState,
|
||||
utils::{lock_file::LockFile, redact::Redaction},
|
||||
};
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
io::Write,
|
||||
sync::{Arc, OnceLock, atomic::AtomicBool},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use windows_service::{
|
||||
define_windows_service,
|
||||
service::{ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType},
|
||||
service_control_handler::{self, ServiceControlHandlerResult, ServiceStatusHandle},
|
||||
service_dispatcher,
|
||||
};
|
||||
const NAME: &str = common::paths::SERVICE_NAME;
|
||||
static LOG_LEVEL: OnceLock<log::Level> = OnceLock::new();
|
||||
define_windows_service!(ffi_service_main, service_main);
|
||||
|
||||
pub(crate) fn dispatch(level: log::Level) -> anyhow::Result<()> {
|
||||
let _ = LOG_LEVEL.set(level);
|
||||
service_dispatcher::start(NAME, ffi_service_main).context("Start GP Connect through the Windows service manager")?;
|
||||
Ok(())
|
||||
}
|
||||
fn status(handle: &ServiceStatusHandle, state: ServiceState, failure: bool) -> windows_service::Result<()> {
|
||||
let running = state == ServiceState::Running;
|
||||
let pending = matches!(state, ServiceState::StartPending | ServiceState::StopPending);
|
||||
handle.set_service_status(ServiceStatus {
|
||||
service_type: ServiceType::OWN_PROCESS,
|
||||
current_state: state,
|
||||
controls_accepted: if running {
|
||||
ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN
|
||||
} else {
|
||||
ServiceControlAccept::empty()
|
||||
},
|
||||
exit_code: if failure {
|
||||
ServiceExitCode::ServiceSpecific(1)
|
||||
} else {
|
||||
ServiceExitCode::Win32(0)
|
||||
},
|
||||
checkpoint: u32::from(pending),
|
||||
wait_hint: if pending {
|
||||
Duration::from_secs(30)
|
||||
} else {
|
||||
Duration::ZERO
|
||||
},
|
||||
process_id: None,
|
||||
})
|
||||
}
|
||||
fn service_main(_arguments: Vec<OsString>) {
|
||||
let stop = CancellationToken::new();
|
||||
let requested = stop.clone();
|
||||
let handle = match service_control_handler::register(NAME, move |control| match control {
|
||||
ServiceControl::Stop | ServiceControl::Shutdown => {
|
||||
requested.cancel();
|
||||
ServiceControlHandlerResult::NoError
|
||||
}
|
||||
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
|
||||
_ => ServiceControlHandlerResult::NotImplemented,
|
||||
}) {
|
||||
Ok(handle) => handle,
|
||||
Err(_) => return,
|
||||
};
|
||||
let result = (|| -> anyhow::Result<()> {
|
||||
status(&handle, ServiceState::StartPending, false)?;
|
||||
ensure!(
|
||||
gpapi::windows::current_user_sid()? == "S-1-5-18",
|
||||
"GP Connect must run as LocalSystem"
|
||||
);
|
||||
let redaction = initialize_logger()?;
|
||||
log::info!("gpservice started: {}", crate::VERSION);
|
||||
crate::vpn_script::recover_network()?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
|
||||
runtime.block_on(run(&handle, stop, redaction))
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
log::error!("Windows service stopped: {error:#}");
|
||||
}
|
||||
let _ = status(&handle, ServiceState::Stopped, result.is_err());
|
||||
}
|
||||
fn initialize_logger() -> anyhow::Result<Arc<Redaction>> {
|
||||
let state = common::paths::service_lock_file();
|
||||
let directory = state.parent().context("Service state directory is unavailable")?;
|
||||
// The installer provisions these directories and their machine-wide ACLs.
|
||||
// Starting the daemon must not create a user-writable fallback location.
|
||||
ensure!(
|
||||
directory.is_dir() && common::paths::service_private_dir().is_dir(),
|
||||
"Install the GP Connect Windows service before starting it"
|
||||
);
|
||||
let writer = logging::writer(&directory.join("gpservice.log"))?;
|
||||
let redaction = Arc::new(Redaction::new());
|
||||
let filter = redaction.clone();
|
||||
let logger = env_logger::builder()
|
||||
.filter_level(log::LevelFilter::Trace)
|
||||
.target(env_logger::Target::Pipe(Box::new(writer)))
|
||||
.format(move |buffer, record| {
|
||||
writeln!(
|
||||
buffer,
|
||||
"[{} {:<5} {}] {}",
|
||||
buffer.timestamp(),
|
||||
record.level(),
|
||||
record.module_path().unwrap_or_default(),
|
||||
filter.redact_str(&record.args().to_string())
|
||||
)
|
||||
})
|
||||
.build();
|
||||
gpapi::logger::init_with_logger(*LOG_LEVEL.get().unwrap_or(&log::Level::Info), logger);
|
||||
Ok(redaction)
|
||||
}
|
||||
async fn run(handle: &ServiceStatusHandle, stop: CancellationToken, redaction: Arc<Redaction>) -> anyhow::Result<()> {
|
||||
let lock = Arc::new(LockFile::new(common::paths::service_lock_file(), std::process::id()));
|
||||
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let admission = admission::Admission::new(registry.clone())?;
|
||||
let (state, observed) = watch::channel(VpnState::Disconnected);
|
||||
let (mut vpn, lifecycle) = VpnTask::new(state, true, registry.clone());
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
lifecycle,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
redaction,
|
||||
false,
|
||||
true,
|
||||
));
|
||||
let websocket = WsServer::new(env!("CARGO_PKG_VERSION"), registry, dispatcher, observed, lock.clone());
|
||||
let service_cancel = websocket.cancel_token();
|
||||
let vpn_cancel = vpn.cancel_token();
|
||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(4);
|
||||
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
|
||||
let vpn_stop = service_cancel.clone();
|
||||
let vpn_handle = tokio::spawn(async move { vpn.start(vpn_stop).await });
|
||||
let websocket_shutdown = shutdown_tx.clone();
|
||||
let websocket_handle = tokio::spawn(async move { websocket.start(websocket_shutdown, ready_tx).await });
|
||||
ready_rx.await.context("Desktop protocol listener failed to start")?;
|
||||
let lease_cancel = service_cancel.clone();
|
||||
let admission_handle = tokio::spawn(async move {
|
||||
if let Err(error) = admission.run(lease_cancel).await {
|
||||
log::error!("Desktop admission stopped: {error:#}");
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
});
|
||||
status(handle, ServiceState::Running, false)?;
|
||||
tokio::select! { _ = stop.cancelled() => {}, _ = shutdown_rx.recv() => {} }
|
||||
let _ = status(handle, ServiceState::StopPending, false);
|
||||
vpn_cancel.cancel();
|
||||
service_cancel.cancel();
|
||||
let _ = tokio::join!(vpn_handle, websocket_handle, admission_handle);
|
||||
lock.unlock()?;
|
||||
log::info!("gpservice stopped");
|
||||
Ok(())
|
||||
}
|
||||
@@ -344,7 +344,6 @@ impl WsServer {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn context(&self) -> Arc<WsServerContext> {
|
||||
Arc::clone(&self.ctx)
|
||||
}
|
||||
|
||||
@@ -1,68 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 3.4.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added gateway selection and switching directly from the system tray or macOS menu bar.
|
||||
|
||||
### Improved
|
||||
|
||||
- Added a Retry Activation action to recover from temporary license activation failures without re-entering the key.
|
||||
- Made sign-in prompts and connection errors visible when connecting or switching gateways from the tray.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed a Native Shell crash after license activation.
|
||||
- Fixed the macOS Tauri interface opening unexpectedly after signing in from the tray while the main window was hidden.
|
||||
- Fixed the Native Shell update button text becoming unreadable when pressed.
|
||||
- Fixed Linux Nix builds using unavailable WebKitGTK dependencies.
|
||||
|
||||
## 3.3.1
|
||||
|
||||
### Improved
|
||||
|
||||
- Made client certificate errors clearer and added more detail to gateway sign-in logs.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Restored support for client certificates with private extensions and legacy RC4-encrypted PKCS#12 files.
|
||||
- Fixed certificate chain selection for PKCS#12 files containing multiple possible issuers.
|
||||
- Fixed certificate validation and recovery guidance in both desktop interfaces.
|
||||
- Fixed Native Shell Settings windows failing to activate from the macOS menu or reopening on the wrong page.
|
||||
- Fixed keyboard navigation and Escape handling in the macOS Native Shell interface.
|
||||
- Fixed AUR package builds and dependency metadata.
|
||||
|
||||
## 3.3.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added Native Shell, a new desktop interface for macOS and Linux. macOS builds now use it by default.
|
||||
- Added an Interface setting on Linux to switch between Tauri and Native Shell.
|
||||
- Added tray icon appearance options for light and dark desktop panels on Linux, FreeBSD, and OpenBSD.
|
||||
- Added in-app feature highlights, with a setting to turn them off.
|
||||
|
||||
### Improved
|
||||
|
||||
- Made System VPN and Local Proxy modes selectable directly from the main window.
|
||||
- Refined connection details, saved-server selection, keyboard navigation, and dialog appearance.
|
||||
- Removed the need for OpenSSL compatibility configuration and external OpenSSL conversion tools.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed macOS VPN DNS configuration and cleanup, including split-tunnel connections.
|
||||
- Fixed background CLI reconnections failing after the initial connection.
|
||||
- Fixed server addresses losing custom ports when pasted as URLs.
|
||||
- Fixed gateway login address handling for servers with explicit ports.
|
||||
- Fixed browser sign-in registration when desktop-specific settings override the callback handler on Linux, FreeBSD, or OpenBSD.
|
||||
- Fixed Okta FastPass failing to open Okta Verify from the embedded sign-in window on Linux, FreeBSD, and OpenBSD.
|
||||
- Fixed supplied server certificate pins not being enforced during tunnel setup.
|
||||
- Fixed delayed clicks activating a different control after a Native Shell view changed.
|
||||
|
||||
### Command-line notes
|
||||
|
||||
- Deprecated `--fix-openssl` on Linux, FreeBSD, and OpenBSD. Existing commands still accept it, but it has no effect.
|
||||
|
||||
## 3.2.0
|
||||
|
||||
### Added
|
||||
|
||||
+1
-16
@@ -20,6 +20,7 @@ browser-launcher = { path = "../browser-launcher", default-features = false, fea
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
tempfile = { workspace = true, optional = true }
|
||||
uuid = { version = "1", optional = true, features = ["v4"] }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
# Webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
@@ -27,7 +28,6 @@ regex = { workspace = true, optional = true }
|
||||
tokio-util = { workspace = true, optional = true }
|
||||
html-escape = { version = "0.3", optional = true }
|
||||
url = { workspace = true, optional = true }
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||
webkit2gtk = { version = "2", optional = true }
|
||||
@@ -60,9 +60,6 @@ webview-auth = [
|
||||
"dep:tokio-util",
|
||||
"dep:html-escape",
|
||||
"dep:url",
|
||||
"dep:serde_json",
|
||||
"dep:webview2-com",
|
||||
"dep:windows",
|
||||
"dep:gtk",
|
||||
"dep:webkit2gtk",
|
||||
"dep:block2",
|
||||
@@ -97,15 +94,3 @@ release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Child webviews let the Windows host own layout beside native controls.
|
||||
tauri = { workspace = true, optional = true, features = ["unstable"] }
|
||||
webview2-com = { version = "0.39", optional = true }
|
||||
windows = { version = "0.62", optional = true, features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_UI_Controls", "Win32_UI_HiDpi", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
|
||||
dunce = "1"
|
||||
winreg = "0.55"
|
||||
common = { path = "../common" }
|
||||
@@ -3,6 +3,7 @@ use std::{
|
||||
io::ErrorKind,
|
||||
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
@@ -13,9 +14,16 @@ use tokio::{
|
||||
time::timeout,
|
||||
};
|
||||
|
||||
mod protocol;
|
||||
pub use protocol::validate_auth_callback;
|
||||
use protocol::*;
|
||||
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||
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;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
@@ -224,9 +232,62 @@ fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
if callback.len() > MAX_CALLBACK_SIZE {
|
||||
bail!("Authentication callback exceeds the maximum supported size");
|
||||
}
|
||||
|
||||
let Some((scheme, data)) = callback.split_once(':') else {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
};
|
||||
if scheme != CALLBACK_SCHEME || data.is_empty() {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum CallbackReadError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
Io,
|
||||
}
|
||||
|
||||
async fn read_callback(stream: &mut UnixStream) -> Result<String, CallbackReadError> {
|
||||
let mut magic = [0_u8; 4];
|
||||
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
|
||||
if &magic != PROTOCOL_MAGIC {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
|
||||
if version != PROTOCOL_VERSION {
|
||||
return Err(CallbackReadError::UnsupportedVersion);
|
||||
}
|
||||
|
||||
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
|
||||
if length == 0 || length > MAX_CALLBACK_SIZE {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut payload)
|
||||
.await
|
||||
.map_err(|_| CallbackReadError::Io)?;
|
||||
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
|
||||
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u8(status).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
//! Bounded authentication callback wire format, shared by local transports.
|
||||
use anyhow::bail;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
pub(super) const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
pub(super) const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||
pub(super) const PROTOCOL_VERSION: u8 = 1;
|
||||
pub(super) const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
|
||||
pub(super) const IO_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
// Acceptance acknowledges delivery, including an authentication failure.
|
||||
pub(super) const STATUS_ACCEPTED: u8 = 0;
|
||||
pub(super) const STATUS_INVALID_CALLBACK: u8 = 1;
|
||||
pub(super) const STATUS_UNSUPPORTED_VERSION: u8 = 2;
|
||||
|
||||
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
if callback.len() > MAX_CALLBACK_SIZE {
|
||||
bail!("Authentication callback exceeds the maximum supported size");
|
||||
}
|
||||
|
||||
let Some((scheme, data)) = callback.split_once(':') else {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
};
|
||||
if scheme != CALLBACK_SCHEME || data.is_empty() {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) enum CallbackReadError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
Io,
|
||||
}
|
||||
|
||||
pub(super) async fn read_callback(
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
) -> Result<String, CallbackReadError> {
|
||||
let mut magic = [0_u8; 4];
|
||||
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
|
||||
if &magic != PROTOCOL_MAGIC {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
|
||||
if version != PROTOCOL_VERSION {
|
||||
return Err(CallbackReadError::UnsupportedVersion);
|
||||
}
|
||||
|
||||
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
|
||||
if length == 0 || length > MAX_CALLBACK_SIZE {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut payload)
|
||||
.await
|
||||
.map_err(|_| CallbackReadError::Io)?;
|
||||
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
|
||||
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
pub(super) async fn write_response(
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
status: u8,
|
||||
) -> anyhow::Result<()> {
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u8(status).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
//! Per-user Windows named pipe for browser authentication callbacks.
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::windows::named_pipe::{ClientOptions, NamedPipeServer},
|
||||
time::timeout,
|
||||
};
|
||||
#[path = "protocol.rs"]
|
||||
mod protocol;
|
||||
pub use protocol::validate_auth_callback;
|
||||
use protocol::*;
|
||||
|
||||
pub struct AuthCallbackReceiver {
|
||||
listener: NamedPipeServer,
|
||||
}
|
||||
impl AuthCallbackReceiver {
|
||||
pub fn bind() -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
listener: gpapi::windows::create_user_pipe(&pipe_name()?, true)
|
||||
.context("Another browser authentication is already waiting")?,
|
||||
})
|
||||
}
|
||||
pub async fn receive(mut self) -> anyhow::Result<SamlAuthData> {
|
||||
loop {
|
||||
self.listener.connect().await?;
|
||||
let mut stream = &mut self.listener;
|
||||
let callback = timeout(IO_TIMEOUT, read_callback(&mut stream)).await;
|
||||
let result = match callback {
|
||||
Ok(Ok(callback)) => match SamlAuthData::from_gpcallback(&callback) {
|
||||
Ok(data) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
Some(Ok(data))
|
||||
}
|
||||
Err(error @ AuthDataParseError::AuthenticationFailed(_)) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
Some(Err(error.into()))
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
None
|
||||
}
|
||||
},
|
||||
Ok(Err(CallbackReadError::UnsupportedVersion)) => {
|
||||
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// DisconnectNamedPipe discards unread response bytes. Wait for the client
|
||||
// to confirm it consumed the response before disconnecting this instance.
|
||||
let _ = timeout(IO_TIMEOUT, stream.read_u8()).await;
|
||||
self.listener.disconnect()?;
|
||||
if let Some(result) = result {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn pipe_name() -> anyhow::Result<String> {
|
||||
Ok(format!(
|
||||
r"\\.\pipe\GPConnect.Auth.{}",
|
||||
gpapi::windows::current_user_sid()?
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
validate_auth_callback(callback)?;
|
||||
timeout(IO_TIMEOUT, async {
|
||||
let mut stream = ClientOptions::new()
|
||||
.open(pipe_name()?)
|
||||
.context("No external-browser authentication is waiting for a callback")?;
|
||||
stream.write_all(PROTOCOL_MAGIC).await?;
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u32(callback.len() as u32).await?;
|
||||
stream.write_all(callback.as_bytes()).await?;
|
||||
let version = stream.read_u8().await?;
|
||||
let status = stream.read_u8().await?;
|
||||
stream.write_u8(status).await?;
|
||||
anyhow::ensure!(
|
||||
version == PROTOCOL_VERSION,
|
||||
"Authentication callback protocol version mismatch"
|
||||
);
|
||||
match status {
|
||||
STATUS_ACCEPTED => Ok(()),
|
||||
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
|
||||
_ => bail!("Authentication callback protocol is unsupported"),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("Timed out forwarding the authentication callback")?
|
||||
}
|
||||
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
use winreg::{RegKey, enums::HKEY_CURRENT_USER};
|
||||
let executable = common::binary_paths::gpauth();
|
||||
anyhow::ensure!(executable.is_file(), "The authentication helper is missing");
|
||||
let root = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let (scheme, _) = root.create_subkey(r"Software\Classes\globalprotectcallback")?;
|
||||
scheme.set_value("", &"URL:GlobalProtect authentication callback")?;
|
||||
scheme.set_value("URL Protocol", &"")?;
|
||||
let (command, _) = scheme.create_subkey(r"shell\open\command")?;
|
||||
// URL association activation requires a shell path, not Rust's verbatim
|
||||
// canonical path (\\?\C:\...), even though CreateProcess accepts both.
|
||||
let executable = dunce::simplified(&executable);
|
||||
command.set_value("", &format!("\"{}\" auth-callback \"%1\"", executable.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn forwards_browser_callback_over_private_windows_pipe() {
|
||||
let receiver = AuthCallbackReceiver::bind().unwrap();
|
||||
// The first-instance flag preserves one pending browser authentication per user.
|
||||
assert!(AuthCallbackReceiver::bind().is_err());
|
||||
let sender = tokio::spawn(async {
|
||||
forward_auth_callback("globalprotectcallback:cas-as=1&[email protected]&token=test-token").await
|
||||
});
|
||||
let data = timeout(std::time::Duration::from_secs(5), receiver.receive())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(data.username(), "[email protected]");
|
||||
assert_eq!(data.token(), Some("test-token"));
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use gpapi::{
|
||||
mod browser;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
#[cfg_attr(windows, path = "callback/windows.rs")]
|
||||
mod callback;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
|
||||
@@ -12,17 +12,12 @@ mod platform_impl;
|
||||
#[path = "webview/macos.rs"]
|
||||
mod platform_impl;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "webview/windows.rs"]
|
||||
mod platform_impl;
|
||||
|
||||
#[cfg(not(any(
|
||||
windows,
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
compile_error!("webview-auth is only supported on Windows, macOS and GTK/WebKitGTK Unix targets");
|
||||
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
|
||||
|
||||
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
@@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AuthDataLocation {
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
Headers,
|
||||
Body,
|
||||
}
|
||||
@@ -155,7 +155,7 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
|
||||
use log::warn;
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
#[cfg(not(windows))]
|
||||
use gpapi::utils::window::get_title_bar_height;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||
use gpapi::{
|
||||
@@ -10,51 +8,24 @@ use gpapi::{
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::redact::redact_uri,
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
};
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
#[cfg(not(windows))]
|
||||
use tauri::WebviewUrl;
|
||||
use tauri::{AppHandle, WindowEvent};
|
||||
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
|
||||
use tokio::{sync::oneshot, time};
|
||||
|
||||
use crate::auth_prelogin;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use super::address_bar::TOOLBAR_HEIGHT;
|
||||
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
||||
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
|
||||
|
||||
#[cfg(not(windows))]
|
||||
type AuthWindow = tauri::WebviewWindow;
|
||||
#[cfg(windows)]
|
||||
use super::platform_impl::{AuthWindow, create_auth_window};
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn create_auth_window(app: &AppHandle, title: &str, theme: Option<tauri::Theme>) -> anyhow::Result<AuthWindow> {
|
||||
let builder = AuthWindow::builder(app, "auth_window", WebviewUrl::default())
|
||||
.title(title)
|
||||
.theme(theme)
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let builder = builder.on_navigation(super::platform_impl::open_okta_verify);
|
||||
Ok(
|
||||
builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?,
|
||||
)
|
||||
}
|
||||
|
||||
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(super) trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
pub trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
|
||||
|
||||
@@ -83,7 +54,7 @@ pub(super) trait PlatformWebviewExt {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub trait GetHeader {
|
||||
fn get_header(&self, key: &str) -> Option<String>;
|
||||
}
|
||||
@@ -154,7 +125,19 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||
let auth_messenger = Arc::new(AuthMessenger::new());
|
||||
let auth_window = create_auth_window(app_handle, self.window_title, native_theme(self.window_theme))?;
|
||||
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let auth_window_builder = auth_window_builder.on_navigation(super::platform_impl::open_okta_verify);
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||
@@ -187,7 +170,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
async fn wait_for_auth(
|
||||
&self,
|
||||
auth_window: &AuthWindow,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<SamlAuthData> {
|
||||
let mut recovery = Recovery::default();
|
||||
@@ -327,16 +310,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
async fn setup_auth_window(
|
||||
&self,
|
||||
auth_window: &AuthWindow,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<()> {
|
||||
info!("Setting up auth window...");
|
||||
|
||||
if self.clean {
|
||||
info!("Clearing all browsing data...");
|
||||
#[cfg(windows)]
|
||||
super::platform_impl::clear_browsing_data(auth_window).await?;
|
||||
#[cfg(not(windows))]
|
||||
auth_window.clear_all_browsing_data()?;
|
||||
}
|
||||
|
||||
@@ -381,7 +361,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_not_found(&self, auth_window: &AuthWindow, auth_messenger: &Arc<AuthMessenger>) {
|
||||
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
|
||||
let visible = auth_window.is_visible().unwrap_or(false);
|
||||
if visible {
|
||||
return;
|
||||
@@ -390,7 +370,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_messenger.schedule_raise_window(2);
|
||||
}
|
||||
|
||||
fn update_recovery(&self, auth_window: &AuthWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
if status != RecoveryStatus::Hidden {
|
||||
self.raise_window(auth_window);
|
||||
}
|
||||
@@ -417,7 +397,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
fn load_restarted_sign_in(
|
||||
&self,
|
||||
auth_window: &AuthWindow,
|
||||
auth_window: &WebviewWindow,
|
||||
messenger: &Arc<AuthMessenger>,
|
||||
auth_request: String,
|
||||
) -> anyhow::Result<()> {
|
||||
@@ -435,7 +415,7 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn raise_window(&self, auth_window: &AuthWindow) {
|
||||
fn raise_window(&self, auth_window: &WebviewWindow) {
|
||||
let visible = auth_window.is_visible().unwrap_or(false);
|
||||
if visible {
|
||||
return;
|
||||
|
||||
@@ -1,380 +0,0 @@
|
||||
//! WebView2 authentication. All COM objects and native controls stay on the UI thread.
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth_messenger::{AuthDataLocation, AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::{GetHeader, PlatformWebviewExt},
|
||||
};
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use tauri::{
|
||||
AppHandle, LogicalPosition, Webview, WebviewBuilder, WebviewUrl, Window, WindowBuilder, webview::PlatformWebview,
|
||||
};
|
||||
use webview2_com::{
|
||||
ClearBrowsingDataCompletedHandler, CoTaskMemPWSTR, DOMContentLoadedEventHandler, ExecuteScriptCompletedHandler,
|
||||
Microsoft::Web::WebView2::Win32::*, NavigationCompletedEventHandler, NavigationStartingEventHandler,
|
||||
SourceChangedEventHandler, WebResourceResponseReceivedEventHandler,
|
||||
};
|
||||
use windows::core::{BOOL, HSTRING, Interface, PWSTR};
|
||||
|
||||
#[path = "windows/controls.rs"]
|
||||
mod controls;
|
||||
#[path = "windows/tls.rs"]
|
||||
mod tls;
|
||||
|
||||
/// Windows hosts native chrome and a manually sized child webview in one window.
|
||||
/// Host-owned child bounds keep the page surface below the native controls
|
||||
/// throughout live resizing.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct AuthWindow {
|
||||
window: Window,
|
||||
webview: Webview,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for AuthWindow {
|
||||
type Target = Window;
|
||||
fn deref(&self) -> &Window {
|
||||
&self.window
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthWindow {
|
||||
pub(super) fn with_webview(&self, callback: impl FnOnce(PlatformWebview) + Send + 'static) -> tauri::Result<()> {
|
||||
self.webview.with_webview(callback)
|
||||
}
|
||||
}
|
||||
|
||||
impl gpapi::utils::window::WindowExt for AuthWindow {
|
||||
fn raise(&self) -> anyhow::Result<()> {
|
||||
self.window.show()?;
|
||||
self.window.set_focus()?;
|
||||
self.webview.set_focus()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_auth_window(
|
||||
app: &AppHandle,
|
||||
title: &str,
|
||||
theme: Option<tauri::Theme>,
|
||||
) -> anyhow::Result<AuthWindow> {
|
||||
let window = WindowBuilder::new(app, "auth_window")
|
||||
.title(title)
|
||||
.theme(theme)
|
||||
.inner_size(900.0, 650.0 + super::address_bar::TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
let webview = window.add_child(
|
||||
WebviewBuilder::new("auth_webview", WebviewUrl::default())
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools"))),
|
||||
LogicalPosition::new(0.0, 0.0),
|
||||
window.inner_size()?,
|
||||
)?;
|
||||
Ok(AuthWindow { window, webview })
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STATES: RefCell<HashMap<usize, Rc<State>>> = RefCell::default();
|
||||
}
|
||||
|
||||
struct State {
|
||||
core: ICoreWebView2,
|
||||
controller: ICoreWebView2Controller,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
controls: controls::Controls,
|
||||
pending: Cell<Option<u64>>,
|
||||
navigations: RefCell<HashMap<u64, u64>>,
|
||||
document: RefCell<(String, u64)>,
|
||||
tls: RefCell<tls::Policy>,
|
||||
}
|
||||
|
||||
fn text(get: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
|
||||
let mut value = PWSTR::null();
|
||||
let result = get(&mut value);
|
||||
let value = CoTaskMemPWSTR::from(value);
|
||||
result?;
|
||||
Ok(value.to_string())
|
||||
}
|
||||
|
||||
fn state(webview: &PlatformWebview) -> anyhow::Result<Rc<State>> {
|
||||
let core = unsafe { webview.controller().CoreWebView2()? };
|
||||
STATES
|
||||
.with_borrow(|states| states.get(&(core.as_raw() as usize)).cloned())
|
||||
.context("Authentication controls are unavailable")
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn read_html(&self, generation: u64) -> windows::core::Result<()> {
|
||||
if generation != self.messenger.generation() {
|
||||
return Ok(());
|
||||
}
|
||||
let messenger = Arc::clone(&self.messenger);
|
||||
unsafe {
|
||||
self.core.ExecuteScript(
|
||||
&HSTRING::from("document.documentElement.outerHTML"),
|
||||
&ExecuteScriptCompletedHandler::create(Box::new(move |result, json| {
|
||||
result?;
|
||||
if let Ok(html) = serde_json::from_str::<String>(&json) {
|
||||
messenger.read_from_html(&html, generation);
|
||||
}
|
||||
Ok(())
|
||||
})),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn listen(self: &Rc<Self>) -> windows::core::Result<()> {
|
||||
let mut token = 0;
|
||||
let weak = Rc::downgrade(self);
|
||||
let starting = NavigationStartingEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let mut id = 0;
|
||||
args.NavigationId(&mut id)?;
|
||||
let generation = *state
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.entry(id)
|
||||
.or_insert_with(|| state.pending.take().unwrap_or_else(|| state.messenger.generation()));
|
||||
let uri = text(|p| args.Uri(p))?;
|
||||
if uri.starts_with("globalprotectcallback:") {
|
||||
args.SetCancel(true)?;
|
||||
match SamlAuthData::from_gpcallback(&uri) {
|
||||
Ok(data) => state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
|
||||
Err(error) => state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(error.into()))),
|
||||
}
|
||||
} else if generation == state.messenger.generation() {
|
||||
*state.document.borrow_mut() = (uri, generation);
|
||||
state.messenger.cancel_raise_window();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self.core.add_NavigationStarting(&starting, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let loaded = DOMContentLoadedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut id = 0;
|
||||
unsafe {
|
||||
args.NavigationId(&mut id)?;
|
||||
}
|
||||
let generation = state.navigations.borrow().get(&id).copied();
|
||||
if let Some(generation) = generation {
|
||||
state.read_html(generation)?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self
|
||||
.core
|
||||
.cast::<ICoreWebView2_2>()?
|
||||
.add_DOMContentLoaded(&loaded, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let completed = NavigationCompletedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let mut id = 0;
|
||||
args.NavigationId(&mut id)?;
|
||||
let Some(generation) = state.navigations.borrow_mut().remove(&id) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut success = BOOL(0);
|
||||
args.IsSuccess(&mut success)?;
|
||||
if success.as_bool() {
|
||||
state.read_html(generation)?;
|
||||
state.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
} else {
|
||||
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
|
||||
args.WebErrorStatus(&mut error)?;
|
||||
if error != COREWEBVIEW2_WEB_ERROR_STATUS_OPERATION_CANCELED {
|
||||
state.messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::LoadFailed(anyhow::anyhow!("WebView2 navigation failed ({})", error.0)),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self.core.add_NavigationCompleted(&completed, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let source = SourceChangedEventHandler::create(Box::new(move |_, _| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
let uri = unsafe { text(|p| state.core.Source(p))? };
|
||||
state.controls.set_address(&uri)?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self.core.add_SourceChanged(&source, &mut token)?;
|
||||
}
|
||||
|
||||
let weak = Rc::downgrade(self);
|
||||
let response = WebResourceResponseReceivedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let uri = text(|p| args.Request()?.Uri(p))?;
|
||||
let (document, generation) = state.document.borrow().clone();
|
||||
// Subresources must not supply authentication credentials for the page.
|
||||
if uri == document && generation == state.messenger.generation() {
|
||||
state
|
||||
.messenger
|
||||
.read_from_response(&Headers(args.Response()?.Headers()?), generation);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
unsafe {
|
||||
self
|
||||
.core
|
||||
.cast::<ICoreWebView2_2>()?
|
||||
.add_WebResourceResponseReceived(&response, &mut token)?;
|
||||
}
|
||||
tls::install(self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Headers(ICoreWebView2HttpResponseHeaders);
|
||||
impl GetHeader for Headers {
|
||||
fn get_header(&self, key: &str) -> Option<String> {
|
||||
unsafe { text(|p| self.0.GetHeader(&HSTRING::from(key), p)).ok() }
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let controller = self.controller();
|
||||
let core = unsafe { controller.CoreWebView2()? };
|
||||
let key = core.as_raw() as usize;
|
||||
let controls = controls::Controls::new(window, &controller, key)?;
|
||||
let state = Rc::new(State {
|
||||
core,
|
||||
controller,
|
||||
messenger,
|
||||
controls,
|
||||
pending: Cell::new(None),
|
||||
navigations: RefCell::default(),
|
||||
document: RefCell::new((String::new(), 0)),
|
||||
tls: RefCell::default(),
|
||||
});
|
||||
STATES.with_borrow_mut(|states| states.insert(key, Rc::clone(&state)));
|
||||
state.listen()?;
|
||||
state.controls.layout(&state)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let state = state(self)?;
|
||||
state.controls.update(&state, status)?;
|
||||
Ok(())
|
||||
}
|
||||
fn stop_loading(&self) {
|
||||
let _ = unsafe { self.controller().CoreWebView2().and_then(|wv| wv.Stop()) };
|
||||
}
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(state(self)?.as_ref())
|
||||
}
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
state(self)?.tls.borrow_mut().ignore_errors = true;
|
||||
Ok(())
|
||||
}
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
unsafe {
|
||||
Ok(text(|p| {
|
||||
self
|
||||
.controller()
|
||||
.CoreWebView2()?
|
||||
.Settings()?
|
||||
.cast::<ICoreWebView2Settings2>()?
|
||||
.UserAgent(p)
|
||||
})?)
|
||||
}
|
||||
}
|
||||
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
|
||||
unsafe {
|
||||
self
|
||||
.controller()
|
||||
.CoreWebView2()?
|
||||
.Settings()?
|
||||
.cast::<ICoreWebView2Settings2>()?
|
||||
.SetUserAgent(&HSTRING::from(user_agent))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn load_url(&self, url: &str) -> anyhow::Result<()> {
|
||||
let state = state(self)?;
|
||||
state.pending.set(Some(state.messenger.generation()));
|
||||
unsafe {
|
||||
state.core.Navigate(&HSTRING::from(url))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
let state = state(self)?;
|
||||
state.pending.set(Some(state.messenger.generation()));
|
||||
unsafe {
|
||||
state.core.NavigateToString(&HSTRING::from(html))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// WebView2 clears profiles asynchronously; do not navigate until cookies are gone.
|
||||
pub(super) async fn clear_browsing_data(window: &AuthWindow) -> anyhow::Result<()> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
window.with_webview(move |wv| {
|
||||
let tx = Rc::new(RefCell::new(Some(tx)));
|
||||
let complete = Rc::clone(&tx);
|
||||
let callback = ClearBrowsingDataCompletedHandler::create(Box::new(move |result| {
|
||||
if let Some(tx) = complete.borrow_mut().take() {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
let result = (|| unsafe {
|
||||
wv.controller()
|
||||
.CoreWebView2()?
|
||||
.cast::<ICoreWebView2_13>()?
|
||||
.Profile()?
|
||||
.cast::<ICoreWebView2Profile2>()?
|
||||
.ClearBrowsingDataAll(&callback)
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
if let Some(tx) = tx.borrow_mut().take() {
|
||||
let _ = tx.send(Err(error));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
rx.await.context("Could not clear sign-in data")??;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,334 +0,0 @@
|
||||
//! Native controls remain outside the identity provider's document.
|
||||
use super::*;
|
||||
use windows::{
|
||||
Win32::{
|
||||
Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM},
|
||||
Graphics::Gdi::*,
|
||||
UI::{
|
||||
Controls::EM_SETRECT,
|
||||
HiDpi::{GetDpiForWindow, SystemParametersInfoForDpi},
|
||||
Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
|
||||
WindowsAndMessaging::*,
|
||||
},
|
||||
},
|
||||
core::{PCWSTR, w},
|
||||
};
|
||||
|
||||
const SUBCLASS: usize = 0x47504155;
|
||||
const ADDRESS_SUBCLASS: usize = 0x47504156;
|
||||
const ADDRESS_HEIGHT: i32 = 24;
|
||||
const TOOLBAR_HEIGHT: i32 = 34;
|
||||
const RETRY: usize = 101;
|
||||
const PROCEED: usize = 102;
|
||||
const CANCEL: usize = 103;
|
||||
|
||||
pub(super) struct Controls {
|
||||
pub(super) parent: HWND,
|
||||
webview_host: HWND,
|
||||
address: HWND,
|
||||
message: HWND,
|
||||
retry: HWND,
|
||||
proceed: HWND,
|
||||
cancel: HWND,
|
||||
status: Cell<RecoveryStatus>,
|
||||
font: Cell<Option<(u32, HFONT)>>,
|
||||
}
|
||||
|
||||
impl Controls {
|
||||
pub(super) fn new(window: &AuthWindow, controller: &ICoreWebView2Controller, key: usize) -> anyhow::Result<Self> {
|
||||
// The host owns both the toolbar and the child webview's remaining area.
|
||||
let parent = HWND(window.hwnd()?.0);
|
||||
let mut webview_host = HWND::default();
|
||||
unsafe {
|
||||
controller.ParentWindow(&mut webview_host)?;
|
||||
}
|
||||
let child = |class: PCWSTR, title: &str, style: WINDOW_STYLE, id: usize| -> windows::core::Result<HWND> {
|
||||
unsafe {
|
||||
let hwnd = CreateWindowExW(
|
||||
WINDOW_EX_STYLE::default(),
|
||||
class,
|
||||
&HSTRING::from(title),
|
||||
WS_CHILD | style,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
Some(parent),
|
||||
Some(HMENU(id as *mut _)),
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
Ok(hwnd)
|
||||
}
|
||||
};
|
||||
let controls = Self {
|
||||
parent,
|
||||
webview_host,
|
||||
address: child(
|
||||
w!("EDIT"),
|
||||
super::super::address_bar::LOADING_ADDRESS,
|
||||
WS_VISIBLE | WS_BORDER | WINDOW_STYLE(ES_READONLY as u32 | ES_MULTILINE as u32 | ES_AUTOHSCROLL as u32),
|
||||
0,
|
||||
)?,
|
||||
message: child(w!("STATIC"), "", WINDOW_STYLE::default(), 0)?,
|
||||
retry: child(w!("BUTTON"), "Try Again", WS_TABSTOP, RETRY)?,
|
||||
proceed: child(w!("BUTTON"), "Continue Anyway…", WS_TABSTOP, PROCEED)?,
|
||||
cancel: child(w!("BUTTON"), "Cancel", WS_TABSTOP, CANCEL)?,
|
||||
status: Cell::new(RecoveryStatus::Hidden),
|
||||
font: Cell::new(None),
|
||||
};
|
||||
unsafe {
|
||||
anyhow::ensure!(
|
||||
SetWindowSubclass(controls.address, Some(address_proc), ADDRESS_SUBCLASS, 0).as_bool(),
|
||||
"Could not style the sign-in address"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
SetWindowSubclass(parent, Some(window_proc), SUBCLASS, key).as_bool(),
|
||||
"Could not install sign-in controls"
|
||||
);
|
||||
}
|
||||
Ok(controls)
|
||||
}
|
||||
|
||||
pub(super) fn set_address(&self, uri: &str) -> windows::core::Result<()> {
|
||||
unsafe {
|
||||
SetWindowTextW(
|
||||
self.address,
|
||||
&HSTRING::from(super::super::address_bar::display_address(Some(uri))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update(&self, state: &State, status: RecoveryStatus) -> windows::core::Result<()> {
|
||||
self.status.set(status);
|
||||
let message = if status.detail().is_empty() {
|
||||
status.message().to_owned()
|
||||
} else {
|
||||
format!("{}\r\n{}", status.message(), status.detail())
|
||||
};
|
||||
unsafe {
|
||||
SetWindowTextW(self.message, &HSTRING::from(message))?;
|
||||
for (hwnd, visible) in [
|
||||
(self.message, status != RecoveryStatus::Hidden),
|
||||
(self.retry, status.can_retry()),
|
||||
(self.proceed, status.can_continue()),
|
||||
(self.cancel, status.blocks_page()),
|
||||
] {
|
||||
let _ = ShowWindow(hwnd, if visible { SW_SHOW } else { SW_HIDE });
|
||||
}
|
||||
state.controller.SetIsVisible(!status.blocks_page())?;
|
||||
}
|
||||
self.layout(state)
|
||||
}
|
||||
|
||||
pub(super) fn layout(&self, state: &State) -> windows::core::Result<()> {
|
||||
unsafe {
|
||||
let dpi = GetDpiForWindow(self.parent);
|
||||
let scale = dpi as f64 / 96.0;
|
||||
let px = |value: i32| (value as f64 * scale).round() as i32;
|
||||
let mut bounds = RECT::default();
|
||||
GetClientRect(self.parent, &mut bounds)?;
|
||||
let width = bounds.right;
|
||||
if self.font.get().is_none_or(|(current_dpi, _)| current_dpi != dpi) {
|
||||
let mut metrics = NONCLIENTMETRICSW {
|
||||
cbSize: std::mem::size_of::<NONCLIENTMETRICSW>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
SystemParametersInfoForDpi(
|
||||
SPI_GETNONCLIENTMETRICS.0,
|
||||
metrics.cbSize,
|
||||
Some(&mut metrics as *mut _ as *mut _),
|
||||
0,
|
||||
dpi,
|
||||
)?;
|
||||
metrics.lfMessageFont.lfHeight = -px(13);
|
||||
let font = CreateFontIndirectW(&metrics.lfMessageFont);
|
||||
if font.is_invalid() {
|
||||
return Err(windows::core::Error::from_thread());
|
||||
}
|
||||
for control in [self.address, self.message, self.retry, self.proceed, self.cancel] {
|
||||
SendMessageW(control, WM_SETFONT, Some(WPARAM(font.0 as usize)), Some(LPARAM(1)));
|
||||
}
|
||||
if let Some((_, old)) = self.font.replace(Some((dpi, font))) {
|
||||
let _ = DeleteObject(old.into());
|
||||
}
|
||||
}
|
||||
MoveWindow(
|
||||
self.address,
|
||||
px(8),
|
||||
px(5),
|
||||
(width - px(16)).max(0),
|
||||
px(ADDRESS_HEIGHT),
|
||||
true,
|
||||
)?;
|
||||
// A one-line formatting rectangle centers the native read-only edit text.
|
||||
// ES_AUTOHSCROLL keeps long URLs on one line and lets users select/copy them.
|
||||
let mut client = RECT::default();
|
||||
GetClientRect(self.address, &mut client)?;
|
||||
let dc = GetDC(Some(self.address));
|
||||
let previous = SelectObject(dc, self.font.get().expect("font initialized").1.into());
|
||||
let mut text_metrics = TEXTMETRICW::default();
|
||||
let measured = GetTextMetricsW(dc, &mut text_metrics);
|
||||
SelectObject(dc, previous);
|
||||
ReleaseDC(Some(self.address), dc);
|
||||
measured.ok()?;
|
||||
let top = ((client.bottom - text_metrics.tmHeight) / 2).max(0);
|
||||
let text = RECT {
|
||||
left: px(6),
|
||||
top,
|
||||
right: client.right - px(6),
|
||||
bottom: top + text_metrics.tmHeight,
|
||||
};
|
||||
SendMessageW(
|
||||
self.address,
|
||||
EM_SETRECT,
|
||||
Some(WPARAM(0)),
|
||||
Some(LPARAM(&text as *const _ as isize)),
|
||||
);
|
||||
let status = self.status.get();
|
||||
let header = if status == RecoveryStatus::Hidden {
|
||||
TOOLBAR_HEIGHT
|
||||
} else {
|
||||
TOOLBAR_HEIGHT + 68
|
||||
};
|
||||
MoveWindow(
|
||||
self.message,
|
||||
px(8),
|
||||
px(TOOLBAR_HEIGHT + 2),
|
||||
(width - px(16)).max(0),
|
||||
px(38),
|
||||
true,
|
||||
)?;
|
||||
let mut right = width - px(8);
|
||||
for (hwnd, visible, size) in [
|
||||
(self.cancel, status.blocks_page(), 70),
|
||||
(self.proceed, status.can_continue(), 136),
|
||||
(self.retry, status.can_retry(), 84),
|
||||
] {
|
||||
if visible {
|
||||
right -= px(size);
|
||||
MoveWindow(hwnd, right, px(TOOLBAR_HEIGHT + 38), px(size), px(28), true)?;
|
||||
right -= px(6);
|
||||
}
|
||||
}
|
||||
let content_height = (bounds.bottom - px(header)).max(0);
|
||||
MoveWindow(self.webview_host, 0, px(header), width, content_height, true)?;
|
||||
state.controller.SetBounds(RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: width,
|
||||
bottom: content_height,
|
||||
})?;
|
||||
let _ = InvalidateRect(Some(self.parent), None, true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Controls {
|
||||
fn drop(&mut self) {
|
||||
if let Some((_, font)) = self.font.get() {
|
||||
unsafe {
|
||||
let _ = DeleteObject(font.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the native edit's selection and accessibility, with a quiet, flat frame.
|
||||
unsafe extern "system" fn address_proc(
|
||||
hwnd: HWND,
|
||||
msg: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
id: usize,
|
||||
_: usize,
|
||||
) -> LRESULT {
|
||||
if msg == WM_NCDESTROY {
|
||||
unsafe {
|
||||
let _ = RemoveWindowSubclass(hwnd, Some(address_proc), id);
|
||||
}
|
||||
}
|
||||
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
|
||||
// EDIT also repaints its frame during WM_PAINT, so style it after native drawing.
|
||||
if matches!(msg, WM_NCPAINT | WM_PAINT) {
|
||||
unsafe {
|
||||
let dc = GetWindowDC(Some(hwnd));
|
||||
let mut bounds = RECT::default();
|
||||
if !dc.is_invalid() && GetWindowRect(hwnd, &mut bounds).is_ok() {
|
||||
let background = GetSysColor(COLOR_3DFACE);
|
||||
let foreground = GetSysColor(COLOR_WINDOWTEXT);
|
||||
let mut border = 0;
|
||||
for shift in [0, 8, 16] {
|
||||
let channel = (((background >> shift) & 255) * 82 + ((foreground >> shift) & 255) * 18) / 100;
|
||||
border |= channel << shift;
|
||||
}
|
||||
let brush = CreateSolidBrush(COLORREF(border));
|
||||
FrameRect(
|
||||
dc,
|
||||
&RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: bounds.right - bounds.left,
|
||||
bottom: bounds.bottom - bounds.top,
|
||||
},
|
||||
brush,
|
||||
);
|
||||
let _ = DeleteObject(brush.into());
|
||||
}
|
||||
ReleaseDC(Some(hwnd), dc);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
msg: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
id: usize,
|
||||
key: usize,
|
||||
) -> LRESULT {
|
||||
let state = STATES.with_borrow(|states| states.get(&key).cloned());
|
||||
// Paint the native toolbar and recovery surface outside the child webview.
|
||||
if msg == WM_ERASEBKGND {
|
||||
unsafe {
|
||||
let mut bounds = RECT::default();
|
||||
if GetClientRect(hwnd, &mut bounds).is_ok() {
|
||||
FillRect(HDC(wparam.0 as *mut _), &bounds, GetSysColorBrush(COLOR_WINDOW));
|
||||
}
|
||||
}
|
||||
return LRESULT(1);
|
||||
}
|
||||
if let Some(state) = &state {
|
||||
if msg == WM_COMMAND && (wparam.0 >> 16) == BN_CLICKED as usize {
|
||||
let event = match wparam.0 & 0xffff {
|
||||
RETRY => Some(AuthEvent::Retry),
|
||||
PROCEED => Some(AuthEvent::RequestTlsException),
|
||||
CANCEL => Some(AuthEvent::Close),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(event) = event {
|
||||
state.messenger.send_auth_event(event);
|
||||
return LRESULT(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
|
||||
if msg == WM_SIZE || msg == WM_DPICHANGED {
|
||||
if let Some(state) = &state {
|
||||
let _ = state.controls.layout(state);
|
||||
}
|
||||
}
|
||||
if msg == WM_NCDESTROY {
|
||||
unsafe {
|
||||
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
|
||||
}
|
||||
STATES.with_borrow_mut(|states| states.remove(&key));
|
||||
if let Some(state) = state {
|
||||
super::tls::clear_exceptions(&state.core);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
use super::super::tls::{TlsFailure, TlsFailureReason};
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
use webview2_com::{ClearServerCertificateErrorActionsCompletedHandler, ServerCertificateErrorDetectedEventHandler};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_YESNO, MessageBoxW};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Policy {
|
||||
pub ignore_errors: bool,
|
||||
approved: HashSet<(String, String)>,
|
||||
pending: Option<Failure>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Failure {
|
||||
identity: (String, String),
|
||||
failure: TlsFailure,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
fn reason(error: COREWEBVIEW2_WEB_ERROR_STATUS) -> TlsFailureReason {
|
||||
match error {
|
||||
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT => TlsFailureReason::HostnameMismatch,
|
||||
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED => TlsFailureReason::Expired,
|
||||
_ => TlsFailureReason::InvalidCertificate,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(state: &Rc<State>) -> windows::core::Result<()> {
|
||||
let weak = Rc::downgrade(state);
|
||||
let handler = ServerCertificateErrorDetectedEventHandler::create(Box::new(move |_, args| {
|
||||
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
|
||||
return Ok(());
|
||||
};
|
||||
unsafe {
|
||||
let uri = text(|p| args.RequestUri(p))?;
|
||||
let host = url::Url::parse(&uri)
|
||||
.ok()
|
||||
.and_then(|url| url.host_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
let pem = text(|p| args.ServerCertificate()?.ToPemEncoding(p))?;
|
||||
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
|
||||
args.ErrorStatus(&mut error)?;
|
||||
let identity = (host.clone(), pem);
|
||||
let mut policy = state.tls.borrow_mut();
|
||||
if policy.ignore_errors || policy.approved.contains(&identity) {
|
||||
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_ALWAYS_ALLOW)?;
|
||||
} else {
|
||||
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_CANCEL)?;
|
||||
let generation = state.document.borrow().1;
|
||||
let failure = TlsFailure {
|
||||
host,
|
||||
reason: reason(error),
|
||||
can_continue: error != COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_REVOKED,
|
||||
};
|
||||
state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure.clone())));
|
||||
policy.pending = Some(Failure {
|
||||
identity,
|
||||
failure,
|
||||
generation,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
let mut token = 0;
|
||||
unsafe {
|
||||
state
|
||||
.core
|
||||
.cast::<ICoreWebView2_14>()?
|
||||
.add_ServerCertificateErrorDetected(&handler, &mut token)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn confirm(state: &State) -> anyhow::Result<()> {
|
||||
let pending = state
|
||||
.tls
|
||||
.borrow()
|
||||
.pending
|
||||
.clone()
|
||||
.context("No certificate error to confirm")?;
|
||||
if !pending.failure.can_continue || pending.generation != state.messenger.generation() {
|
||||
bail!("This certificate exception is no longer available");
|
||||
}
|
||||
let answer = unsafe {
|
||||
MessageBoxW(
|
||||
Some(state.controls.parent),
|
||||
&HSTRING::from(pending.failure.confirmation_message()),
|
||||
&HSTRING::from(pending.failure.confirmation_title()),
|
||||
MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
|
||||
)
|
||||
};
|
||||
if answer == IDYES {
|
||||
let identity = pending.identity.clone();
|
||||
let generation = pending.generation;
|
||||
state.tls.borrow_mut().approved.insert(identity);
|
||||
state.messenger.send_auth_event(AuthEvent::TlsAccepted(generation));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// WebView2 caches approvals in the session. Do not leave them for another sign-in window.
|
||||
pub(super) fn clear_exceptions(core: &ICoreWebView2) {
|
||||
if let Ok(core) = core.cast::<ICoreWebView2_14>() {
|
||||
let _ = unsafe {
|
||||
core.ClearServerCertificateErrorActions(&ClearServerCertificateErrorActionsCompletedHandler::create(Box::new(
|
||||
|_| Ok(()),
|
||||
)))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn maps_certificate_failure_reasons() {
|
||||
assert_eq!(
|
||||
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT),
|
||||
TlsFailureReason::HostnameMismatch
|
||||
);
|
||||
assert_eq!(
|
||||
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED),
|
||||
TlsFailureReason::Expired
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,4 @@ which = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"]
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = { version = "0.55", optional = true }
|
||||
launcher = ["dep:open", "dep:webbrowser", "dep:which"]
|
||||
@@ -1,11 +1,8 @@
|
||||
#[cfg(all(feature = "launcher", windows))]
|
||||
#[path = "platform/windows.rs"]
|
||||
mod platform;
|
||||
#[cfg(all(feature = "launcher", target_os = "macos"))]
|
||||
#[path = "platform/macos.rs"]
|
||||
mod platform;
|
||||
|
||||
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
|
||||
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||
#[path = "platform/generic.rs"]
|
||||
mod platform;
|
||||
|
||||
@@ -41,7 +38,7 @@ impl<'a> Browser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
|
||||
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
|
||||
pub(crate) fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Browser::Auto => "auto",
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
//! Windows browsers are resolved through their registered App Paths.
|
||||
use crate::Browser;
|
||||
use anyhow::{Context, bail};
|
||||
use std::path::PathBuf;
|
||||
use winreg::{
|
||||
RegKey,
|
||||
enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
|
||||
};
|
||||
|
||||
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
|
||||
let executable = match browser {
|
||||
Browser::Auto | Browser::Default => return webbrowser::open(url).context("Could not open the browser"),
|
||||
Browser::Chrome => registered_browser("chrome.exe").context("Chrome is not installed")?,
|
||||
Browser::Edge => registered_browser("msedge.exe").context("Edge is not installed")?,
|
||||
Browser::Firefox => registered_browser("firefox.exe").context("Firefox is not installed")?,
|
||||
Browser::Safari => bail!("Safari is not available on Windows"),
|
||||
Browser::Other(program) => PathBuf::from(program),
|
||||
};
|
||||
std::process::Command::new(executable)
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.context("Could not open the configured browser")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn registered_browser(name: &str) -> Option<PathBuf> {
|
||||
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE].into_iter().find_map(|hive| {
|
||||
let key = RegKey::predef(hive)
|
||||
.open_subkey(format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{name}"))
|
||||
.ok()?;
|
||||
let path: String = key.get_value("").ok()?;
|
||||
let path = PathBuf::from(path.trim_matches('"'));
|
||||
path.is_file().then_some(path)
|
||||
})
|
||||
}
|
||||
+5
-10
@@ -5,16 +5,11 @@ fn main() {
|
||||
let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap();
|
||||
let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui");
|
||||
|
||||
let suffix = if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
".exe"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let gp_service_binary = workspace_dir.join(format!("target/debug/gpservice{suffix}"));
|
||||
let gp_client_binary = workspace_dir.join(format!("target/debug/gpclient{suffix}"));
|
||||
let gp_auth_binary = workspace_dir.join(format!("target/debug/gpauth{suffix}"));
|
||||
let gp_gui_helper_binary = workspace_dir.join(format!("target/debug/gpgui-helper{suffix}"));
|
||||
let gp_gui_binary = gpgui_dir.join(format!("target/debug/gpgui{suffix}"));
|
||||
let gp_service_binary = workspace_dir.join("target/debug/gpservice");
|
||||
let gp_client_binary = workspace_dir.join("target/debug/gpclient");
|
||||
let gp_auth_binary = workspace_dir.join("target/debug/gpauth");
|
||||
let gp_gui_helper_binary = workspace_dir.join("target/debug/gpgui-helper");
|
||||
let gp_gui_binary = gpgui_dir.join("target/debug/gpgui");
|
||||
|
||||
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
|
||||
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display());
|
||||
|
||||
@@ -89,7 +89,7 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
|
||||
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(format!("{binary_name}{}", std::env::consts::EXE_SUFFIX));
|
||||
let binary = bin_dir.join(binary_name);
|
||||
if is_file(&binary) {
|
||||
return Some(binary);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
|
||||
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
|
||||
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
|
||||
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
|
||||
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
pub mod binary_paths;
|
||||
pub mod constants;
|
||||
pub mod paths;
|
||||
@@ -1,32 +0,0 @@
|
||||
//! Machine-wide service state shared by the daemon and desktop clients.
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn service_lock_file() -> PathBuf {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
PathBuf::from("/var/run/gpservice.lock")
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
std::env::var_os("ProgramData")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
|
||||
.join("GP Connect")
|
||||
.join("gpservice.lock")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub const SERVICE_PIPE: &str = r"\\.\pipe\GPConnect.Service";
|
||||
|
||||
#[cfg(windows)]
|
||||
pub const SERVICE_NAME: &str = "GPConnect";
|
||||
|
||||
/// Installer-owned SYSTEM/Administrators-only state, including temporary keys.
|
||||
#[cfg(windows)]
|
||||
pub fn service_private_dir() -> PathBuf {
|
||||
service_lock_file()
|
||||
.parent()
|
||||
.expect("service state directory")
|
||||
.join("Private")
|
||||
}
|
||||
+7
-22
@@ -6,7 +6,9 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
common = { path = "../common" }
|
||||
directories = { workspace = true, optional = true }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
dns-lookup = { workspace = true, optional = true }
|
||||
@@ -14,10 +16,8 @@ log.workspace = true
|
||||
reqwest.workspace = true
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-pemfile = "2"
|
||||
rustls-platform-verifier = "0.7"
|
||||
p12-keystore = "0.4.1"
|
||||
pkcs12 = { version = "=0.2.0-pre.0", default-features = false }
|
||||
cms = { version = "=0.3.0-pre.1", default-features = false }
|
||||
sec1 = { version = "0.8.1", default-features = false, features = ["der"] }
|
||||
pem.workspace = true
|
||||
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
||||
x509-cert = { version = "0.3", default-features = false }
|
||||
@@ -34,6 +34,7 @@ thiserror.workspace = true
|
||||
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
|
||||
url.workspace = true
|
||||
regex.workspace = true
|
||||
uzers = { workspace = true, optional = true }
|
||||
serde_urlencoded.workspace = true
|
||||
md5.workspace = true
|
||||
sha2.workspace = true
|
||||
@@ -42,6 +43,7 @@ chrono.workspace = true
|
||||
humantime.workspace = true
|
||||
netdev = { workspace = true, optional = true }
|
||||
socket2 = { version = "0.6", features = ["all"], optional = true }
|
||||
os_info = { version = "3", default-features = false, optional = true }
|
||||
snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
getrandom = "0.4"
|
||||
@@ -62,15 +64,8 @@ oslog = { version = "0.2", default-features = false, optional = true }
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
directories = { workspace = true, optional = true }
|
||||
libloading = { version = "0.9", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
os_info = { version = "3", default-features = false, optional = true }
|
||||
|
||||
[target.'cfg(target_os="windows")'.dependencies]
|
||||
os_info = { version = "3", default-features = false }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
pkg-config = "0.3"
|
||||
@@ -83,18 +78,8 @@ tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[features]
|
||||
default = ["desktop"]
|
||||
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
|
||||
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
|
||||
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:os_info", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
|
||||
tauri = ["desktop", "dep:tauri", "dep:gtk"]
|
||||
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
|
||||
webview-auth = []
|
||||
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO"] }
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] }
|
||||
@@ -10,7 +10,6 @@ pub enum AnchorSource {
|
||||
UnixMac,
|
||||
UnixRandom,
|
||||
MacosIokit,
|
||||
WindowsSmbios,
|
||||
}
|
||||
|
||||
impl From<AnchorSource> for u8 {
|
||||
@@ -19,7 +18,6 @@ impl From<AnchorSource> for u8 {
|
||||
AnchorSource::UnixMac => 1,
|
||||
AnchorSource::UnixRandom => 2,
|
||||
AnchorSource::MacosIokit => 3,
|
||||
AnchorSource::WindowsSmbios => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +41,6 @@ impl TryFrom<u8> for AnchorSource {
|
||||
1 => Ok(Self::UnixMac),
|
||||
2 => Ok(Self::UnixRandom),
|
||||
3 => Ok(Self::MacosIokit),
|
||||
4 => Ok(Self::WindowsSmbios),
|
||||
value => Err(InvalidAnchorSource(value)),
|
||||
}
|
||||
}
|
||||
@@ -68,7 +65,6 @@ impl DeviceAnchor {
|
||||
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
||||
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
|
||||
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
|
||||
AnchorSource::WindowsSmbios => b"gp-device-anchor:v1:windows-smbios-uuid:".as_slice(),
|
||||
};
|
||||
let mut input = domain.to_vec();
|
||||
input.extend_from_slice(seed.as_ref());
|
||||
@@ -85,7 +81,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn preserves_existing_hardware_ids_for_all_sources() {
|
||||
let cases: [(AnchorSource, &[u8], &str); 4] = [
|
||||
let cases: [(AnchorSource, &[u8], &str); 3] = [
|
||||
(
|
||||
AnchorSource::UnixMac,
|
||||
&[0, 17, 34, 51, 68, 85],
|
||||
@@ -101,11 +97,6 @@ mod tests {
|
||||
b"12345678-1234-5678-9abc-def012345678",
|
||||
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
|
||||
),
|
||||
(
|
||||
AnchorSource::WindowsSmbios,
|
||||
b"12345678-1234-5678-9abc-def012345678",
|
||||
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
|
||||
),
|
||||
];
|
||||
for (source, seed, expected) in cases {
|
||||
let anchor = DeviceAnchor::derive(source, seed);
|
||||
@@ -133,17 +124,12 @@ mod tests {
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::WindowsSmbios).unwrap(), "4");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("4").unwrap(),
|
||||
AnchorSource::WindowsSmbios
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
||||
AnchorSource::UnixMac
|
||||
);
|
||||
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("5").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -22,23 +22,11 @@ pub enum ServerTlsErrorKind {
|
||||
}
|
||||
|
||||
impl ServerTlsError {
|
||||
pub(crate) fn from_request(
|
||||
server: &url::Url,
|
||||
error: &(dyn Error + 'static),
|
||||
has_client_identity: bool,
|
||||
) -> Option<anyhow::Error> {
|
||||
let kind = classify_with_identity(error, has_client_identity)?;
|
||||
let error = anyhow::Error::new(Self {
|
||||
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> {
|
||||
Some(Self {
|
||||
server: server.origin().ascii_serialization(),
|
||||
kind,
|
||||
});
|
||||
if has_client_identity && kind == ServerTlsErrorKind::ClientCertificateRequired {
|
||||
Some(error.context(
|
||||
"The VPN server could not use the configured client certificate. Check it with your VPN administrator",
|
||||
))
|
||||
} else {
|
||||
Some(error)
|
||||
}
|
||||
kind: classify(error)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,10 +60,6 @@ impl ServerTlsErrorKind {
|
||||
}
|
||||
|
||||
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
||||
classify_with_identity(error, false)
|
||||
}
|
||||
|
||||
fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bool) -> Option<ServerTlsErrorKind> {
|
||||
let mut source = Some(error);
|
||||
while let Some(error) = source {
|
||||
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
|
||||
@@ -87,14 +71,6 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
|
||||
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
|
||||
ServerTlsErrorKind::ClientCertificateRequired
|
||||
}
|
||||
rustls::Error::AlertReceived(
|
||||
rustls::AlertDescription::BadCertificate
|
||||
| rustls::AlertDescription::UnsupportedCertificate
|
||||
| rustls::AlertDescription::CertificateRevoked
|
||||
| rustls::AlertDescription::CertificateExpired
|
||||
| rustls::AlertDescription::CertificateUnknown
|
||||
| rustls::AlertDescription::UnknownCA,
|
||||
) if has_client_identity => ServerTlsErrorKind::ClientCertificateRequired,
|
||||
_ => ServerTlsErrorKind::Other,
|
||||
});
|
||||
}
|
||||
@@ -147,39 +123,6 @@ mod tests {
|
||||
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_identity_peer_errors_have_actionable_copy_without_becoming_server_trust_failures() {
|
||||
let server = url::Url::parse("https://vpn.example.com/private/login").unwrap();
|
||||
for alert in [
|
||||
rustls::AlertDescription::CertificateRequired,
|
||||
rustls::AlertDescription::BadCertificate,
|
||||
rustls::AlertDescription::UnknownCA,
|
||||
] {
|
||||
let error = rustls::Error::AlertReceived(alert);
|
||||
let configured = ServerTlsError::from_request(&server, &error, true).unwrap();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&configured),
|
||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
||||
);
|
||||
let message = configured.to_string();
|
||||
assert!(
|
||||
message.contains("configured client certificate") && message.contains("VPN administrator"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
!message.contains("password") && !message.contains("passphrase"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(!message.contains("/private/login"));
|
||||
}
|
||||
let trust_error = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer);
|
||||
let classified = ServerTlsError::from_request(&server, &trust_error, true).unwrap();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&classified),
|
||||
Some(ServerTlsErrorKind::Certificate)
|
||||
);
|
||||
}
|
||||
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
server_with_client_auth(tls, SslVerifyMode::NONE)
|
||||
}
|
||||
@@ -283,8 +226,8 @@ mod tests {
|
||||
.await
|
||||
.unwrap_err();
|
||||
worker.join().unwrap();
|
||||
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error, false).unwrap();
|
||||
assert_eq!(ServerTlsErrorKind::from_error(&tls), Some(ServerTlsErrorKind::Other));
|
||||
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap();
|
||||
assert_eq!(tls.kind, ServerTlsErrorKind::Other);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -371,38 +314,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
utils::request::ClientIdentity,
|
||||
};
|
||||
let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/client-identity");
|
||||
let identity = ClientIdentity::load(
|
||||
fixtures.join("rsa-critical-extension.pem").to_str().unwrap(),
|
||||
Some(fixtures.join("rsa-pkcs8.pem").to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()))
|
||||
.client_identity(Some(identity))
|
||||
.ignore_tls_errors(true)
|
||||
.build();
|
||||
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let error = prelogin(&address, ¶ms, PreloginOptions::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
worker.join().unwrap();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&error),
|
||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
||||
);
|
||||
assert!(error.to_string().contains("configured client certificate"), "{error:#}");
|
||||
assert!(!error.to_string().contains("passphrase"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
||||
use crate::{
|
||||
@@ -500,10 +411,10 @@ mod tests {
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(
|
||||
&ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error, false).unwrap()
|
||||
),
|
||||
Some(ServerTlsErrorKind::Certificate)
|
||||
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error)
|
||||
.unwrap()
|
||||
.kind,
|
||||
ServerTlsErrorKind::Certificate
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::{
|
||||
gp_params::GpParams,
|
||||
params::gateway_login::{self, GatewayLoginInput},
|
||||
session::GatewayAuthentication,
|
||||
utils::{normalize_server, parse_gp_response, redact::redact_uri, remove_url_scheme, xml::ElementExt},
|
||||
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
pub enum GatewayLogin {
|
||||
@@ -181,14 +181,14 @@ async fn receive_gateway_login(
|
||||
log_gateway_login_context(context, client_ip, gp_params);
|
||||
|
||||
let res = client
|
||||
.post(&login_url)
|
||||
.post(login_url)
|
||||
.form(&request_params.body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match crate::error::ServerTlsError::from_request(origin, &e, gp_params.has_client_identity()) {
|
||||
Some(tls) => tls,
|
||||
match crate::error::ServerTlsError::from_request(origin, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
@@ -200,30 +200,14 @@ async fn receive_gateway_login(
|
||||
.map(<[u8]>::to_vec);
|
||||
let endpoint = res.remote_addr();
|
||||
let url = res.url().clone();
|
||||
let http_version = res.version();
|
||||
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
// Redirect paths and query strings can contain authentication tokens. Log
|
||||
// only the redacted origin and whether the response is from the login path.
|
||||
warn!(
|
||||
"Gateway login response failed: status={}, reason={}, http={:?}, origin={}, port={:?}, redirected={}, login_endpoint={}, content_type={:?}, client_certificate={}, ignore_tls_errors={}",
|
||||
err.status,
|
||||
err.reason,
|
||||
http_version,
|
||||
redact_uri(&url.origin().ascii_serialization()),
|
||||
url.port_or_known_default(),
|
||||
url.as_str() != login_url,
|
||||
url.path() == "/ssl-vpn/login.esp",
|
||||
content_type,
|
||||
gp_params.has_client_identity(),
|
||||
gp_params.ignore_tls_errors(),
|
||||
);
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) {
|
||||
return tls;
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
|
||||
return anyhow::anyhow!(tls);
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return anyhow::anyhow!(crate::error::AuthenticationRejected);
|
||||
}
|
||||
warn!("Gateway login response failed: {}", err.reason);
|
||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||
})?;
|
||||
|
||||
@@ -445,85 +429,6 @@ mod tests {
|
||||
.build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_login_logs_http_context_without_credentials_or_redirect_tokens() {
|
||||
use std::cell::RefCell;
|
||||
|
||||
thread_local! {
|
||||
static MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
struct Logger;
|
||||
impl log::Log for Logger {
|
||||
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
let message = record.args().to_string();
|
||||
if message.starts_with("Gateway login response failed:") {
|
||||
MESSAGES.with_borrow_mut(|messages| messages.push(message));
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
log::set_logger(&Logger).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Warn);
|
||||
|
||||
for (status, reason, redirected) in [
|
||||
(403, None, false),
|
||||
(502, None, true),
|
||||
(401, Some("access denied"), false),
|
||||
] {
|
||||
let body = "<html>response-body-secret</html>";
|
||||
let mut responses = Vec::new();
|
||||
if redirected {
|
||||
responses.push(
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /path-secret?token=query-secret\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
);
|
||||
}
|
||||
let reason_header = reason
|
||||
.map(|reason| format!("x-private-pan-globalprotect: {reason}\r\n"))
|
||||
.unwrap_or_default();
|
||||
responses.push(format!(
|
||||
"HTTP/1.1 {status} Error\r\nContent-Type: text/html\r\nSet-Cookie: cookie-secret\r\n{reason_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
));
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(responses).await;
|
||||
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("username-secret", "password-secret").into();
|
||||
let error = client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
server.await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!("Gateway login error: {}", reason.unwrap_or("<none>"))
|
||||
);
|
||||
let messages = MESSAGES.with_borrow_mut(std::mem::take);
|
||||
assert_eq!(messages.len(), 1);
|
||||
let message = &messages[0];
|
||||
for expected in [
|
||||
format!("status={status}"),
|
||||
format!("reason={}", reason.unwrap_or("<none>")),
|
||||
format!("port={:?}", origin.port()),
|
||||
format!("redirected={redirected}"),
|
||||
format!("login_endpoint={}", !redirected),
|
||||
"http=HTTP/1.1".into(),
|
||||
"content_type=Some(\"text/html\")".into(),
|
||||
"client_certificate=false".into(),
|
||||
"ignore_tls_errors=false".into(),
|
||||
] {
|
||||
assert!(message.contains(&expected), "missing {expected}: {message}");
|
||||
}
|
||||
assert!(!message.contains("secret"), "sensitive data in diagnostic: {message}");
|
||||
assert!(!message.contains("127.0.0.1"), "unredacted origin: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_cancels_stalled_headers_and_body() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
@@ -6,7 +6,7 @@ use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
utils::request::ClientIdentity,
|
||||
utils::request::{ClientIdentity, create_identity},
|
||||
};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||
@@ -160,21 +160,21 @@ impl GpParams {
|
||||
self.prepared_identity.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn has_client_identity(&self) -> bool {
|
||||
self.prepared_identity.is_some() || self.certificate.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let builder = if let Some(identity) = &self.prepared_identity {
|
||||
identity.client_builder(self.ignore_tls_errors)?
|
||||
let mut builder = crate::utils::request::client_builder()
|
||||
.tls_info(true)
|
||||
.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...");
|
||||
ClientIdentity::load(cert, self.sslkey.as_deref(), self.key_password.as_deref())?
|
||||
.client_builder(self.ignore_tls_errors)?
|
||||
} else {
|
||||
crate::utils::request::client_builder().danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
};
|
||||
let builder = builder.tls_info(true).user_agent(self.user_agent());
|
||||
builder = builder.identity(create_identity(
|
||||
cert,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,3 @@ pub mod clap;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod script_tun;
|
||||
|
||||
#[cfg(all(feature = "desktop", windows))]
|
||||
pub mod windows;
|
||||
@@ -201,15 +201,15 @@ pub async fn retrieve_config(
|
||||
result = async {
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
||||
Some(tls) => tls,
|
||||
match ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow::anyhow!(tls));
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
|
||||
@@ -274,15 +274,15 @@ async fn retrieve_csc_config(
|
||||
|
||||
let res = client.post(&url).form(¶ms).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
||||
Some(tls) => tls,
|
||||
match ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow::anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
||||
|
||||
@@ -152,15 +152,15 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
||||
|
||||
let res = request.send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match crate::error::ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
||||
Some(error) => error,
|
||||
match crate::error::ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(error) => anyhow!(error),
|
||||
None => anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
|
||||
|
||||
@@ -236,7 +236,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
if self.browser.is_none() {
|
||||
{
|
||||
if self.hidpi {
|
||||
auth_cmd.arg("--hidpi");
|
||||
}
|
||||
@@ -409,42 +409,6 @@ mod tests {
|
||||
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn external_browser_receives_no_embedded_window_arguments() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.browser(Some("edge"))
|
||||
.clean(true)
|
||||
.hidpi(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--browser", "edge"]));
|
||||
for option in ["--clean", "--hidpi", "--window-title", "--window-theme"] {
|
||||
assert!(!args.iter().any(|arg| arg == option), "unexpected {option} in {args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn embedded_window_receives_auth_preferences() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.clean(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.iter().any(|arg| arg == "--clean"));
|
||||
assert!(
|
||||
args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--window-title", "GP Connect Login"])
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--window-theme", "dark"]));
|
||||
assert!(!args.iter().any(|arg| arg == "--browser"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_profile_sets_os_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux)
|
||||
|
||||
@@ -72,7 +72,6 @@ impl SwitchListener {
|
||||
self.directory.path().join("control")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub async fn ready(&self) -> anyhow::Result<()> {
|
||||
let (mut socket, _) = self.listener.accept().await?;
|
||||
anyhow::ensure!(
|
||||
|
||||
@@ -1,41 +1,20 @@
|
||||
#[cfg(unix)]
|
||||
mod command_runner;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_runner.rs"]
|
||||
mod command_runner;
|
||||
#[cfg(unix)]
|
||||
mod command_traits;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_traits.rs"]
|
||||
mod command_traits;
|
||||
#[cfg(unix)]
|
||||
mod desktop_child;
|
||||
#[cfg(unix)]
|
||||
mod desktop_session_env;
|
||||
#[cfg(unix)]
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod desktop_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod gui_launcher;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
pub mod gui_switch;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod nsh_runtime;
|
||||
#[cfg(unix)]
|
||||
pub mod users;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod collection;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/collection.rs"]
|
||||
pub mod collection;
|
||||
|
||||
pub mod rendering_recovery;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/user_process.rs"]
|
||||
pub mod user_process;
|
||||
@@ -49,17 +49,11 @@ impl RecoveryState {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
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))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
|
||||
status.code().is_some_and(|code| (code as u32) >= 0xC0000000)
|
||||
}
|
||||
|
||||
pub fn eligible(command: &Command) -> bool {
|
||||
eligible_with_inheritance(command, true)
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
//! Resolve system collectors from Windows' system directory, never the working directory.
|
||||
use super::command_runner::run_controlled;
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output},
|
||||
};
|
||||
|
||||
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> {
|
||||
let system = std::env::var_os("SystemRoot")?;
|
||||
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
match self.resolve(name) {
|
||||
Some(path) => self.run_path(&path, args),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.run_path(path, args)
|
||||
}
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let mut command = Command::new(path);
|
||||
command.args(args);
|
||||
match run_controlled(command, self.control, 256 * 1024) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
io::{self, Read, Write},
|
||||
os::windows::io::AsRawHandle,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
|
||||
|
||||
pub(crate) enum ChildInput<'a> {
|
||||
Null,
|
||||
Terminal,
|
||||
// Preserve the borrowed input type shared by callers without a Windows launcher.
|
||||
#[allow(dead_code)]
|
||||
Frame(&'a [u8]),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ObservedOutput {
|
||||
pub output: Output,
|
||||
}
|
||||
|
||||
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
|
||||
run_observed(
|
||||
command,
|
||||
control,
|
||||
Some(limit),
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
ChildInput::Null,
|
||||
)
|
||||
.map(|observed| observed.output)
|
||||
}
|
||||
|
||||
pub(crate) fn run_observed(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
observer: &mut dyn FnMut(&[u8]),
|
||||
stderr_sink: &mut dyn Write,
|
||||
stdin: ChildInput<'_>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
control.check()?;
|
||||
// Windows desktop processes must not open a console for each helper.
|
||||
use std::os::windows::process::CommandExt;
|
||||
if !matches!(stdin, ChildInput::Terminal) {
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
});
|
||||
command.stderr(Stdio::piped());
|
||||
command.stdin(match stdin {
|
||||
ChildInput::Terminal => Stdio::inherit(),
|
||||
ChildInput::Null => Stdio::null(),
|
||||
ChildInput::Frame(_) => Stdio::piped(),
|
||||
});
|
||||
let mut child = ControlledChild(command.spawn()?);
|
||||
let input = if let ChildInput::Frame(frame) = stdin {
|
||||
let mut pipe = child.0.stdin.take().expect("piped stdin");
|
||||
let frame = frame.to_vec();
|
||||
Some(thread::spawn(move || pipe.write_all(&frame)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut stdout = child.0.stdout.take();
|
||||
let mut stderr = child.0.stderr.take().expect("piped stderr");
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
loop {
|
||||
control.check()?;
|
||||
if let Some(pipe) = &mut stdout {
|
||||
let length = read_available(pipe, &mut buffer)?;
|
||||
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]);
|
||||
}
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
if let Some(status) = child.0.try_wait()? {
|
||||
// Drain the remaining buffered output after the process exits.
|
||||
if let Some(pipe) = &mut stdout {
|
||||
loop {
|
||||
let length = read_available(pipe, &mut buffer)?;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
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]);
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
}
|
||||
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
|
||||
result?;
|
||||
}
|
||||
return Ok(ObservedOutput {
|
||||
output: Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
|
||||
let mut available = 0;
|
||||
let success = unsafe {
|
||||
PeekNamedPipe(
|
||||
pipe.as_raw_handle(),
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
&mut available,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if success == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(109) {
|
||||
return Ok(0);
|
||||
} // ERROR_BROKEN_PIPE
|
||||
return Err(error);
|
||||
}
|
||||
let length = buffer.len().min(available as usize);
|
||||
if length == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
pipe.read(&mut buffer[..length])
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn captures_output_and_rejects_excess_output() {
|
||||
let mut command = Command::new("cmd.exe");
|
||||
command.args(["/D", "/C", "echo hello"]);
|
||||
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
|
||||
assert!(result.status.success());
|
||||
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
|
||||
let mut command = Command::new("cmd.exe");
|
||||
command.args(["/D", "/C", "echo too much"]);
|
||||
assert_eq!(
|
||||
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn cancels_a_running_helper() {
|
||||
let start = std::time::Instant::now();
|
||||
let mut command = Command::new("powershell.exe");
|
||||
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(150) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
run_controlled(command, &control, 1024).unwrap_err().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
assert!(start.elapsed() < Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Windows authentication runs in the interactive user's GUI process.
|
||||
pub trait CommandExt {
|
||||
fn into_non_root(self) -> anyhow::Result<Command>;
|
||||
}
|
||||
|
||||
impl CommandExt for Command {
|
||||
fn into_non_root(self) -> anyhow::Result<Command> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
//! Launch a native worker with the admitted user's primary token and environment.
|
||||
use std::{
|
||||
ffi::{OsStr, c_void},
|
||||
io,
|
||||
os::windows::{
|
||||
ffi::OsStrExt,
|
||||
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::Path,
|
||||
ptr,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
|
||||
Security::{ImpersonateLoggedOnUser, RevertToSelf},
|
||||
System::{
|
||||
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
|
||||
JobObjects::*,
|
||||
Threading::*,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct UserProcess {
|
||||
process: OwnedHandle,
|
||||
job: Option<OwnedHandle>,
|
||||
pid: u32,
|
||||
}
|
||||
struct Environment(*mut c_void);
|
||||
impl Drop for Environment {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
DestroyEnvironmentBlock(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, message)
|
||||
}
|
||||
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
|
||||
let value: Vec<_> = value.encode_wide().collect();
|
||||
if value.contains(&0) {
|
||||
return Err(invalid("Windows process strings cannot contain NUL"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
fn quote(argument: &[u16], output: &mut Vec<u16>) {
|
||||
output.push(b'"' as u16);
|
||||
let mut backslashes = 0;
|
||||
for &character in argument {
|
||||
if character == b'\\' as u16 {
|
||||
backslashes += 1;
|
||||
continue;
|
||||
}
|
||||
let count = if character == b'"' as u16 {
|
||||
backslashes * 2 + 1
|
||||
} else {
|
||||
backslashes
|
||||
};
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, count));
|
||||
output.push(character);
|
||||
backslashes = 0;
|
||||
}
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
|
||||
output.push(b'"' as u16);
|
||||
}
|
||||
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
|
||||
let mut output = Vec::new();
|
||||
quote(program, &mut output);
|
||||
for argument in arguments {
|
||||
output.push(b' ' as u16);
|
||||
quote(&wide(OsStr::new(argument))?, &mut output);
|
||||
}
|
||||
output.push(0);
|
||||
if output.len() > 32767 {
|
||||
return Err(invalid("Windows worker command line is too long"));
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
fn key(entry: &[u16]) -> &[u16] {
|
||||
let end = entry
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
|
||||
.map(|(index, _)| index)
|
||||
.unwrap_or(entry.len());
|
||||
&entry[..end]
|
||||
}
|
||||
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
|
||||
// Environment names follow Windows' ordinal, case-insensitive ordering.
|
||||
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
|
||||
.cmp(&CSTR_EQUAL)
|
||||
}
|
||||
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
|
||||
let mut pointer = ptr::null_mut();
|
||||
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let environment = Environment(pointer);
|
||||
let mut entries = Vec::new();
|
||||
unsafe {
|
||||
let mut current = environment.0.cast::<u16>();
|
||||
while *current != 0 {
|
||||
let mut length = 0;
|
||||
while *current.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
entries.push(std::slice::from_raw_parts(current, length).to_vec());
|
||||
current = current.add(length + 1);
|
||||
}
|
||||
}
|
||||
for (name, value) in variables {
|
||||
if name.is_empty() || name.contains('=') {
|
||||
return Err(invalid("Invalid worker environment name"));
|
||||
}
|
||||
let name = wide(OsStr::new(name))?;
|
||||
let value = wide(OsStr::new(value))?;
|
||||
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
|
||||
let mut entry = name;
|
||||
entry.push(b'=' as u16);
|
||||
entry.extend(value);
|
||||
entries.push(entry);
|
||||
}
|
||||
entries.sort_by(|left, right| compare(key(left), key(right)));
|
||||
let mut block = Vec::new();
|
||||
for entry in entries {
|
||||
block.extend(entry);
|
||||
block.push(0);
|
||||
}
|
||||
if block.is_empty() {
|
||||
block.push(0);
|
||||
}
|
||||
block.push(0);
|
||||
Ok(block)
|
||||
}
|
||||
impl UserProcess {
|
||||
/// No service handles or service environment are inherited. The user token
|
||||
/// determines the Windows session, including an existing interactive desktop.
|
||||
pub fn launch(
|
||||
token: BorrowedHandle<'_>,
|
||||
program: &Path,
|
||||
arguments: &[String],
|
||||
variables: &[(&str, &str)],
|
||||
) -> io::Result<Self> {
|
||||
if !program.is_absolute() {
|
||||
return Err(invalid("Windows worker executable must be absolute"));
|
||||
}
|
||||
let mut executable = wide(program.as_os_str())?;
|
||||
let mut command = command_line(&executable, arguments)?;
|
||||
executable.push(0);
|
||||
let mut environment = user_environment(token, variables)?;
|
||||
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
|
||||
let mut directory = wide(directory.as_os_str())?;
|
||||
directory.push(0);
|
||||
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
|
||||
if job.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let job = unsafe { OwnedHandle::from_raw_handle(job) };
|
||||
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
||||
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
||||
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
|
||||
std::mem::size_of_val(&limits) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
|
||||
let startup = STARTUPINFOW {
|
||||
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
|
||||
lpDesktop: desktop.as_mut_ptr(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut information = PROCESS_INFORMATION::default();
|
||||
// Read/execute the requested image as its user, as Unix exec-after-setuid
|
||||
// does. The service's filesystem access must not authorize a private image.
|
||||
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
struct Revert;
|
||||
impl Drop for Revert {
|
||||
fn drop(&mut self) {
|
||||
if unsafe { RevertToSelf() } == 0 {
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
let revert = Revert;
|
||||
let created = unsafe {
|
||||
CreateProcessAsUserW(
|
||||
token.as_raw_handle(),
|
||||
executable.as_ptr(),
|
||||
command.as_mut_ptr(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
0,
|
||||
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
|
||||
environment.as_mut_ptr().cast(),
|
||||
directory.as_ptr(),
|
||||
&startup,
|
||||
&mut information,
|
||||
)
|
||||
};
|
||||
let error = (created == 0).then(io::Error::last_os_error);
|
||||
drop(revert);
|
||||
if let Some(error) = error {
|
||||
return Err(error);
|
||||
}
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
|
||||
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
|
||||
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
// The suspended child is not owned by the job on this failure path.
|
||||
unsafe {
|
||||
TerminateProcess(process.as_raw_handle(), 1);
|
||||
WaitForSingleObject(process.as_raw_handle(), 5000);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let child = Self {
|
||||
process,
|
||||
job: Some(job),
|
||||
pid: information.dwProcessId,
|
||||
};
|
||||
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
pub fn id(&self) -> u32 {
|
||||
self.pid
|
||||
}
|
||||
pub fn has_exited(&self) -> io::Result<bool> {
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
|
||||
WAIT_OBJECT_0 => Ok(true),
|
||||
WAIT_TIMEOUT => Ok(false),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
pub fn stop(&mut self) -> io::Result<()> {
|
||||
if self.job.take().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
|
||||
WAIT_OBJECT_0 => Ok(()),
|
||||
WAIT_TIMEOUT => Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Windows worker did not terminate",
|
||||
)),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for UserProcess {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = self.stop() {
|
||||
log::warn!("Could not stop Windows worker: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
|
||||
#[test]
|
||||
fn command_line_round_trips_through_windows_parser() {
|
||||
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
|
||||
let arguments = [
|
||||
"proxy-worker",
|
||||
"",
|
||||
"space value",
|
||||
"quoted\"value",
|
||||
"two\\\\\"quotes",
|
||||
"trailing\\",
|
||||
"雪",
|
||||
"&|<>",
|
||||
]
|
||||
.map(String::from);
|
||||
let command = command_line(&program, &arguments).unwrap();
|
||||
let mut count = 0;
|
||||
unsafe {
|
||||
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
|
||||
assert!(!parsed.is_null());
|
||||
let result = std::slice::from_raw_parts(parsed, count as usize)
|
||||
.iter()
|
||||
.map(|&value| {
|
||||
let mut length = 0;
|
||||
while *value.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
LocalFree(parsed.cast());
|
||||
assert_eq!(result[0], String::from_utf16_lossy(&program));
|
||||
assert_eq!(result[1..], arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,28 +187,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn credential_round_trips_a_validated_device_anchor() {
|
||||
use crate::device_anchor::AnchorSource;
|
||||
|
||||
for (source, wire_source) in [
|
||||
(AnchorSource::UnixMac, 1),
|
||||
(AnchorSource::UnixRandom, 2),
|
||||
(AnchorSource::MacosIokit, 3),
|
||||
(AnchorSource::WindowsSmbios, 4),
|
||||
] {
|
||||
let anchor = DeviceAnchor {
|
||||
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
|
||||
source,
|
||||
};
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
|
||||
.unwrap()
|
||||
.with_device_anchor(anchor.clone())
|
||||
.unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
assert_eq!(payload["device_anchor"]["source"], wire_source);
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
assert_eq!(decoded.device_anchor(), Some(&anchor));
|
||||
}
|
||||
let anchor = DeviceAnchor {
|
||||
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
|
||||
source: crate::device_anchor::AnchorSource::UnixMac,
|
||||
};
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
|
||||
.unwrap()
|
||||
.with_device_anchor(anchor.clone())
|
||||
.unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
assert_eq!(payload["device_anchor"]["source"], 1);
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
assert_eq!(decoded.device_anchor(), Some(&anchor));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -218,7 +209,7 @@ mod tests {
|
||||
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
|
||||
|
||||
for source in [0, u8::MAX] {
|
||||
for source in [0, 4] {
|
||||
payload["device_anchor"] = serde_json::json!({
|
||||
"hardware_id": hardware_id,
|
||||
"source": source
|
||||
|
||||
@@ -11,8 +11,6 @@ pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult}
|
||||
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
|
||||
|
||||
pub const MAX_CREDENTIAL_FRAME: usize = 512;
|
||||
/// First request read before a Windows service captures its pipe client's token.
|
||||
pub const WINDOWS_ADMISSION_REQUEST: [u8; 4] = *b"GPC1";
|
||||
pub const MAX_PRELUDE: usize = 256;
|
||||
pub const MAX_PRODUCT_VERSION: usize = 64;
|
||||
pub const HIP_PROTOCOL_VERSION: u16 = 1;
|
||||
|
||||
@@ -29,11 +29,6 @@ use linux as platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos as platform;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
use windows as platform;
|
||||
|
||||
mod binding;
|
||||
use super::detection;
|
||||
pub mod native;
|
||||
@@ -480,7 +475,6 @@ fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
let output = CollectorCommands::new(control)
|
||||
.run(name, args)?
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
//! Windows network identity from IP Helper and adapter DNS configuration.
|
||||
use super::*;
|
||||
use std::os::windows::io::AsRawSocket;
|
||||
use windows_sys::Win32::{
|
||||
NetworkManagement::IpHelper::{
|
||||
DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1, FreeInterfaceDnsSettings, FreeMibTable,
|
||||
GetInterfaceDnsSettings, GetIpForwardTable2,
|
||||
},
|
||||
Networking::WinSock::{
|
||||
AF_INET, AF_INET6, AF_UNSPEC, IP_UNICAST_IF, IPPROTO_IP, IPPROTO_IPV6, IPV6_UNICAST_IF, SOCKADDR_INET,
|
||||
SOCKET_ERROR, WSAGetLastError, setsockopt,
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) fn scope_resolver_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
interface: &Interface,
|
||||
endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(interface.index != 0, "Resolver interface index is missing");
|
||||
// IP_UNICAST_IF uses network byte order; IPV6_UNICAST_IF uses host byte order.
|
||||
let (level, option, index) = if endpoint.is_ipv4() {
|
||||
(IPPROTO_IP, IP_UNICAST_IF, interface.index.to_be())
|
||||
} else {
|
||||
(IPPROTO_IPV6, IPV6_UNICAST_IF, interface.index)
|
||||
};
|
||||
let result = unsafe {
|
||||
setsockopt(
|
||||
socket.as_raw_socket() as usize,
|
||||
level,
|
||||
option,
|
||||
(&index as *const u32).cast(),
|
||||
std::mem::size_of::<u32>() as i32,
|
||||
)
|
||||
};
|
||||
if result == SOCKET_ERROR {
|
||||
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
|
||||
control.check()?;
|
||||
let mut table = std::ptr::null_mut();
|
||||
let status = unsafe { GetIpForwardTable2(AF_UNSPEC, &mut table) };
|
||||
if status != 0 {
|
||||
return Err(io::Error::from_raw_os_error(status as i32).into());
|
||||
}
|
||||
let interfaces = netdev::get_interfaces();
|
||||
let result = unsafe {
|
||||
let rows = std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize);
|
||||
rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let destination = address(&row.DestinationPrefix.Prefix)?;
|
||||
let gateway = address(&row.NextHop)?;
|
||||
let interface = interfaces
|
||||
.iter()
|
||||
.find(|interface| interface.index == row.InterfaceIndex)?;
|
||||
Some(RouteContext {
|
||||
destination: format!("{destination}/{}", row.DestinationPrefix.PrefixLength),
|
||||
gateway: gateway.to_string(),
|
||||
interface: interface.name.clone(),
|
||||
table: "main".into(),
|
||||
metric: row.Metric.to_string(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
unsafe {
|
||||
FreeMibTable(table.cast());
|
||||
}
|
||||
control.check()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
unsafe fn address(address: &SOCKADDR_INET) -> Option<IpAddr> {
|
||||
unsafe {
|
||||
match address.si_family {
|
||||
AF_INET => Some(std::net::Ipv4Addr::from(address.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()),
|
||||
AF_INET6 => Some(std::net::Ipv6Addr::from(address.Ipv6.sin6_addr.u.Byte).into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
control.check()?;
|
||||
let mut resolvers = netdev::get_interfaces()
|
||||
.into_iter()
|
||||
.filter(|interface| !interface.dns_servers.is_empty())
|
||||
.map(|interface| {
|
||||
Ok(ResolverContext {
|
||||
interface: Some(interface.name.clone()),
|
||||
servers: interface.dns_servers.iter().map(ToString::to_string).collect(),
|
||||
domains: resolver_domains(&interface.name)?,
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
resolvers.sort();
|
||||
control.check()?;
|
||||
Ok(resolvers)
|
||||
}
|
||||
|
||||
fn resolver_domains(interface: &str) -> anyhow::Result<Vec<String>> {
|
||||
let id = uuid::Uuid::parse_str(interface.trim_matches(['{', '}']))?;
|
||||
let (data1, data2, data3, data4) = id.as_fields();
|
||||
let guid = windows_sys::core::GUID {
|
||||
data1,
|
||||
data2,
|
||||
data3,
|
||||
data4: *data4,
|
||||
};
|
||||
let mut settings = DNS_INTERFACE_SETTINGS {
|
||||
Version: DNS_INTERFACE_SETTINGS_VERSION1,
|
||||
..Default::default()
|
||||
};
|
||||
let status = unsafe { GetInterfaceDnsSettings(guid, &mut settings) };
|
||||
if status != 0 {
|
||||
return Err(io::Error::from_raw_os_error(status as i32).into());
|
||||
}
|
||||
let mut domains = Vec::new();
|
||||
for pointer in [settings.Domain, settings.SearchList] {
|
||||
if pointer.is_null() {
|
||||
continue;
|
||||
}
|
||||
let text = unsafe {
|
||||
let mut length = 0;
|
||||
while *pointer.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
|
||||
};
|
||||
for domain in text
|
||||
.split(|ch: char| ch == ',' || ch.is_whitespace())
|
||||
.filter(|domain| !domain.is_empty())
|
||||
{
|
||||
let domain = domain.to_ascii_lowercase();
|
||||
if !domains.contains(&domain) {
|
||||
domains.push(domain);
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
FreeInterfaceDnsSettings(&mut settings);
|
||||
}
|
||||
Ok(domains)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) ->
|
||||
Ok(builder.interface(binding.interface()))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))]
|
||||
#[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!(
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
//! Client identity capabilities, separate from peer certificate policy.
|
||||
use pkcs8::{
|
||||
ObjectIdentifier, PrivateKeyInfoRef,
|
||||
der::{
|
||||
Decode, Reader, Tag, TagNumber, Tagged,
|
||||
asn1::{AnyRef, BitStringRef, ContextSpecific, OctetStringRef},
|
||||
},
|
||||
};
|
||||
use rustls::pki_types::PrivateKeyDer;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "native_key.rs"]
|
||||
mod implementation;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "portable_key.rs"]
|
||||
mod implementation;
|
||||
|
||||
pub(in crate::utils) use implementation::ClientKey;
|
||||
|
||||
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
|
||||
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
|
||||
const EC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
|
||||
const ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
|
||||
const ED448: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.113");
|
||||
const P521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
|
||||
const DSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10040.4.1");
|
||||
|
||||
fn validate_algorithm(oid: ObjectIdentifier) -> Result<(), RequestIdentityError> {
|
||||
match oid {
|
||||
RSA | EC | ED25519 => Ok(()),
|
||||
RSA_PSS => Err(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS")),
|
||||
ED448 => Err(RequestIdentityError::UnsupportedKeyAlgorithm("Ed448")),
|
||||
DSA => Err(RequestIdentityError::UnsupportedKeyAlgorithm("DSA")),
|
||||
_ => Err(RequestIdentityError::UnsupportedKeyAlgorithm(
|
||||
"an unknown key algorithm",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_ec_parameters(parameters: Option<AnyRef<'_>>) -> Result<(), RequestIdentityError> {
|
||||
if let Some(parameters) = parameters {
|
||||
if parameters.tag() == Tag::ObjectIdentifier {
|
||||
let curve = parameters
|
||||
.decode_as::<ObjectIdentifier>()
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
if curve == P521 {
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm("P-521"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(
|
||||
"EC with explicit parameters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_ec_point(point: &[u8]) -> Result<(), RequestIdentityError> {
|
||||
if matches!(point.first(), Some(2 | 3)) {
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(
|
||||
"EC with compressed public keys",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_sec1(bytes: &[u8]) -> anyhow::Result<()> {
|
||||
let (parameters, point) = AnyRef::from_der(bytes)
|
||||
.and_then(|sequence| {
|
||||
sequence.sequence(|reader| {
|
||||
let version: u8 = reader.decode()?;
|
||||
if version != 1 {
|
||||
return Err(reader.error(Tag::Integer.value_error()));
|
||||
}
|
||||
let _: &OctetStringRef = reader.decode()?;
|
||||
let parameters = ContextSpecific::<AnyRef<'_>>::decode_explicit(reader, TagNumber(0))?.map(|field| field.value);
|
||||
let point =
|
||||
ContextSpecific::<BitStringRef<'_>>::decode_explicit(reader, TagNumber(1))?.map(|field| field.value);
|
||||
Ok((parameters, point))
|
||||
})
|
||||
})
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
validate_ec_parameters(parameters)?;
|
||||
if let Some(point) = point {
|
||||
validate_ec_point(point.as_bytes().ok_or(RequestIdentityError::InvalidKey)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_private_key(key: &PrivateKeyDer<'_>) -> anyhow::Result<()> {
|
||||
match key {
|
||||
PrivateKeyDer::Pkcs8(key) => {
|
||||
let info = PrivateKeyInfoRef::from_der(key.secret_pkcs8_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
validate_algorithm(info.algorithm.oid)?;
|
||||
if info.algorithm.oid == EC {
|
||||
validate_ec_parameters(info.algorithm.parameters)?;
|
||||
validate_sec1(info.private_key.as_bytes())?;
|
||||
}
|
||||
}
|
||||
PrivateKeyDer::Sec1(key) => validate_sec1(key.secret_sec1_der())?,
|
||||
PrivateKeyDer::Pkcs1(_) => {}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn validate_certificate(bytes: &[u8]) -> anyhow::Result<()> {
|
||||
let certificate = x509_cert::Certificate::from_der(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let public_key = certificate.tbs_certificate().subject_public_key_info();
|
||||
validate_algorithm(public_key.algorithm.oid)?;
|
||||
if public_key.algorithm.oid == EC {
|
||||
validate_ec_parameters(public_key.algorithm.parameters.as_ref().map(|value| value.into()))?;
|
||||
validate_ec_point(
|
||||
public_key
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -44,272 +44,3 @@ void gp_key_free(unsigned char *data, size_t length) {
|
||||
gnutls_free(data);
|
||||
}
|
||||
}
|
||||
|
||||
#include <gnutls/abstract.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Check only the signature, not whether this local certificate is trusted,
|
||||
* current, or has extensions understood by the client. */
|
||||
int gp_certificate_verify_signature(
|
||||
const unsigned char *certificate, size_t certificate_length,
|
||||
const unsigned char *issuer_key, size_t issuer_key_length,
|
||||
const unsigned char *message, size_t message_length,
|
||||
const unsigned char *signature, size_t signature_length) {
|
||||
gnutls_x509_crt_t child = NULL;
|
||||
gnutls_pubkey_t public_key = NULL;
|
||||
int result, algorithm;
|
||||
if (certificate_length > UINT_MAX || issuer_key_length > UINT_MAX ||
|
||||
message_length > UINT_MAX || signature_length > UINT_MAX) return -1;
|
||||
result = gnutls_global_init();
|
||||
if (result < 0) return -1;
|
||||
gnutls_datum_t child_data = {(unsigned char *)certificate, (unsigned int)certificate_length};
|
||||
gnutls_datum_t key_data = {(unsigned char *)issuer_key, (unsigned int)issuer_key_length};
|
||||
gnutls_datum_t data = {(unsigned char *)message, (unsigned int)message_length};
|
||||
gnutls_datum_t sig = {(unsigned char *)signature, (unsigned int)signature_length};
|
||||
result = gnutls_x509_crt_init(&child);
|
||||
if (result >= 0) result = gnutls_x509_crt_import(child, &child_data, GNUTLS_X509_FMT_DER);
|
||||
if (result >= 0) result = gnutls_pubkey_init(&public_key);
|
||||
if (result >= 0) result = gnutls_pubkey_import(public_key, &key_data, GNUTLS_X509_FMT_DER);
|
||||
if (result >= 0) {
|
||||
algorithm = gnutls_x509_crt_get_signature_algorithm(child);
|
||||
if (algorithm < 0) result = algorithm;
|
||||
else result = gnutls_pubkey_verify_data2(public_key, algorithm,
|
||||
GNUTLS_VERIFY_ALLOW_BROKEN | GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1, &data, &sig) >= 0;
|
||||
}
|
||||
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
|
||||
if (child != NULL) gnutls_x509_crt_deinit(child);
|
||||
gnutls_global_deinit();
|
||||
return result < 0 ? -1 : result;
|
||||
}
|
||||
|
||||
/* Stable private kinds, independent of the native enum values. */
|
||||
struct gp_client_key {
|
||||
gnutls_privkey_t signer;
|
||||
gnutls_pubkey_t public_key;
|
||||
};
|
||||
|
||||
void gp_client_key_delete(struct gp_client_key *key) {
|
||||
if (key == NULL) return;
|
||||
if (key->public_key != NULL) gnutls_pubkey_deinit(key->public_key);
|
||||
if (key->signer != NULL) gnutls_privkey_deinit(key->signer);
|
||||
free(key);
|
||||
gnutls_global_deinit();
|
||||
}
|
||||
|
||||
int gp_client_key_new(const unsigned char *data, size_t length, int *kind,
|
||||
struct gp_client_key **output) {
|
||||
gnutls_x509_privkey_t input = NULL;
|
||||
struct gp_client_key *key = NULL;
|
||||
int result, algorithm;
|
||||
*output = NULL;
|
||||
*kind = 9;
|
||||
if (length > UINT_MAX || gnutls_global_init() < 0) return 1;
|
||||
key = calloc(1, sizeof(*key));
|
||||
if (key == NULL) { gnutls_global_deinit(); return 1; }
|
||||
result = gnutls_x509_privkey_init(&input);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
|
||||
result = gnutls_x509_privkey_import2(input, &bytes, GNUTLS_X509_FMT_DER, NULL, 0);
|
||||
}
|
||||
if (result < 0) goto invalid;
|
||||
algorithm = gnutls_x509_privkey_get_pk_algorithm(input);
|
||||
if (algorithm == GNUTLS_PK_RSA_PSS) { *kind = 5; goto unsupported; }
|
||||
if (algorithm == GNUTLS_PK_DSA) { *kind = 7; goto unsupported; }
|
||||
if (algorithm == GNUTLS_PK_EDDSA_ED448) { *kind = 8; goto unsupported; }
|
||||
result = gnutls_privkey_init(&key->signer);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_privkey_import_x509(key->signer, input, GNUTLS_PRIVKEY_IMPORT_COPY);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_pubkey_init(&key->public_key);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_pubkey_import_privkey(key->public_key, key->signer, 0, 0);
|
||||
if (result < 0) goto invalid;
|
||||
if (algorithm == GNUTLS_PK_RSA) *kind = 0;
|
||||
else if (algorithm == GNUTLS_PK_EDDSA_ED25519) *kind = 4;
|
||||
else if (algorithm == GNUTLS_PK_ECDSA) {
|
||||
gnutls_ecc_curve_t curve;
|
||||
gnutls_datum_t x = {NULL, 0}, y = {NULL, 0};
|
||||
result = gnutls_pubkey_export_ecc_raw(key->public_key, &curve, &x, &y);
|
||||
gnutls_free(x.data);
|
||||
gnutls_free(y.data);
|
||||
if (result < 0) goto invalid;
|
||||
if (curve == GNUTLS_ECC_CURVE_SECP256R1) *kind = 1;
|
||||
else if (curve == GNUTLS_ECC_CURVE_SECP384R1) *kind = 2;
|
||||
else if (curve == GNUTLS_ECC_CURVE_SECP521R1) { *kind = 3; goto unsupported; }
|
||||
else { *kind = 6; goto unsupported; }
|
||||
} else goto unsupported;
|
||||
gnutls_x509_privkey_deinit(input);
|
||||
*output = key;
|
||||
return 0;
|
||||
unsupported:
|
||||
if (input != NULL) gnutls_x509_privkey_deinit(input);
|
||||
gp_client_key_delete(key);
|
||||
return 2;
|
||||
invalid:
|
||||
if (input != NULL) gnutls_x509_privkey_deinit(input);
|
||||
gp_client_key_delete(key);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int gp_client_key_public(struct gp_client_key *key, unsigned char **output, size_t *length) {
|
||||
gnutls_datum_t bytes = {NULL, 0};
|
||||
int result = gnutls_pubkey_export2(key->public_key, GNUTLS_X509_FMT_DER, &bytes);
|
||||
*output = bytes.data;
|
||||
*length = bytes.size;
|
||||
return result;
|
||||
}
|
||||
|
||||
int gp_client_key_matches(struct gp_client_key *key, const unsigned char *data, size_t length) {
|
||||
gnutls_x509_crt_t certificate = NULL;
|
||||
gnutls_pubkey_t public_key = NULL;
|
||||
unsigned char key_id[32], cert_id[32];
|
||||
size_t key_id_length = sizeof(key_id), cert_id_length = sizeof(cert_id);
|
||||
int result;
|
||||
if (length > UINT_MAX) return -1;
|
||||
result = gnutls_x509_crt_init(&certificate);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
|
||||
result = gnutls_x509_crt_import(certificate, &bytes, GNUTLS_X509_FMT_DER);
|
||||
}
|
||||
if (result >= 0) result = gnutls_pubkey_init(&public_key);
|
||||
if (result >= 0) result = gnutls_pubkey_import_x509(public_key, certificate, 0);
|
||||
if (result >= 0) result = gnutls_pubkey_get_key_id(key->public_key, GNUTLS_KEYID_USE_SHA256, key_id, &key_id_length);
|
||||
if (result >= 0) result = gnutls_pubkey_get_key_id(public_key, GNUTLS_KEYID_USE_SHA256, cert_id, &cert_id_length);
|
||||
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
|
||||
if (certificate != NULL) gnutls_x509_crt_deinit(certificate);
|
||||
if (result < 0) return result;
|
||||
return key_id_length == cert_id_length && !memcmp(key_id, cert_id, key_id_length);
|
||||
}
|
||||
|
||||
int gp_client_key_sign(struct gp_client_key *key, unsigned short scheme,
|
||||
const unsigned char *message, size_t length,
|
||||
unsigned char **output, size_t *output_length) {
|
||||
gnutls_sign_algorithm_t algorithm;
|
||||
unsigned int flags = 0;
|
||||
*output = NULL;
|
||||
*output_length = 0;
|
||||
if (length > UINT_MAX) return -1;
|
||||
switch (scheme) {
|
||||
case 0x0804: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA256; break;
|
||||
case 0x0805: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA384; break;
|
||||
case 0x0806: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA512; break;
|
||||
case 0x0401: algorithm = GNUTLS_SIGN_RSA_SHA256; break;
|
||||
case 0x0501: algorithm = GNUTLS_SIGN_RSA_SHA384; break;
|
||||
case 0x0601: algorithm = GNUTLS_SIGN_RSA_SHA512; break;
|
||||
case 0x0403: algorithm = GNUTLS_SIGN_ECDSA_SECP256R1_SHA256; break;
|
||||
case 0x0503: algorithm = GNUTLS_SIGN_ECDSA_SECP384R1_SHA384; break;
|
||||
case 0x0807: algorithm = GNUTLS_SIGN_EDDSA_ED25519; break;
|
||||
default: return -1;
|
||||
}
|
||||
if (scheme >= 0x0804 && scheme <= 0x0806)
|
||||
flags = GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH;
|
||||
gnutls_datum_t bytes = {(unsigned char *)message, (unsigned int)length};
|
||||
gnutls_datum_t signature = {NULL, 0};
|
||||
int result = gnutls_privkey_sign_data2(key->signer, algorithm, flags, &bytes, &signature);
|
||||
*output = signature.data;
|
||||
*output_length = signature.size;
|
||||
return result;
|
||||
}
|
||||
|
||||
#include <gnutls/pkcs12.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Invoked only after Rust has identified the supported RC4 archive scheme.
|
||||
* Integrity and identity-count checks precede the native leaf selection. */
|
||||
int gp_pkcs12_identity(const unsigned char *input, size_t length, const char *password,
|
||||
unsigned char **certificate, size_t *certificate_length,
|
||||
unsigned char **private_key, size_t *private_key_length) {
|
||||
gnutls_pkcs12_t archive = NULL;
|
||||
gnutls_x509_privkey_t key = NULL;
|
||||
gnutls_x509_crt_t *chain = NULL, *extra = NULL;
|
||||
unsigned int chain_length = 0, extra_length = 0;
|
||||
gnutls_datum_t exported_key = {NULL, 0};
|
||||
unsigned int key_count = 0, cert_count = 0;
|
||||
int result, status = 5;
|
||||
*certificate = NULL;
|
||||
*certificate_length = 0;
|
||||
*private_key = NULL;
|
||||
*private_key_length = 0;
|
||||
if (length > UINT_MAX || gnutls_global_init() < 0) return 5;
|
||||
result = gnutls_pkcs12_init(&archive);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)input, (unsigned int)length};
|
||||
result = gnutls_pkcs12_import(archive, &bytes, GNUTLS_X509_FMT_DER, 0);
|
||||
}
|
||||
if (result < 0) goto out;
|
||||
result = gnutls_pkcs12_verify_mac(archive, password);
|
||||
if (result == GNUTLS_E_MAC_VERIFY_FAILED) { status = 1; goto out; }
|
||||
if (result < 0 && result != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) goto out;
|
||||
for (int index = 0; ; index++) {
|
||||
gnutls_pkcs12_bag_t bag;
|
||||
result = gnutls_pkcs12_bag_init(&bag);
|
||||
if (result < 0) goto out;
|
||||
result = gnutls_pkcs12_get_bag(archive, index, bag);
|
||||
if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
|
||||
gnutls_pkcs12_bag_deinit(bag);
|
||||
break;
|
||||
}
|
||||
if (result >= 0 && gnutls_pkcs12_bag_get_type(bag, 0) == GNUTLS_BAG_ENCRYPTED)
|
||||
result = gnutls_pkcs12_bag_decrypt(bag, password);
|
||||
if (result < 0) {
|
||||
gnutls_pkcs12_bag_deinit(bag);
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1;
|
||||
else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4;
|
||||
goto out;
|
||||
}
|
||||
int count = gnutls_pkcs12_bag_get_count(bag);
|
||||
if (count < 0) { gnutls_pkcs12_bag_deinit(bag); goto out; }
|
||||
for (int item = 0; item < count; item++) {
|
||||
int type = gnutls_pkcs12_bag_get_type(bag, item);
|
||||
if (type == GNUTLS_BAG_PKCS8_KEY || type == GNUTLS_BAG_PKCS8_ENCRYPTED_KEY) key_count++;
|
||||
if (type == GNUTLS_BAG_CERTIFICATE) cert_count++;
|
||||
}
|
||||
gnutls_pkcs12_bag_deinit(bag);
|
||||
}
|
||||
if (key_count == 0 || cert_count == 0) { status = 2; goto out; }
|
||||
if (key_count != 1) { status = 3; goto out; }
|
||||
result = gnutls_pkcs12_simple_parse(archive, password, &key, &chain, &chain_length,
|
||||
&extra, &extra_length, NULL, GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED);
|
||||
if (result < 0) {
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1;
|
||||
else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4;
|
||||
else if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) status = 6;
|
||||
goto out;
|
||||
}
|
||||
if (key == NULL || chain_length == 0) { status = 2; goto out; }
|
||||
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER, NULL, GNUTLS_PKCS_PLAIN, &exported_key);
|
||||
if (result < 0) goto out;
|
||||
for (unsigned int index = 0; index < chain_length; index++) {
|
||||
gnutls_datum_t part = {NULL, 0};
|
||||
result = gnutls_x509_crt_export2(chain[index], GNUTLS_X509_FMT_PEM, &part);
|
||||
if (result < 0) goto out;
|
||||
if (part.size > SIZE_MAX - *certificate_length) { gnutls_free(part.data); goto out; }
|
||||
unsigned char *buffer = gnutls_realloc(*certificate, *certificate_length + part.size);
|
||||
if (buffer == NULL) { gnutls_free(part.data); goto out; }
|
||||
memcpy(buffer + *certificate_length, part.data, part.size);
|
||||
*certificate = buffer;
|
||||
*certificate_length += part.size;
|
||||
gnutls_free(part.data);
|
||||
}
|
||||
*private_key = exported_key.data;
|
||||
*private_key_length = exported_key.size;
|
||||
exported_key.data = NULL;
|
||||
exported_key.size = 0;
|
||||
status = 0;
|
||||
out:
|
||||
if (status != 0) {
|
||||
gp_key_free(*certificate, *certificate_length);
|
||||
*certificate = NULL;
|
||||
*certificate_length = 0;
|
||||
}
|
||||
gp_key_free(exported_key.data, exported_key.size);
|
||||
if (key != NULL) gnutls_x509_privkey_deinit(key);
|
||||
for (unsigned int index = 0; index < chain_length; index++) gnutls_x509_crt_deinit(chain[index]);
|
||||
for (unsigned int index = 0; index < extra_length; index++) gnutls_x509_crt_deinit(extra[index]);
|
||||
gnutls_free(chain);
|
||||
gnutls_free(extra);
|
||||
if (archive != NULL) gnutls_pkcs12_deinit(archive);
|
||||
gnutls_global_deinit();
|
||||
return status;
|
||||
}
|
||||
@@ -1,22 +1,11 @@
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use pkcs8::SecretDocument;
|
||||
use pkcs8::der::{Encode, asn1::ObjectIdentifier};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_certificate_verify_signature(
|
||||
certificate: *const u8,
|
||||
certificate_length: usize,
|
||||
issuer_key: *const u8,
|
||||
issuer_key_length: usize,
|
||||
message: *const u8,
|
||||
message_length: usize,
|
||||
signature: *const u8,
|
||||
signature_length: usize,
|
||||
) -> c_int;
|
||||
fn gp_key_import(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
@@ -25,58 +14,9 @@ unsafe extern "C" {
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_pkcs12_identity(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
password: *const c_char,
|
||||
certificate: *mut *mut u8,
|
||||
certificate_length: *mut usize,
|
||||
key: *mut *mut u8,
|
||||
key_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
pub(super) fn verify_certificate_signature(
|
||||
certificate: &x509_cert::Certificate,
|
||||
issuer: &x509_cert::Certificate,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
|
||||
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
|
||||
let mut issuer_key = issuer.tbs_certificate().subject_public_key_info().clone();
|
||||
if certificate.signature_algorithm().oid == RSA_PSS {
|
||||
if !matches!(issuer_key.algorithm.oid, RSA | RSA_PSS) {
|
||||
return Ok(false);
|
||||
}
|
||||
// GnuTLS's generic verifier takes PSS parameters from the imported key.
|
||||
// Give this verification operation the certificate's full AlgorithmIdentifier,
|
||||
// including salt length, rather than the default implied by its signature enum.
|
||||
// This temporary SPKI never changes the certificates sent to the server.
|
||||
issuer_key.algorithm = certificate.signature_algorithm().clone();
|
||||
}
|
||||
let issuer_key = issuer_key.to_der()?;
|
||||
let certificate = certificate.to_der()?;
|
||||
let result = unsafe {
|
||||
gp_certificate_verify_signature(
|
||||
certificate.as_ptr(),
|
||||
certificate.len(),
|
||||
issuer_key.as_ptr(),
|
||||
issuer_key.len(),
|
||||
message.as_ptr(),
|
||||
message.len(),
|
||||
signature.as_ptr(),
|
||||
signature.len(),
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => Ok(false),
|
||||
1 => Ok(true),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
|
||||
struct ExportedKey {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
@@ -124,55 +64,3 @@ pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str
|
||||
_ => Err(RequestIdentityError::InvalidKey.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn archive(
|
||||
bytes: &[u8],
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<(Zeroizing<Vec<u8>>, SecretDocument)> {
|
||||
let mut password = Zeroizing::new(passphrase.unwrap_or_default().as_bytes().to_vec());
|
||||
anyhow::ensure!(
|
||||
!password.contains(&0),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
password.push(0);
|
||||
let mut certificate = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
let mut key = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
let result = unsafe {
|
||||
gp_pkcs12_identity(
|
||||
bytes.as_ptr(),
|
||||
bytes.len(),
|
||||
password.as_ptr().cast(),
|
||||
&mut certificate.data,
|
||||
&mut certificate.length,
|
||||
&mut key.data,
|
||||
&mut key.length,
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => {
|
||||
anyhow::ensure!(
|
||||
!certificate.data.is_null() && certificate.length > 0,
|
||||
"Invalid certificate file"
|
||||
);
|
||||
anyhow::ensure!(!key.data.is_null() && key.length > 0, "Invalid private key");
|
||||
let certificate =
|
||||
Zeroizing::new(unsafe { std::slice::from_raw_parts(certificate.data, certificate.length) }.to_vec());
|
||||
let key = SecretDocument::try_from(unsafe { std::slice::from_raw_parts(key.data, key.length) })
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
Ok((certificate, key))
|
||||
}
|
||||
1 if passphrase.is_none() => Err(RequestIdentityError::NoPassphrase("PKCS#12").into()),
|
||||
1 => Err(RequestIdentityError::InvalidPkcs12(p12_keystore::error::Error::InvalidData).into()),
|
||||
2 => Err(RequestIdentityError::IncompletePkcs12.into()),
|
||||
3 => Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
4 => Err(RequestIdentityError::UnsupportedEncryption.into()),
|
||||
6 => Err(RequestIdentityError::KeyMismatch.into()),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
use pkcs8::der::{Decode, Encode};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
/// Identify the signing issuer, without applying trust, expiry or extension policy
|
||||
/// to a local identity. The VPN server remains responsible for those checks.
|
||||
pub(super) fn is_issuer(certificate: &[u8], issuer: &[u8]) -> anyhow::Result<bool> {
|
||||
let child = x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let parent = x509_cert::Certificate::from_der(issuer).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
if child.tbs_certificate().issuer() != parent.tbs_certificate().subject() {
|
||||
return Ok(false);
|
||||
}
|
||||
let signature = child
|
||||
.signature()
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
super::platform_import::verify_certificate_signature(&child, &parent, &child.tbs_certificate().to_der()?, signature)
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
mod client_key;
|
||||
mod issuer;
|
||||
pub(super) use client_key::{ClientKey, validate_certificate};
|
||||
|
||||
pub(super) mod pkcs12;
|
||||
mod pkcs12_format;
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
@@ -12,14 +7,14 @@ mod pkcs12_format;
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "gnutls.rs"]
|
||||
mod platform_import;
|
||||
mod legacy_key;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "portable_import.rs"]
|
||||
mod platform_import;
|
||||
#[path = "unsupported.rs"]
|
||||
mod legacy_key;
|
||||
|
||||
pub(super) use platform_import::{archive, decrypt as decrypt_key};
|
||||
pub(super) use legacy_key::decrypt as decrypt_key;
|
||||
@@ -1,307 +0,0 @@
|
||||
use std::{
|
||||
ffi::{c_int, c_void},
|
||||
fmt,
|
||||
ptr::NonNull,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use rustls::{
|
||||
SignatureAlgorithm, SignatureScheme,
|
||||
pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer},
|
||||
sign::{Signer, SigningKey},
|
||||
};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_client_key_new(data: *const u8, length: usize, kind: *mut c_int, output: *mut *mut c_void) -> c_int;
|
||||
fn gp_client_key_delete(key: *mut c_void);
|
||||
fn gp_client_key_public(key: *mut c_void, output: *mut *mut u8, length: *mut usize) -> c_int;
|
||||
fn gp_client_key_matches(key: *mut c_void, cert: *const u8, length: usize) -> c_int;
|
||||
fn gp_client_key_sign(
|
||||
key: *mut c_void,
|
||||
scheme: u16,
|
||||
message: *const u8,
|
||||
length: usize,
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
struct NativeKey(NonNull<c_void>);
|
||||
|
||||
// The handle is not thread-affine. All access and final release occur under its
|
||||
// Rust owner; shared operations use the mutex in ClientKey.
|
||||
unsafe impl Send for NativeKey {}
|
||||
|
||||
impl Drop for NativeKey {
|
||||
fn drop(&mut self) {
|
||||
unsafe { gp_client_key_delete(self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
struct NativeBytes {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
}
|
||||
impl Drop for NativeBytes {
|
||||
fn drop(&mut self) {
|
||||
unsafe { gp_key_free(self.data, self.length) };
|
||||
}
|
||||
}
|
||||
impl NativeBytes {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
fn copy(&self) -> anyhow::Result<Vec<u8>> {
|
||||
anyhow::ensure!(
|
||||
!self.data.is_null() && self.length > 0,
|
||||
"Client certificate operation failed"
|
||||
);
|
||||
Ok(unsafe { std::slice::from_raw_parts(self.data, self.length) }.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::utils) struct ClientKey {
|
||||
key: Arc<Mutex<NativeKey>>,
|
||||
kind: c_int,
|
||||
public_key: Vec<u8>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ClientKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ClientKey")
|
||||
.field("algorithm", &self.algorithm())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientKey {
|
||||
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
|
||||
super::validate_private_key(key)?;
|
||||
let bytes = key.secret_der();
|
||||
let mut kind = 0;
|
||||
let mut pointer = std::ptr::null_mut();
|
||||
let result = unsafe { gp_client_key_new(bytes.as_ptr(), bytes.len(), &mut kind, &mut pointer) };
|
||||
if result == 2 {
|
||||
let algorithm = match kind {
|
||||
3 => "P-521",
|
||||
5 => "RSA-PSS",
|
||||
6 => "an unsupported elliptic curve",
|
||||
7 => "DSA",
|
||||
8 => "Ed448",
|
||||
_ => "an unknown key algorithm",
|
||||
};
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(algorithm).into());
|
||||
}
|
||||
if result != 0 {
|
||||
return Err(RequestIdentityError::InvalidKey.into());
|
||||
}
|
||||
let key = NativeKey(NonNull::new(pointer).ok_or(RequestIdentityError::InvalidKey)?);
|
||||
let mut exported = NativeBytes::new();
|
||||
let result = unsafe { gp_client_key_public(key.0.as_ptr(), &mut exported.data, &mut exported.length) };
|
||||
anyhow::ensure!(result == 0, "Could not read the client certificate's public key");
|
||||
Ok(Self {
|
||||
key: Arc::new(Mutex::new(key)),
|
||||
kind,
|
||||
public_key: exported.copy()?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result<bool> {
|
||||
let key = self
|
||||
.key
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("The client certificate is unavailable"))?;
|
||||
match unsafe { gp_client_key_matches(key.0.as_ptr(), certificate.as_ptr(), certificate.len()) } {
|
||||
1 => Ok(true),
|
||||
0 => Ok(false),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn schemes(&self) -> &'static [SignatureScheme] {
|
||||
use SignatureScheme::*;
|
||||
match self.kind {
|
||||
0 => &[
|
||||
RSA_PSS_SHA512,
|
||||
RSA_PSS_SHA384,
|
||||
RSA_PSS_SHA256,
|
||||
RSA_PKCS1_SHA512,
|
||||
RSA_PKCS1_SHA384,
|
||||
RSA_PKCS1_SHA256,
|
||||
],
|
||||
// Rustls does not expose the negotiated TLS version here. Keep TLS 1.3
|
||||
// curve/hash requirements; TLS 1.2 cross-curve hash offers remain unsupported.
|
||||
1 => &[ECDSA_NISTP256_SHA256],
|
||||
2 => &[ECDSA_NISTP384_SHA384],
|
||||
4 => &[ED25519],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SigningKey for ClientKey {
|
||||
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
|
||||
self
|
||||
.schemes()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|scheme| offered.contains(scheme))
|
||||
.map(|scheme| {
|
||||
Box::new(ClientSigner {
|
||||
key: self.clone(),
|
||||
scheme,
|
||||
}) as Box<dyn Signer>
|
||||
})
|
||||
}
|
||||
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
|
||||
Some(SubjectPublicKeyInfoDer::from(self.public_key.as_slice()))
|
||||
}
|
||||
fn algorithm(&self) -> SignatureAlgorithm {
|
||||
match self.kind {
|
||||
0 => SignatureAlgorithm::RSA,
|
||||
4 => SignatureAlgorithm::ED25519,
|
||||
_ => SignatureAlgorithm::ECDSA,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ClientSigner {
|
||||
key: ClientKey,
|
||||
scheme: SignatureScheme,
|
||||
}
|
||||
impl Signer for ClientSigner {
|
||||
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, rustls::Error> {
|
||||
let error = || rustls::Error::General("Could not sign with the client certificate".into());
|
||||
let key = self.key.key.lock().map_err(|_| error())?;
|
||||
let mut output = NativeBytes::new();
|
||||
let result = unsafe {
|
||||
gp_client_key_sign(
|
||||
key.0.as_ptr(),
|
||||
self.scheme.into(),
|
||||
message.as_ptr(),
|
||||
message.len(),
|
||||
&mut output.data,
|
||||
&mut output.length,
|
||||
)
|
||||
};
|
||||
if result != 0 {
|
||||
return Err(error());
|
||||
}
|
||||
output.copy().map_err(|_| error())
|
||||
}
|
||||
fn scheme(&self) -> SignatureScheme {
|
||||
self.scheme
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openssl::{
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Padding,
|
||||
sign::{RsaPssSaltlen, Verifier},
|
||||
};
|
||||
|
||||
fn fixture(name: &str) -> Vec<u8> {
|
||||
std::fs::read(
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn native_key(bytes: &[u8]) -> ClientKey {
|
||||
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
ClientKey::load(&key).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() {
|
||||
let bytes = fixture("rsa-pkcs8.pem");
|
||||
let key = native_key(&bytes);
|
||||
let oracle = PKey::private_key_from_pem(&bytes).unwrap();
|
||||
let message = b"client authentication regression";
|
||||
for (scheme, digest, pss) in [
|
||||
(SignatureScheme::RSA_PSS_SHA256, MessageDigest::sha256(), true),
|
||||
(SignatureScheme::RSA_PSS_SHA384, MessageDigest::sha384(), true),
|
||||
(SignatureScheme::RSA_PSS_SHA512, MessageDigest::sha512(), true),
|
||||
(SignatureScheme::RSA_PKCS1_SHA256, MessageDigest::sha256(), false),
|
||||
(SignatureScheme::RSA_PKCS1_SHA384, MessageDigest::sha384(), false),
|
||||
(SignatureScheme::RSA_PKCS1_SHA512, MessageDigest::sha512(), false),
|
||||
] {
|
||||
let signer = key.choose_scheme(&[scheme]).unwrap();
|
||||
assert_eq!(signer.scheme(), scheme);
|
||||
let signature = signer.sign(message).unwrap();
|
||||
let mut verifier = Verifier::new(digest, &oracle).unwrap();
|
||||
if pss {
|
||||
verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
|
||||
verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap();
|
||||
verifier.set_rsa_mgf1_md(digest).unwrap();
|
||||
}
|
||||
assert!(verifier.verify_oneshot(&signature, message).unwrap(), "{scheme:?}");
|
||||
}
|
||||
assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p256_signatures_verify_with_an_independent_backend() {
|
||||
let bytes = fixture("ec-pkcs8.pem");
|
||||
let key = native_key(&bytes);
|
||||
let oracle = PKey::private_key_from_pem(&bytes).unwrap();
|
||||
let signer = key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).unwrap();
|
||||
let message = b"native client key signature";
|
||||
let signature = signer.sign(message).unwrap();
|
||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap();
|
||||
assert!(verifier.verify_oneshot(&signature, message).unwrap());
|
||||
assert!(key.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_key_types_fail_at_import() {
|
||||
for (name, algorithm) in [("ec-p521.pem", "P-521"), ("rsa-pss.pem", "RSA-PSS")] {
|
||||
let bytes = fixture(name);
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let error = ClientKey::load(&private_key).unwrap_err();
|
||||
assert!(matches!(error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedKeyAlgorithm(actual)) if *actual == algorithm));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_remains_usable_when_shared_clients_sign_concurrently() {
|
||||
let key = native_key(&fixture("rsa-pkcs8.pem"));
|
||||
let mut workers = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let key = key.clone();
|
||||
workers.push(std::thread::spawn(move || {
|
||||
key
|
||||
.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
|
||||
.unwrap()
|
||||
.sign(b"shared identity")
|
||||
.unwrap()
|
||||
}));
|
||||
}
|
||||
let oracle = PKey::private_key_from_pem(&fixture("rsa-pkcs8.pem")).unwrap();
|
||||
for worker in workers {
|
||||
let signature = worker.join().unwrap();
|
||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap();
|
||||
verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
|
||||
verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap();
|
||||
assert!(verifier.verify_oneshot(&signature, b"shared identity").unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,22 @@
|
||||
use p12_keystore::Pkcs12Archive;
|
||||
use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
|
||||
use super::{
|
||||
ClientKey,
|
||||
pkcs12_format::{self, ArchiveBackend},
|
||||
use rustls::{
|
||||
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
sign::CertifiedKey,
|
||||
};
|
||||
use crate::utils::{client_tls, request::RequestIdentityError};
|
||||
|
||||
pub(in crate::utils) fn certified_key(
|
||||
bytes: &[u8],
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<std::sync::Arc<rustls::sign::CertifiedKey>> {
|
||||
use crate::utils::request::{RequestIdentityError, pem_request_identity};
|
||||
|
||||
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> {
|
||||
anyhow::ensure!(
|
||||
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
if pkcs12_format::backend(bytes)? == ArchiveBackend::NativeRc4 {
|
||||
let (certificate, key) = super::archive(bytes, passphrase)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
return client_tls::pem_certified_key(&certificate, key.as_bytes());
|
||||
}
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| match error {
|
||||
p12_keystore::error::Error::UnsupportedEncryptionScheme | p12_keystore::error::Error::UnsupportedMacAlgorithm => {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
}
|
||||
p12_keystore::error::Error::MacError(_)
|
||||
| p12_keystore::error::Error::UnpadError
|
||||
| p12_keystore::error::Error::Pkcs5Error(_)
|
||||
if passphrase.is_none() =>
|
||||
{
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
error => RequestIdentityError::InvalidPkcs12(error),
|
||||
})?;
|
||||
if archive.keys.is_empty() || archive.certs.is_empty() {
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
@@ -40,8 +25,7 @@ pub(in crate::utils) fn certified_key(
|
||||
return Err(RequestIdentityError::AmbiguousPkcs12.into());
|
||||
}
|
||||
let key = &archive.keys[0].key;
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
let signing_key = ClientKey::load(&private_key)?;
|
||||
let provider = rustls::crypto::ring::default_provider();
|
||||
let mut certs = Vec::new();
|
||||
for bag in &archive.certs {
|
||||
if !certs
|
||||
@@ -51,36 +35,38 @@ pub(in crate::utils) fn certified_key(
|
||||
certs.push(&bag.cert);
|
||||
}
|
||||
}
|
||||
let mut matches = Vec::new();
|
||||
for (index, cert) in certs.iter().enumerate() {
|
||||
if signing_key.matches_certificate(cert.as_der())? {
|
||||
matches.push(index);
|
||||
}
|
||||
}
|
||||
let leaf = match matches.first() {
|
||||
Some(leaf) => *leaf,
|
||||
None => return Err(RequestIdentityError::KeyMismatch.into()),
|
||||
let matches: Vec<_> = certs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, cert)| {
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
CertifiedKey::from_der(
|
||||
vec![CertificateDer::from(cert.as_der().to_vec())],
|
||||
private_key,
|
||||
&provider,
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(index)
|
||||
})
|
||||
.collect();
|
||||
let leaf = match matches.as_slice() {
|
||||
[leaf] => *leaf,
|
||||
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
};
|
||||
let mut current = certs.remove(leaf);
|
||||
let mut chain = Vec::new();
|
||||
loop {
|
||||
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
|
||||
if super::issuer::is_issuer(current.as_der(), current.as_der())? {
|
||||
if current.subject() == current.issuer() {
|
||||
break;
|
||||
}
|
||||
let mut parent = None;
|
||||
for (index, candidate) in certs.iter().enumerate() {
|
||||
if super::issuer::is_issuer(current.as_der(), candidate.as_der())? {
|
||||
parent = Some(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(parent) = parent else {
|
||||
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
|
||||
break;
|
||||
};
|
||||
current = certs.remove(parent);
|
||||
}
|
||||
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
client_tls::pem_certified_key(&chain, key.as_bytes())
|
||||
pem_request_identity(&chain, key.as_bytes())
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
//! Select an archive importer from decoded encryption metadata, before passwords.
|
||||
use cms::encrypted_data::EncryptedData;
|
||||
use pkcs8::{
|
||||
ObjectIdentifier,
|
||||
der::{
|
||||
Decode, Encode,
|
||||
asn1::{ContextSpecific, OctetString},
|
||||
},
|
||||
};
|
||||
use pkcs12::{
|
||||
AuthenticatedSafe,
|
||||
pbe_params::{EncryptedPrivateKeyInfo, Pkcs12PbeParams},
|
||||
pfx::Pfx,
|
||||
safe_bag::SafeContents,
|
||||
};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
|
||||
const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6");
|
||||
const ENCRYPTED_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2");
|
||||
const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13");
|
||||
const RC4_128: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.1");
|
||||
const DES3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3");
|
||||
const RC2_40: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.6");
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ArchiveBackend {
|
||||
Rust,
|
||||
NativeRc4,
|
||||
}
|
||||
|
||||
fn invalid(_: pkcs8::der::Error) -> RequestIdentityError {
|
||||
RequestIdentityError::InvalidCertificate
|
||||
}
|
||||
|
||||
/// Inspect only visible metadata. Encrypted safe contents remain opaque until
|
||||
/// the selected importer verifies the MAC and decrypts them.
|
||||
pub(super) fn backend(bytes: &[u8]) -> Result<ArchiveBackend, RequestIdentityError> {
|
||||
let pfx = Pfx::from_der(bytes).map_err(invalid)?;
|
||||
if pfx.auth_safe.content_type != DATA {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
let contents = pfx.auth_safe.content.decode_as::<OctetString>().map_err(invalid)?;
|
||||
let safes = AuthenticatedSafe::from_der(contents.as_bytes()).map_err(invalid)?;
|
||||
let mut selected = ArchiveBackend::Rust;
|
||||
for safe in safes {
|
||||
if safe.content_type == ENCRYPTED_DATA {
|
||||
let encrypted = safe.content.decode_as::<EncryptedData>().map_err(invalid)?;
|
||||
let algorithm = encrypted.enc_content_info.content_enc_alg;
|
||||
inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?;
|
||||
} else if safe.content_type == DATA {
|
||||
let contents = safe.content.decode_as::<OctetString>().map_err(invalid)?;
|
||||
let bags = SafeContents::from_der(contents.as_bytes()).map_err(invalid)?;
|
||||
for bag in bags {
|
||||
if bag.bag_id == ENCRYPTED_KEY {
|
||||
let encrypted = ContextSpecific::<EncryptedPrivateKeyInfo>::from_der(&bag.bag_value).map_err(invalid)?;
|
||||
let algorithm = encrypted.value.encryption_algorithm;
|
||||
inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
}
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
fn inspect_algorithm(
|
||||
oid: ObjectIdentifier,
|
||||
parameters: Option<&pkcs8::der::Any>,
|
||||
selected: &mut ArchiveBackend,
|
||||
) -> Result<(), RequestIdentityError> {
|
||||
let parameters = parameters
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?
|
||||
.to_der()
|
||||
.map_err(invalid)?;
|
||||
if oid == PBES2 {
|
||||
pkcs8::pkcs5::pbes2::Parameters::from_der(¶meters).map_err(|error| match error.kind() {
|
||||
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
|
||||
_ => RequestIdentityError::InvalidCertificate,
|
||||
})?;
|
||||
} else if matches!(oid, RC4_128 | DES3 | RC2_40) {
|
||||
Pkcs12PbeParams::from_der(¶meters).map_err(invalid)?;
|
||||
if oid == RC4_128 {
|
||||
*selected = ArchiveBackend::NativeRc4;
|
||||
}
|
||||
} else {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn published_archive_formats_choose_their_importer_from_metadata() {
|
||||
for name in [
|
||||
"modern.p12",
|
||||
"legacy-rc2.p12",
|
||||
"empty-password.p12",
|
||||
"unicode-password.p12",
|
||||
"no-bag-ids.p12",
|
||||
] {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name);
|
||||
assert_eq!(
|
||||
backend(&std::fs::read(path).unwrap()).unwrap(),
|
||||
ArchiveBackend::Rust,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
backend(include_bytes!(
|
||||
"../../../tests/files/client-identity/legacy-RC4-128.p12"
|
||||
))
|
||||
.unwrap(),
|
||||
ArchiveBackend::NativeRc4
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_archive_encryption_is_terminal_before_password_handling() {
|
||||
for bytes in [
|
||||
include_bytes!("../../../tests/files/client-identity/legacy-RC2-128.p12").as_slice(),
|
||||
include_bytes!("../../../tests/files/client-identity/legacy-2DES.p12").as_slice(),
|
||||
] {
|
||||
assert!(matches!(
|
||||
backend(bytes),
|
||||
Err(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Portable certificate verification; native legacy import is unavailable here.
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use pkcs8::der::{Decode, Encode, asn1::AnyRef};
|
||||
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn archive(
|
||||
_bytes: &[u8],
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<(zeroize::Zeroizing<Vec<u8>>, pkcs8::SecretDocument)> {
|
||||
Err(RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
|
||||
pub(super) fn verify_certificate_signature(
|
||||
child: &x509_cert::Certificate,
|
||||
parent: &x509_cert::Certificate,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
let public_key = parent.tbs_certificate().subject_public_key_info();
|
||||
let key_algorithm = public_key.algorithm.to_der()?;
|
||||
let signature_algorithm = child.signature_algorithm().to_der()?;
|
||||
let key_algorithm = AnyRef::from_der(&key_algorithm)?.value();
|
||||
let signature_algorithm = AnyRef::from_der(&signature_algorithm)?.value();
|
||||
let key = public_key
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
Ok(
|
||||
rustls::crypto::ring::default_provider()
|
||||
.signature_verification_algorithms
|
||||
.all
|
||||
.iter()
|
||||
.any(|algorithm| {
|
||||
algorithm.public_key_alg_id().as_ref() == key_algorithm
|
||||
&& algorithm.signature_alg_id().as_ref() == signature_algorithm
|
||||
&& algorithm.verify_signature(key, message, signature).is_ok()
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use pkcs8::der::{Decode, Encode};
|
||||
use rustls::{
|
||||
SignatureAlgorithm, SignatureScheme,
|
||||
pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer},
|
||||
sign::{Signer, SigningKey},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(in crate::utils) struct ClientKey {
|
||||
key: Arc<dyn SigningKey>,
|
||||
}
|
||||
|
||||
impl ClientKey {
|
||||
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
|
||||
super::validate_private_key(key)?;
|
||||
let key = rustls::crypto::ring::default_provider()
|
||||
.key_provider
|
||||
.load_private_key(key.clone_key())
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
Ok(Self { key })
|
||||
}
|
||||
pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result<bool> {
|
||||
let certificate =
|
||||
x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let key = self.key.public_key().ok_or(RequestIdentityError::InvalidKey)?;
|
||||
Ok(certificate.tbs_certificate().subject_public_key_info().to_der()? == key.as_ref())
|
||||
}
|
||||
}
|
||||
impl SigningKey for ClientKey {
|
||||
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
|
||||
self.key.choose_scheme(offered)
|
||||
}
|
||||
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
|
||||
self.key.public_key()
|
||||
}
|
||||
fn algorithm(&self) -> SignatureAlgorithm {
|
||||
self.key.algorithm()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
//! Local identity matching is separate from the peer's certificate validation.
|
||||
use std::{io::Cursor, sync::Arc};
|
||||
|
||||
use pkcs8::der::Decode;
|
||||
use rustls::{
|
||||
ClientConfig, DigitallySignedStruct, SignatureScheme,
|
||||
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
|
||||
pki_types::{CertificateDer, ServerName, UnixTime},
|
||||
sign::{CertifiedKey, SingleCertAndKey},
|
||||
};
|
||||
use rustls_platform_verifier::BuilderVerifierExt;
|
||||
|
||||
use super::{
|
||||
certificate::{ClientKey, validate_certificate},
|
||||
request::RequestIdentityError,
|
||||
};
|
||||
|
||||
pub(super) fn pem_certified_key(certificate: &[u8], key: &[u8]) -> anyhow::Result<Arc<CertifiedKey>> {
|
||||
let certificates = rustls_pemfile::certs(&mut Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut Cursor::new(key))
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
let signing_key = Arc::new(ClientKey::load(&private_key)?);
|
||||
let leaf = certificates.first().ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
validate_certificate(leaf)?;
|
||||
if !signing_key.matches_certificate(leaf)? {
|
||||
return Err(RequestIdentityError::KeyMismatch.into());
|
||||
}
|
||||
for certificate in certificates.iter().skip(1) {
|
||||
x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
}
|
||||
// The local key has been matched without applying peer certificate policy.
|
||||
Ok(Arc::new(CertifiedKey::new(certificates, signing_key)))
|
||||
}
|
||||
|
||||
pub(super) fn identity_client_builder(
|
||||
identity: Arc<CertifiedKey>,
|
||||
ignore_server_certificate_errors: bool,
|
||||
) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let config = ClientConfig::builder_with_provider(provider.clone()).with_safe_default_protocol_versions()?;
|
||||
let config = if ignore_server_certificate_errors {
|
||||
config
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(IgnoreServerCertificateErrors {
|
||||
schemes: provider.signature_verification_algorithms.supported_schemes(),
|
||||
}))
|
||||
} else {
|
||||
// Match Reqwest's default system trust store, including private enterprise CAs.
|
||||
config.with_platform_verifier()?
|
||||
};
|
||||
let mut config = config.with_client_cert_resolver(Arc::new(SingleCertAndKey::from(identity)));
|
||||
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
Ok(super::request::client_builder().tls_backend_preconfigured(config))
|
||||
}
|
||||
|
||||
/// Equivalent to Reqwest's danger_accept_invalid_certs(true), used only when
|
||||
/// the user explicitly enables the existing ignore-certificate-errors setting.
|
||||
#[derive(Debug)]
|
||||
struct IgnoreServerCertificateErrors {
|
||||
schemes: Vec<SignatureScheme>,
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for IgnoreServerCertificateErrors {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_: &CertificateDer<'_>,
|
||||
_: &[CertificateDer<'_>],
|
||||
_: &ServerName<'_>,
|
||||
_: &[u8],
|
||||
_: UnixTime,
|
||||
) -> Result<ServerCertVerified, rustls::Error> {
|
||||
Ok(ServerCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
_: &[u8],
|
||||
_: &CertificateDer<'_>,
|
||||
_: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
_: &[u8],
|
||||
_: &CertificateDer<'_>,
|
||||
_: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
self.schemes.clone()
|
||||
}
|
||||
}
|
||||
@@ -90,8 +90,7 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
}
|
||||
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
|
||||
"EC PRIVATE KEY" => {
|
||||
// The signing provider validates both named and explicitly encoded curves.
|
||||
SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
return Ok(block.encoded());
|
||||
}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use common::paths::service_lock_file;
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use thiserror::Error;
|
||||
use tokio::fs;
|
||||
|
||||
@@ -109,7 +109,7 @@ impl LockInfo {
|
||||
}
|
||||
|
||||
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
|
||||
gpservice_lock_info_at(service_lock_file()).await
|
||||
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
|
||||
}
|
||||
|
||||
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
|
||||
|
||||
@@ -3,7 +3,6 @@ pub mod xml;
|
||||
pub mod base64;
|
||||
mod certificate;
|
||||
pub mod checksum;
|
||||
mod client_tls;
|
||||
pub mod crypto;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod endpoint;
|
||||
|
||||
@@ -1,40 +1,34 @@
|
||||
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use rustls::sign::CertifiedKey;
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{certificate::pkcs12, client_tls, identity_encoding};
|
||||
use super::{certificate::pkcs12, identity_encoding};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
#[error("No private key was found. Choose the matching key file")]
|
||||
#[error("Failed to find the private key")]
|
||||
NoKey,
|
||||
#[error("This certificate or key is password-protected. Enter its password")]
|
||||
#[error("No passphrase provided")]
|
||||
NoPassphrase(&'static str),
|
||||
#[error("Could not unlock the certificate or key. Check the password and file")]
|
||||
#[error("Failed to decrypt private key")]
|
||||
DecryptError(&'static str),
|
||||
#[error("This certificate or key uses unsupported encryption. Re-export it with AES encryption")]
|
||||
UnsupportedEncryption,
|
||||
#[error("This private key format is not supported. Choose a PEM key or a PKCS#12 certificate file")]
|
||||
UnsupportedKeyFormat,
|
||||
#[error(
|
||||
"This client certificate uses an unsupported key type ({0}). Ask your VPN administrator for an RSA or P-256 certificate"
|
||||
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
|
||||
)]
|
||||
UnsupportedKeyAlgorithm(&'static str),
|
||||
#[error("The private key does not match this certificate. Choose the matching key file")]
|
||||
KeyMismatch,
|
||||
#[error("The private key file is invalid. Choose a different key file")]
|
||||
UnsupportedEncryption,
|
||||
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
|
||||
UnsupportedKeyFormat,
|
||||
#[error("Invalid private key")]
|
||||
InvalidKey,
|
||||
#[error("The certificate file is invalid. Choose a different certificate file")]
|
||||
#[error("Invalid certificate or certificate chain")]
|
||||
InvalidCertificate,
|
||||
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
|
||||
IncompletePkcs12,
|
||||
#[error("Could not open the PKCS#12 file. Check the password or choose another file")]
|
||||
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
|
||||
InvalidPkcs12(#[source] p12_keystore::error::Error),
|
||||
#[error(
|
||||
"The certificate file contains more than one matching identity. Choose a file with one client certificate and key"
|
||||
)]
|
||||
#[error("The PKCS#12 file must contain one matching client identity")]
|
||||
AmbiguousPkcs12,
|
||||
}
|
||||
|
||||
@@ -44,7 +38,7 @@ pub enum RequestIdentityError {
|
||||
#[derive(Clone)]
|
||||
pub struct ClientIdentity {
|
||||
material: Arc<IdentityMaterial>,
|
||||
certified_key: Arc<CertifiedKey>,
|
||||
identity: Identity,
|
||||
}
|
||||
|
||||
struct IdentityMaterial {
|
||||
@@ -74,14 +68,14 @@ impl ClientIdentity {
|
||||
};
|
||||
let key = identity_encoding::private_key(&key_bytes, passphrase)?;
|
||||
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
|
||||
let certified_key = client_tls::pem_certified_key(&certificate, &key)?;
|
||||
let identity = pem_request_identity(&certificate, &key)?;
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
key: Some(key),
|
||||
passphrase: None,
|
||||
}),
|
||||
certified_key,
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -92,12 +86,12 @@ impl ClientIdentity {
|
||||
key: Option<Zeroizing<Vec<u8>>>,
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let (certified_key, passphrase) = match &key {
|
||||
Some(key) => (client_tls::pem_certified_key(&certificate, key)?, None),
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (pem_request_identity(&certificate, key)?, None),
|
||||
None => {
|
||||
let certified_key = pkcs12::certified_key(&certificate, passphrase)?;
|
||||
let identity = pkcs12::identity(&certificate, passphrase)?;
|
||||
(
|
||||
certified_key,
|
||||
identity,
|
||||
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
|
||||
)
|
||||
}
|
||||
@@ -108,7 +102,7 @@ impl ClientIdentity {
|
||||
key,
|
||||
passphrase,
|
||||
}),
|
||||
certified_key,
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -121,8 +115,8 @@ impl ClientIdentity {
|
||||
pub fn key_password(&self) -> Option<&str> {
|
||||
self.material.passphrase.as_ref().map(|value| value.as_str())
|
||||
}
|
||||
pub(crate) fn client_builder(&self, ignore_tls_errors: bool) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
client_tls::identity_client_builder(self.certified_key.clone(), ignore_tls_errors)
|
||||
pub(crate) fn request_identity(&self) -> Identity {
|
||||
self.identity.clone()
|
||||
}
|
||||
|
||||
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
|
||||
@@ -155,6 +149,29 @@ impl ClientIdentityFiles {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
let error_context =
|
||||
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
|
||||
let mut combined = Zeroizing::new(certificate.to_vec());
|
||||
combined.push(b'\n');
|
||||
combined.extend_from_slice(key);
|
||||
let identity = Identity::from_pem(&combined).context(error_context)?;
|
||||
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(error_context)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
|
||||
.context(error_context)?
|
||||
.context(error_context)?;
|
||||
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
|
||||
.context(error_context)?;
|
||||
client_builder()
|
||||
.no_proxy()
|
||||
.identity(identity.clone())
|
||||
.build()
|
||||
.context(error_context)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
Ok(Zeroizing::new(
|
||||
fs::read(path).context("Failed to read client identity")?,
|
||||
@@ -191,6 +208,12 @@ pub fn client_builder() -> reqwest::ClientBuilder {
|
||||
reqwest::Client::builder().tls_backend_rustls()
|
||||
}
|
||||
|
||||
/// 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::*;
|
||||
@@ -199,29 +222,6 @@ mod tests {
|
||||
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem");
|
||||
const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem");
|
||||
|
||||
#[test]
|
||||
fn unsupported_identity_errors_explain_the_action_without_blaming_passwords_or_key_matching() {
|
||||
for error in [
|
||||
RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"),
|
||||
RequestIdentityError::UnsupportedEncryption,
|
||||
RequestIdentityError::UnsupportedKeyFormat,
|
||||
] {
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.contains("unsupported") || message.contains("not supported"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("Ask ") || message.contains("Re-export ") || message.contains("Choose "),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
!message.contains("password") && !message.contains("does not match"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_without_key_reports_missing_key_even_with_passphrase() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
@@ -247,21 +247,21 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_loading_preserves_password_errors_and_builds_a_request_client() {
|
||||
fn create_identity_preserves_password_errors_and_builds_a_request_client() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(ENCRYPTED_KEY).unwrap();
|
||||
for (password, missing) in [(None, true), (Some("wrong"), false)] {
|
||||
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, password).unwrap_err();
|
||||
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("Unexpected identity error: {other:?}"),
|
||||
}
|
||||
}
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
drop(source);
|
||||
identity.client_builder(false).unwrap().build().unwrap();
|
||||
client_builder().identity(identity).build().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -283,7 +283,7 @@ mod tests {
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&path).exists());
|
||||
identity.client_builder(false).unwrap().build().unwrap();
|
||||
client_builder().identity(identity.request_identity()).build().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,6 @@ pub async fn shutdown_signal() {
|
||||
.await;
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user