Compare commits

..
Author SHA1 Message Date
Kevin Yue 4e6a3ab553 ci: publish only Windows installers and their verification files 2026-11-15 10:22:29 +08:00
Kevin Yue 976fcd5adc fix(ci): retain the verified Unix build during macOS retry promotion 2026-11-15 09:17:39 +08:00
Kevin Yue b7450ecae3 fix(ci): wait for Windows update feed propagation 2026-11-15 03:00:52 +08:00
Kevin Yue ed306bdbdc fix(ci): identify the release feed publisher in HTTP requests 2026-11-15 02:53:13 +08:00
Kevin Yue e22aa64ba6 chore: update OpenConnect native warning cleanup 2026-11-15 02:35:12 +08:00
Kevin Yue 5b17706ff1 chore: update OpenConnect to remove native compiler warning 2026-11-15 02:00:56 +08:00
Kevin Yue 6e72eb19e1 fix(windows): handle inherited modules and short extraction paths 2026-11-15 02:00:21 +08:00
Kevin Yue 78afa8fd14 ci: retain signed candidates and installer failure diagnostics 2026-11-15 01:02:57 +08:00
Kevin Yue 0f85b259cd test: check retained state inside the actual configuration tree 2026-11-15 00:54:18 +08:00
Kevin Yue 343ed3b1e5 ci: reuse the selected Windows signing tools 2026-11-15 00:49:34 +08:00
Kevin Yue 42f4aebbde feat: publish architecture-specific Windows update payloads 2026-11-15 00:48:36 +08:00
Kevin Yue df28072f60 ci: report safe Windows build failure locations 2026-11-15 00:32:33 +08:00
Kevin Yue de9656fcd2 feat: build and smoke test native Windows ARM64 packages 2026-11-15 00:25:34 +08:00
Kevin Yue 87fdcc76b3 test: cover Windows device anchor in credential frames 2026-11-15 00:00:53 +08:00
Kevin Yue 8d768f4584 build: enforce LF source checkouts with Git attributes 2026-11-14 23:44:30 +08:00
Kevin Yue b84712b038 fix: preserve LF endings in Windows CI source checkout 2026-11-14 23:42:39 +08:00
Kevin Yue cf715ea38f fix: repair platform dependency and Windows CI inputs 2026-11-14 23:38:03 +08:00
Kevin Yue 560d2b2de7 feat: build and publish Windows NSH packages with verified updates 2026-11-14 23:10:21 +08:00
Kevin Yue 2c9d227f02 Merge pull request #704 from yuezk/fix/feed-publisher-runner
ci: run feed publication on Intel macOS
2026-11-13 00:32:41 +08:00
Kevin Yue f3cd4ca6fb ci: run feed publication on Intel macOS 2026-11-13 00:29:24 +08:00
Kevin Yue 79570610db Merge pull request #703 from yuezk/chore/promote-v3.4.0
chore: promote GP Connect 3.4.0 sources and Nix packages
2026-11-13 00:05:18 +08:00
Kevin Yue a5e8c7abe5 release: derive AUR version from the promoted tag 2026-11-13 00:00:31 +08:00
Kevin Yue e122ad8380 release: validate Nix packages for v3.4.0 2026-11-13 00:00:30 +08:00
Kevin Yue 28643d2de6 Merge commit '53a778a1a4d9cb8883826d242e8b1ee9d4d9438b' into chore/promote-v3.4.0 2026-11-13 00:00:29 +08:00
Kevin Yue f5b1b279c7 Merge pull request #702 from yuezk/fix/defer-aur-tag-versioning
fix: defer AUR tag versioning until release promotion
2026-11-12 23:06:44 +08:00
Kevin Yue 9528818793 fix(aur): keep Cargo versioning until release promotion 2026-11-12 23:05:16 +08:00
Kevin Yue 53a778a1a4 release: GP Connect 3.4.0 2026-11-12 23:01:11 +08:00
Kevin Yue d1815a02a1 Merge pull request #701 from yuezk/chore/release-promotion-history
fix: preserve release tag history during promotion
2026-11-12 22:58:29 +08:00
Kevin Yue 1547d0c1e9 fix(release): preserve tag ancestry during source promotion 2026-11-12 22:57:06 +08:00
Kevin Yue 6e99d8d81f fix: derive AUR VCS version from Cargo after squash releases (#700) 2026-11-09 00:59:42 +08:00
Kevin Yue 408536807c chore: promote GP Connect 3.3.1 sources and Nix packages (#699)
* fix: restore client certificate compatibility after OpenSSL removal

Use GnuTLS for desktop client key matching and signing without applying server certificate policy to local identities. Restore RC4 PKCS12 import and renewed certificate selection, and provide actionable unsupported identity errors.

Add HTTP and OpenConnect mutual TLS regressions. Record the unresolved TLS 1.2 ECDSA hash limitation and reject P-521 and RSA-PSS keys explicitly.

* fix: select PKCS12 issuers by certificate signature

Handle CA rollover and self-issued intermediates by checking issuer signatures. Preserve RSA-PSS signature parameters during GnuTLS verification and keep the original archive for OpenConnect.

Add mutual-TLS regression coverage for certificate bag order and RSA-PSS salt lengths. Verified 53 targeted tests plus gpapi, desktop-core, and iOS compile checks.

* fix: add gateway login diagnostics and scope platform dependencies

* chore: prepare GP Connect 3.3.1 release
2026-11-09 00:51:46 +08:00
Ihar Hrachyshka e03a758acb test: use root for HIP user lookup (#696) 2026-11-06 09:08:48 +08:00
Kevin Yue 16e08c09af Merge pull request #695 from yuezk/fix/aur-srcinfo
fix: build AUR native dependencies without makepkg LTO
2026-11-06 01:28:07 +08:00
Kevin Yue a949b175d4 fix: disable makepkg LTO for mixed Rust and C archives 2026-11-06 01:19:54 +08:00
Kevin Yue 1202ca6c81 fix: synchronize AUR dependency metadata 2026-11-06 01:10:29 +08:00
Kevin Yue 0408bcb67f Merge pull request #694 from yuezk/chore/promote-v3.3.0
chore: promote 3.3.0 sources and Nix packages
2026-11-06 01:08:13 +08:00
Kevin Yue a9474d4059 docs: include complete 3.3.0 release notes 2026-11-06 00:49:58 +08:00
Kevin Yue 5380a5f3c3 release: promote v3.3.0 sources and Nix packages together 2026-11-06 00:49:57 +08:00
Kevin Yue 82c9ba2dcd docs: include Okta FastPass fix in 3.3.0 release notes 2026-11-05 23:33:02 +08:00
177 changed files with 10887 additions and 1025 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Keep source and build scripts consistent on every platform.
* text=auto eol=lf
+186
View File
@@ -0,0 +1,186 @@
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
+27
View File
@@ -42,6 +42,11 @@ on:
required: true required: true
default: false default: false
type: boolean type: boolean
build_windows:
description: 'Build Windows x64 and ARM64 NSH installers'
required: true
default: false
type: boolean
push: push:
paths-ignore: paths-ignore:
- LICENSE - LICENSE
@@ -465,6 +470,24 @@ jobs:
secrets: secrets:
GH_PAT: ${{ secrets.GH_PAT }} 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: nix-source:
needs: [validate-inputs, build-gpgui-glibc] needs: [validate-inputs, build-gpgui-glibc]
strategy: strategy:
@@ -1191,6 +1214,7 @@ jobs:
- build-gpgui-glibc - build-gpgui-glibc
- build-gpgui-musl - build-gpgui-musl
- build-gpgui-nsh - build-gpgui-nsh
- build-windows
- setup-bsd-matrix - setup-bsd-matrix
- build-gpgui-frontend - build-gpgui-frontend
- build-bsd - build-bsd
@@ -1201,6 +1225,7 @@ jobs:
NEEDS_JSON: ${{ toJson(needs) }} NEEDS_JSON: ${{ toJson(needs) }}
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }} BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }} 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: | run: |
python3 - <<'PY' python3 - <<'PY'
import json import json
@@ -1220,6 +1245,8 @@ jobs:
continue continue
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled: elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
continue continue
elif name == "build-windows" and result == "skipped" and os.environ["BUILD_WINDOWS"] != "true":
continue
elif result == "skipped": elif result == "skipped":
failed.append(f"{name}: {result}") failed.append(f"{name}: {result}")
+31 -3
View File
@@ -34,6 +34,10 @@ on:
highlights: highlights:
required: false required: false
type: string type: string
unix_snapshot_build:
description: Verified Unix snapshot build when it differs from the macOS retry
required: false
type: string
unix_platforms: unix_platforms:
required: false required: false
default: linux,freebsd,openbsd default: linux,freebsd,openbsd
@@ -75,6 +79,10 @@ on:
description: Stable release highlights, one per line description: Stable release highlights, one per line
required: false required: false
type: string type: string
unix_snapshot_build:
description: Verified Unix snapshot build; omit when it matches the macOS build
required: false
type: string
unix_platforms: unix_platforms:
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd) description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
required: true required: true
@@ -87,7 +95,8 @@ concurrency:
jobs: jobs:
publish: publish:
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }} # Feed verification runs host tools, so it can use Intel runner capacity.
runs-on: macos-26-intel
environment: macos-release environment: macos-release
permissions: permissions:
contents: write contents: write
@@ -103,6 +112,7 @@ jobs:
SPARKLE_VERSION: 2.9.2 SPARKLE_VERSION: 2.9.2
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }} UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
UNIX_PLATFORMS: ${{ inputs.unix_platforms }} UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
UNIX_SNAPSHOT_BUILD: ${{ inputs.unix_snapshot_build }}
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65 SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
steps: steps:
- name: Validate inputs - name: Validate inputs
@@ -125,6 +135,12 @@ jobs:
echo "unix_platforms must list published Unix targets separated by commas" >&2 echo "unix_platforms must list published Unix targets separated by commas" >&2
exit 1 exit 1
fi 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 if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
echo "The snapshot channel must publish to the snapshot release" >&2 echo "The snapshot channel must publish to the snapshot release" >&2
exit 1 exit 1
@@ -343,6 +359,7 @@ jobs:
echo "short_version=$short_version" >> "$GITHUB_OUTPUT" echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
- name: Prepare Unix update manifest - name: Prepare Unix update manifest
id: unix_manifest
env: env:
RELEASED_AT: ${{ steps.release.outputs.released_at }} RELEASED_AT: ${{ steps.release.outputs.released_at }}
run: | run: |
@@ -383,7 +400,8 @@ jobs:
else else
printf 'Development snapshot after %s.\n' \ printf 'Development snapshot after %s.\n' \
"${{ steps.bundle.outputs.short_version }}" > "$highlights" "${{ steps.bundle.outputs.short_version }}" > "$highlights"
generate_args+=(--build "${{ steps.bundle.outputs.version }}") unix_build="${UNIX_SNAPSHOT_BUILD:-${{ steps.bundle.outputs.version }}}"
generate_args+=(--build "$unix_build")
released_at="$(date -u +%F)" released_at="$(date -u +%F)"
fi fi
@@ -392,6 +410,9 @@ jobs:
--released-at "$released_at" \ --released-at "$released_at" \
--highlights-file "$highlights" \ --highlights-file "$highlights" \
--output "$manifest" --output "$manifest"
if [[ "$CHANNEL" == "snapshot" ]]; then
echo "build=$unix_build" >> "$GITHUB_OUTPUT"
fi
- name: Fetch current appcast - name: Fetch current appcast
id: current-appcast id: current-appcast
@@ -527,6 +548,13 @@ jobs:
--channel "$CHANNEL" \ --channel "$CHANNEL" \
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME" --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 - name: Deploy update feed worker
env: env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
@@ -580,7 +608,7 @@ jobs:
--version "${{ steps.bundle.outputs.short_version }}" --version "${{ steps.bundle.outputs.short_version }}"
) )
if [[ "$CHANNEL" == "snapshot" ]]; then if [[ "$CHANNEL" == "snapshot" ]]; then
expected+=(--build "${{ steps.bundle.outputs.version }}") expected+=(--build "${{ steps.unix_manifest.outputs.build }}")
fi fi
for _ in 1 2 3 4 5 6 7 8 9 10; do for _ in 1 2 3 4 5 6 7 8 9 10; do
if curl --fail --location --silent --show-error \ if curl --fail --location --silent --show-error \
@@ -0,0 +1,162 @@
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" }
}
Generated
+85 -24
View File
@@ -292,11 +292,13 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]] [[package]]
name = "auth" name = "auth"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"block2", "block2",
"browser-launcher", "browser-launcher",
"common",
"dunce",
"gpapi", "gpapi",
"gtk", "gtk",
"html-escape", "html-escape",
@@ -307,6 +309,7 @@ dependencies = [
"objc2-security", "objc2-security",
"objc2-web-kit", "objc2-web-kit",
"regex", "regex",
"serde_json",
"tauri", "tauri",
"tempfile", "tempfile",
"tiny_http", "tiny_http",
@@ -316,6 +319,9 @@ dependencies = [
"uuid", "uuid",
"uzers", "uzers",
"webkit2gtk", "webkit2gtk",
"webview2-com",
"windows",
"winreg 0.55.0",
] ]
[[package]] [[package]]
@@ -547,13 +553,14 @@ dependencies = [
[[package]] [[package]]
name = "browser-launcher" name = "browser-launcher"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"log", "log",
"open", "open",
"webbrowser", "webbrowser",
"which", "which",
"winreg 0.55.0",
] ]
[[package]] [[package]]
@@ -911,7 +918,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"tempfile", "tempfile",
] ]
@@ -1551,7 +1558,7 @@ dependencies = [
"rustc_version", "rustc_version",
"toml 1.1.8+spec-1.1.0", "toml 1.1.8+spec-1.1.0",
"vswhom", "vswhom",
"winreg", "winreg 0.56.0",
] ]
[[package]] [[package]]
@@ -1655,6 +1662,16 @@ dependencies = [
"rustc_version", "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]] [[package]]
name = "filedescriptor" name = "filedescriptor"
version = "0.8.3" version = "0.8.3"
@@ -2115,7 +2132,7 @@ dependencies = [
[[package]] [[package]]
name = "gpapi" name = "gpapi"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.23.1", "base64 0.23.1",
@@ -2124,6 +2141,7 @@ dependencies = [
"chrono", "chrono",
"clap", "clap",
"clap-verbosity-flag", "clap-verbosity-flag",
"cms",
"common", "common",
"directories", "directories",
"dns-lookup", "dns-lookup",
@@ -2142,6 +2160,7 @@ dependencies = [
"oslog", "oslog",
"p12-keystore", "p12-keystore",
"pem", "pem",
"pkcs12",
"pkcs8", "pkcs8",
"pkg-config", "pkg-config",
"proptest", "proptest",
@@ -2149,7 +2168,7 @@ dependencies = [
"reqwest", "reqwest",
"rustls", "rustls",
"rustls-pemfile", "rustls-pemfile",
"sec1", "rustls-platform-verifier",
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
@@ -2167,6 +2186,7 @@ dependencies = [
"uuid", "uuid",
"uzers", "uzers",
"whoami", "whoami",
"windows-sys 0.61.2",
"x509-cert", "x509-cert",
"xmltree", "xmltree",
"zeroize", "zeroize",
@@ -2174,7 +2194,7 @@ dependencies = [
[[package]] [[package]]
name = "gpauth" name = "gpauth"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"auth", "auth",
@@ -2193,7 +2213,7 @@ dependencies = [
[[package]] [[package]]
name = "gpclient" name = "gpclient"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -2224,7 +2244,7 @@ dependencies = [
[[package]] [[package]]
name = "gpgui-helper" name = "gpgui-helper"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -2245,7 +2265,7 @@ dependencies = [
[[package]] [[package]]
name = "gphip" name = "gphip"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"askama", "askama",
@@ -2262,7 +2282,7 @@ dependencies = [
[[package]] [[package]]
name = "gpservice" name = "gpservice"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -2271,6 +2291,7 @@ dependencies = [
"common", "common",
"compile-time", "compile-time",
"env_logger", "env_logger",
"file-rotate",
"futures", "futures",
"getrandom 0.4.3", "getrandom 0.4.3",
"gpapi", "gpapi",
@@ -2291,13 +2312,15 @@ dependencies = [
"tokio-tungstenite 0.30.0", "tokio-tungstenite 0.30.0",
"tokio-util", "tokio-util",
"uuid", "uuid",
"windows-service",
"windows-sys 0.61.2",
"xz2", "xz2",
"zeroize", "zeroize",
] ]
[[package]] [[package]]
name = "gptunnel" name = "gptunnel"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"gpapi", "gpapi",
"log", "log",
@@ -2309,9 +2332,17 @@ dependencies = [
[[package]] [[package]]
name = "gpvpnc" name = "gpvpnc"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"base64 0.23.1",
"ipnet",
"log", "log",
"serde",
"serde_json",
"tempfile",
"uuid",
"windows-sys 0.61.2",
"winreg 0.56.0",
] ]
[[package]] [[package]]
@@ -2813,6 +2844,9 @@ name = "ipnet"
version = "2.12.2" version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "is-docker" name = "is-docker"
@@ -3823,7 +3857,7 @@ dependencies = [
[[package]] [[package]]
name = "openconnect" name = "openconnect"
version = "3.3.0" version = "3.4.0"
dependencies = [ dependencies = [
"autotools", "autotools",
"cc", "cc",
@@ -3833,6 +3867,7 @@ dependencies = [
"log", "log",
"pkg-config", "pkg-config",
"tempfile", "tempfile",
"windows-sys 0.61.2",
] ]
[[package]] [[package]]
@@ -4880,16 +4915,6 @@ dependencies = [
"sha2 0.11.1", "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]] [[package]]
name = "security-framework" name = "security-framework"
version = "3.7.0" version = "3.7.0"
@@ -6738,6 +6763,12 @@ dependencies = [
"web-sys", "web-sys",
] ]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"
@@ -6888,6 +6919,17 @@ dependencies = [
"windows-link", "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]] [[package]]
name = "windows-strings" name = "windows-strings"
version = "0.5.1" version = "0.5.1"
@@ -6915,6 +6957,15 @@ dependencies = [
"windows-targets 0.52.6", "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]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.61.2" version = "0.61.2"
@@ -7081,6 +7132,16 @@ dependencies = [
"memchr", "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]] [[package]]
name = "winreg" name = "winreg"
version = "0.56.0" version = "0.56.0"
+1 -2
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package] [workspace.package]
rust-version = "1.91" rust-version = "1.91"
version = "3.3.0" version = "3.4.0"
authors = ["Kevin Yue <[email protected]>"] authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect" homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024" edition = "2024"
@@ -24,7 +24,6 @@ base64 = { version = "0.23", default-features = false, features = ["std"] }
chrono = "0.4" chrono = "0.4"
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3" clap-verbosity-flag = "3"
ctrlc = "3.4"
directories = "6.0" directories = "6.0"
dns-lookup = "4.0.2" dns-lookup = "4.0.2"
env_logger = "0.11" env_logger = "0.11"
+3
View File
@@ -16,6 +16,9 @@ fn main() {
resolve_commit(&repo_root, &source_commit) 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")] #[cfg(feature = "webview-auth")]
tauri_build::build() tauri_build::build()
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

+6 -6
View File
@@ -1,8 +1,8 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use auth::forward_auth_callback; use auth::forward_auth_callback;
use auth::{BrowserAuthenticator, auth_prelogin}; use auth::{BrowserAuthenticator, auth_prelogin};
use clap::Parser; use clap::Parser;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use clap::Subcommand; use clap::Subcommand;
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
use gpapi::auth::AuthWindowTheme; use gpapi::auth::AuthWindowTheme;
@@ -49,7 +49,7 @@ See 'gpauth -h' for more information.
" "
)] )]
struct Cli { struct Cli {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[command(subcommand)] #[command(subcommand)]
command: Option<CliCommand>, command: Option<CliCommand>,
@@ -134,7 +134,7 @@ struct Cli {
verbose: InfoLevelVerbosity, verbose: InfoLevelVerbosity,
} }
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[derive(Subcommand)] #[derive(Subcommand)]
enum CliCommand { enum CliCommand {
#[command(hide = true)] #[command(hide = true)]
@@ -272,7 +272,7 @@ fn init_logger(cli: &Cli) {
pub async fn run() { pub async fn run() {
let cli = Cli::parse(); let cli = Cli::parse();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if let Some(CliCommand::AuthCallback { callback }) = &cli.command { if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
if let Err(err) = forward_auth_callback(callback).await { if let Err(err) = forward_auth_callback(callback).await {
eprintln!("Failed to forward authentication callback: {err}"); eprintln!("Failed to forward authentication callback: {err}");
@@ -382,7 +382,7 @@ mod tests {
} }
#[test] #[test]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn callback_arguments_parse_separately() { fn callback_arguments_parse_separately() {
let cli = Cli::try_parse_from([ let cli = Cli::try_parse_from([
"gpauth", "gpauth",
+5
View File
@@ -0,0 +1,5 @@
{
"bundle": {
"icon": ["icons/windows/icon.ico"]
}
}
+29
View File
@@ -0,0 +1,29 @@
#![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"));
}
+59
View File
@@ -511,3 +511,62 @@ 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"
);
}
}
+2 -3
View File
@@ -785,9 +785,8 @@ mod tests {
#[test] #[test]
fn explicit_hip_user_resolves_to_the_selected_account() { fn explicit_hip_user_resolves_to_the_selected_account() {
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap(); // Build sandboxes may use a UID without an entry in the user database.
let name = current.name().to_string_lossy().into_owned(); assert_eq!(get_uid(&Some("root".to_string())).unwrap(), Some(0));
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
} }
#[test] #[test]
+8 -2
View File
@@ -186,6 +186,8 @@ impl<'a> ConnectHandler<'a> {
match identity_error { match identity_error {
RequestIdentityError::UnsupportedEncryption RequestIdentityError::UnsupportedEncryption
| RequestIdentityError::UnsupportedKeyFormat | RequestIdentityError::UnsupportedKeyFormat
| RequestIdentityError::UnsupportedKeyAlgorithm(_)
| RequestIdentityError::KeyMismatch
| RequestIdentityError::InvalidKey | RequestIdentityError::InvalidKey
| RequestIdentityError::InvalidCertificate | RequestIdentityError::InvalidCertificate
| RequestIdentityError::IncompletePkcs12 | RequestIdentityError::IncompletePkcs12
@@ -206,8 +208,12 @@ impl<'a> ConnectHandler<'a> {
return Ok(()); return Ok(());
} }
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => { RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
let message = format!("Enter the {} passphrase:", cert_type); let message = if *cert_type == "PKCS#12" {
let password = Password::new(&message) "Enter the certificate file password:"
} else {
"Enter the private key password:"
};
let password = Password::new(message)
.without_confirmation() .without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked) .with_display_mode(PasswordDisplayMode::Masked)
.prompt()?; .prompt()?;
+12 -2
View File
@@ -30,14 +30,24 @@ uuid = { workspace = true, features = ["v4"] }
zeroize.workspace = true zeroize.workspace = true
tempfile.workspace = true tempfile.workspace = true
getrandom = "0.4" getrandom = "0.4"
mac_address = "1.2.1"
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "socket", "user"] } 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] [dev-dependencies]
openssl.workspace = true openssl.workspace = true
tokio-tungstenite.workspace = true tokio-tungstenite.workspace = true
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(any(target_os = "macos", windows))'.dependencies]
gpvpnc = { path = "../../crates/gpvpnc" } 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"] }
+3 -10
View File
@@ -6,7 +6,7 @@ use std::time::Duration;
use anyhow::{Context, bail}; use anyhow::{Context, bail};
use clap::Parser; use clap::Parser;
use common::constants::GP_SERVICE_LOCK_FILE; use common::paths::service_lock_file;
use gpapi::clap::InfoLevelVerbosity; use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger; use gpapi::logger;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@@ -25,14 +25,7 @@ use crate::{
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer, request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
}; };
const VERSION: &str = concat!( use crate::VERSION;
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
struct RedactingMacosLogger { struct RedactingMacosLogger {
@@ -271,7 +264,7 @@ impl Cli {
return Ok(dev_service_lock_file_path(socket)); return Ok(dev_service_lock_file_path(socket));
} }
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE)) Ok(service_lock_file())
} }
fn init_logger(&self) -> Arc<Redaction> { fn init_logger(&self) -> Arc<Redaction> {
+12
View File
@@ -0,0 +1,12 @@
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))
}
+2 -5
View File
@@ -75,7 +75,7 @@ impl DesktopClient {
loop { loop {
match self.read_control().await? { match self.read_control().await? {
Some(DESKTOP_GUI_INSTALLER) => { Some(DESKTOP_GUI_INSTALLER) => {
self.write_all(&[u8::from(crate::request_dispatcher::gui_installer().is_some())]).await?; self.write_all(&[u8::from(crate::gui_installation::installer().is_some())]).await?;
} }
Some(DESKTOP_SWITCH_BEGIN) => { Some(DESKTOP_SWITCH_BEGIN) => {
ensure!(pending.is_none(), "A GUI switch is already pending"); ensure!(pending.is_none(), "A GUI switch is already pending");
@@ -299,10 +299,7 @@ mod tests {
let mut reader = reader; let mut reader = reader;
let mut capability = [0]; let mut capability = [0];
reader.read_exact(&mut capability).unwrap(); reader.read_exact(&mut capability).unwrap();
assert_eq!( assert_eq!(capability[0], u8::from(crate::gui_installation::installer().is_some()));
capability[0],
u8::from(crate::request_dispatcher::gui_installer().is_some())
);
reader reader
}) })
.await .await
+1 -1
View File
@@ -366,7 +366,7 @@ mod tests {
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"# r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
); );
for source in [0, 4] { for source in [0, u8::MAX] {
let json = serde_json::json!({ let json = serde_json::json!({
"version": 1, "version": 1,
"anchor": { "anchor": {
+359
View File
@@ -0,0 +1,359 @@
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")));
}
}
}
+19 -41
View File
@@ -1,4 +1,4 @@
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc}; use std::{io, sync::Arc};
use anyhow::{Context, ensure}; use anyhow::{Context, ensure};
use gpapi::{ use gpapi::{
@@ -6,7 +6,17 @@ use gpapi::{
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder}, os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
}; };
use gphip::{ReportContext, ReportInput}; use gphip::{ReportContext, ReportInput};
use openconnect::{HipRequest, HipScript, HipScriptEnvironment}; 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;
pub(crate) struct HipExecution { pub(crate) struct HipExecution {
pub source: openconnect::HipSource, pub source: openconnect::HipSource,
@@ -36,7 +46,7 @@ impl HipApproval {
pub(crate) fn resolve( pub(crate) fn resolve(
source: &HipSource, source: &HipSource,
desktop_uid: Option<u32>, desktop_uid: Option<u32>,
brokered_macos: bool, restricted_desktop: bool,
edited_report: Option<Arc<str>>, edited_report: Option<Arc<str>>,
profile: Option<OsProfile>, profile: Option<OsProfile>,
) -> anyhow::Result<HipExecution> { ) -> anyhow::Result<HipExecution> {
@@ -63,22 +73,11 @@ pub(crate) fn resolve(
} }
HipSource::UserScript { path } => { HipSource::UserScript { path } => {
approval = None; approval = None;
ensure_custom_available(brokered_macos)?; ensure_custom_available(restricted_desktop)?;
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?; scripts::user_script(path, desktop_uid)?
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 } => { HipSource::ApprovedRootScript { approval_id } => {
ensure_custom_available(brokered_macos)?; ensure_custom_available(restricted_desktop)?;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[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")?; let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
@@ -113,10 +112,10 @@ pub(crate) fn resolve(
}) })
} }
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> { fn ensure_custom_available(restricted_desktop: bool) -> anyhow::Result<()> {
ensure!( ensure!(
!cfg!(target_os = "macos") && !brokered_macos, !cfg!(target_os = "macos") && !restricted_desktop,
"Custom HIP scripts are unavailable on macOS" "Custom HIP scripts are unavailable on this platform"
); );
Ok(()) Ok(())
} }
@@ -149,27 +148,6 @@ 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( pub(crate) fn profile(
identity: &HostIdentity, identity: &HostIdentity,
os: ClientOs, os: ClientOs,
+37
View File
@@ -0,0 +1,37 @@
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,
})
}
+3
View File
@@ -0,0 +1,3 @@
pub(super) fn user_script(_path: &str, _desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
anyhow::bail!("Custom HIP scripts are unavailable on Windows")
}
+30 -1
View File
@@ -1,11 +1,15 @@
#[cfg_attr(windows, path = "cli/windows.rs")]
mod cli; mod cli;
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))] #[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
mod credential_lease; mod credential_lease;
#[cfg(unix)]
mod desktop_client; mod desktop_client;
#[cfg(debug_assertions)] #[cfg(all(debug_assertions, unix))]
mod dev_bootstrap; mod dev_bootstrap;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
mod device_anchor; mod device_anchor;
#[cfg(unix)]
mod gui_installation;
mod handlers; mod handlers;
mod hip_preview; mod hip_preview;
mod hip_source; mod hip_source;
@@ -13,6 +17,7 @@ mod hip_source;
mod macos_broker; mod macos_broker;
mod request_dispatcher; mod request_dispatcher;
mod routes; mod routes;
#[cfg(unix)]
mod runtime_user; mod runtime_user;
mod session_registry; mod session_registry;
mod vpn_script; mod vpn_script;
@@ -20,7 +25,31 @@ mod vpn_task;
mod ws_connection; mod ws_connection;
mod ws_server; 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] #[tokio::main]
async fn main() { async fn main() {
cli::run().await; 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
}
}
}
+30 -376
View File
@@ -1,27 +1,15 @@
use std::{ use std::sync::{Arc, atomic::AtomicBool};
fs::{self, File, OpenOptions, Permissions},
io::{BufReader, Read, Write},
os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::Path,
sync::{Arc, atomic::AtomicBool},
};
use gpapi::{ use gpapi::{
service::{ service::{
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest}, request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
transport::{ServiceErrorCode, ServiceResult}, transport::{ServiceErrorCode, ServiceResult},
}, },
utils::{checksum::verify_checksum, redact::Redaction}, utils::redact::Redaction,
}; };
use log::{info, warn}; use log::{info, warn};
use tar::Archive; #[cfg(unix)]
use tempfile::NamedTempFile;
use tokio::sync::Mutex; 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(crate) struct SessionAuthority {
pub registry: Arc<crate::session_registry::SessionRegistry>, pub registry: Arc<crate::session_registry::SessionRegistry>,
@@ -75,9 +63,10 @@ pub struct RequestDispatcher {
lifecycle: crate::vpn_task::LifecycleHandle, lifecycle: crate::vpn_task::LifecycleHandle,
gui_restart_requested: Arc<AtomicBool>, gui_restart_requested: Arc<AtomicBool>,
redaction: Arc<Redaction>, redaction: Arc<Redaction>,
#[cfg(unix)]
install_lock: Mutex<()>, install_lock: Mutex<()>,
gui_management_enabled: bool, gui_management_enabled: bool,
externally_brokered: bool, restricted_desktop: bool,
} }
impl RequestDispatcher { impl RequestDispatcher {
@@ -89,15 +78,16 @@ impl RequestDispatcher {
gui_restart_requested: Arc<AtomicBool>, gui_restart_requested: Arc<AtomicBool>,
redaction: Arc<Redaction>, redaction: Arc<Redaction>,
gui_management_enabled: bool, gui_management_enabled: bool,
externally_brokered: bool, restricted_desktop: bool,
) -> Self { ) -> Self {
Self { Self {
lifecycle, lifecycle,
gui_restart_requested, gui_restart_requested,
redaction, redaction,
#[cfg(unix)]
install_lock: Mutex::new(()), install_lock: Mutex::new(()),
gui_management_enabled, gui_management_enabled,
externally_brokered, restricted_desktop,
} }
} }
@@ -202,7 +192,7 @@ impl RequestDispatcher {
edited_report, edited_report,
} => { } => {
let prepared = let prepared =
crate::vpn_task::prepare_connection(*request, self.externally_brokered, preparation.cancellation()).await; crate::vpn_task::prepare_connection(*request, self.restricted_desktop, preparation.cancellation()).await;
return match prepared { return match prepared {
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report), Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
Err(error) => { Err(error) => {
@@ -279,24 +269,25 @@ impl RequestDispatcher {
} }
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> { fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
if !self.externally_brokered { if !self.restricted_desktop {
return Ok(()); return Ok(());
} }
if request.args().vpnc_script().is_some() { if request.args().vpnc_script().is_some() {
return Err("macOS does not support custom VPN scripts"); return Err("Custom VPN scripts are unavailable on this platform");
} }
if matches!( if matches!(
request.args().hip_source(), request.args().hip_source(),
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. } gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
) { ) {
return Err("macOS does not support custom HIP scripts"); return Err("Custom HIP scripts are unavailable on this platform");
} }
if request.args().certificate().is_some() || request.args().sslkey().is_some() { if request.args().certificate().is_some() || request.args().sslkey().is_some() {
return Err("macOS client identity must be provided as protected data, not root-readable paths"); return Err("Client identity must be provided as certificate data");
} }
Ok(()) Ok(())
} }
#[cfg(unix)]
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult { async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") { if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
return ServiceResult::rejected( return ServiceResult::rejected(
@@ -308,14 +299,17 @@ impl RequestDispatcher {
let path = request.path; let path = request.path;
let checksum = request.checksum; let checksum = request.checksum;
let target = request.variant.update_target(); let target = request.variant.update_target();
let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await; let installed = tokio::task::spawn_blocking(move || {
crate::gui_installation::install(std::path::Path::new(&path), &checksum, &target)
})
.await;
match installed { match installed {
Ok(Ok(())) => ServiceResult::Accepted, Ok(Ok(())) => ServiceResult::Accepted,
Ok(Err(GuiInstallError::Checksum(err))) => { Ok(Err(crate::gui_installation::InstallError::Checksum(err))) => {
warn!("Failed to verify GUI update checksum: {err}"); warn!("Failed to verify GUI update checksum: {err}");
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed") ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
} }
Ok(Err(GuiInstallError::Install(err))) => { Ok(Err(crate::gui_installation::InstallError::Install(err))) => {
warn!("Failed to install GUI update: {err}"); warn!("Failed to install GUI update: {err}");
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed") ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
} }
@@ -325,335 +319,20 @@ impl RequestDispatcher {
} }
} }
} }
} #[cfg(windows)]
async fn update_gui(&self, _request: UpdateGuiRequest) -> ServiceResult {
#[derive(Debug)] ServiceResult::rejected(
enum GuiInstallError { ServiceErrorCode::InvalidRequest,
Checksum(anyhow::Error), "Use the Windows installer to update GP Connect",
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)] #[cfg(test)]
mod tests { mod tests {
use crate::vpn_task::test_connect_request as test_request;
use std::{io::Cursor, os::unix::fs::PermissionsExt};
use gpapi::{
gateway::Gateway,
service::transport::{ServiceErrorCode, ServiceResult},
};
use tar::{Builder, EntryType, Header};
use xz2::write::XzEncoder;
use super::*; use super::*;
use crate::vpn_task::test_connect_request as test_request;
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> { use gpapi::gateway::Gateway;
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] #[tokio::test]
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() { async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
let dispatcher = RequestDispatcher::new( let dispatcher = RequestDispatcher::new(
@@ -700,7 +379,7 @@ mod tests {
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string())); let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
assert_eq!( assert_eq!(
dispatcher.validate_connect_request(&custom), dispatcher.validate_connect_request(&custom),
Err("macOS does not support custom VPN scripts") Err("Custom VPN scripts are unavailable on this platform")
); );
} }
@@ -709,32 +388,7 @@ mod tests {
}); });
assert_eq!( assert_eq!(
dispatcher.validate_connect_request(&custom), dispatcher.validate_connect_request(&custom),
Err("macOS does not support custom HIP scripts") Err("Custom HIP scripts are unavailable on this platform")
); );
} }
#[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")));
}
}
} }
+36
View File
@@ -62,6 +62,8 @@ enum SessionStatus {
} }
struct SessionRecord { struct SessionRecord {
#[cfg(windows)]
windows_identity: Option<Arc<gpapi::windows::PipeClientIdentity>>,
non_tunnel: Option<AttachmentAttempt>, non_tunnel: Option<AttachmentAttempt>,
closed_attachment: Option<Uuid>, closed_attachment: Option<Uuid>,
secret: Zeroizing<[u8; 32]>, secret: Zeroizing<[u8; 32]>,
@@ -255,6 +257,8 @@ impl SessionRegistry {
sessions.insert( sessions.insert(
credential.session_id(), credential.session_id(),
SessionRecord { SessionRecord {
#[cfg(windows)]
windows_identity: None,
non_tunnel: None, non_tunnel: None,
closed_attachment: None, closed_attachment: None,
secret: Zeroizing::new(*credential.secret()), secret: Zeroizing::new(*credential.secret()),
@@ -273,6 +277,38 @@ impl SessionRegistry {
Ok(credential) 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")] #[cfg(target_os = "macos")]
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
let Ok(mut sessions) = self.sessions.lock() else { let Ok(mut sessions) = self.sessions.lock() else {
+7 -1
View File
@@ -1,6 +1,9 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[path = "privileged_unix.rs"] #[path = "privileged_unix.rs"]
mod platform; mod platform;
#[cfg(windows)]
#[path = "windows.rs"]
mod platform;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
#[path = "macos.rs"] #[path = "macos.rs"]
mod platform; mod platform;
@@ -8,7 +11,8 @@ mod platform;
target_os = "linux", target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "openbsd", target_os = "openbsd",
target_os = "macos" target_os = "macos",
windows
)))] )))]
#[path = "default.rs"] #[path = "default.rs"]
mod platform; mod platform;
@@ -16,3 +20,5 @@ mod platform;
mod selection; mod selection;
pub(crate) use platform::builder; pub(crate) use platform::builder;
#[cfg(windows)]
pub(crate) use platform::recover_network;
+24
View File
@@ -0,0 +1,24 @@
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)
}),
)
}
+5 -4
View File
@@ -126,6 +126,7 @@ impl LifecycleHandle {
ServiceResult::Accepted ServiceResult::Accepted
} }
#[cfg(any(unix, test))]
pub async fn disconnect_and_wait(&self) -> bool { pub async fn disconnect_and_wait(&self) -> bool {
let completion = { let completion = {
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned"); let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
@@ -447,7 +448,7 @@ pub(crate) struct VpnTask {
events: mpsc::Receiver<LifecycleEvent>, events: mpsc::Receiver<LifecycleEvent>,
lifecycle: LifecycleHandle, lifecycle: LifecycleHandle,
vpn_state_tx: watch::Sender<VpnState>, vpn_state_tx: watch::Sender<VpnState>,
brokered_macos: bool, restricted_desktop: bool,
registry: Arc<crate::session_registry::SessionRegistry>, registry: Arc<crate::session_registry::SessionRegistry>,
active: Option<ActiveAttempt>, active: Option<ActiveAttempt>,
cancel_token: CancellationToken, cancel_token: CancellationToken,
@@ -456,7 +457,7 @@ pub(crate) struct VpnTask {
impl VpnTask { impl VpnTask {
pub fn new( pub fn new(
vpn_state_tx: watch::Sender<VpnState>, vpn_state_tx: watch::Sender<VpnState>,
brokered_macos: bool, restricted_desktop: bool,
registry: Arc<crate::session_registry::SessionRegistry>, registry: Arc<crate::session_registry::SessionRegistry>,
) -> (Self, LifecycleHandle) { ) -> (Self, LifecycleHandle) {
let (events_tx, events) = mpsc::channel(4); let (events_tx, events) = mpsc::channel(4);
@@ -470,7 +471,7 @@ impl VpnTask {
events, events,
lifecycle: lifecycle.clone(), lifecycle: lifecycle.clone(),
vpn_state_tx, vpn_state_tx,
brokered_macos, restricted_desktop,
registry, registry,
active: None, active: None,
cancel_token: CancellationToken::new(), cancel_token: CancellationToken::new(),
@@ -617,7 +618,7 @@ impl VpnTask {
desktop_uid, desktop_uid,
edited_report, edited_report,
session_id, session_id,
brokered_macos: self.brokered_macos, restricted_desktop: self.restricted_desktop,
registry: self.registry.clone(), registry: self.registry.clone(),
lifecycle: self.lifecycle.clone(), lifecycle: self.lifecycle.clone(),
}, },
+12 -7
View File
@@ -30,7 +30,7 @@ pub(super) struct ConnectionResources {
/// the complete ledger and its retained identity resources to the service. /// the complete ledger and its retained identity resources to the service.
pub(crate) async fn prepare_connection( pub(crate) async fn prepare_connection(
request: ConnectRequest, request: ConnectRequest,
brokered_macos: bool, restricted_desktop: bool,
cancellation: CancellationToken, cancellation: CancellationToken,
) -> anyhow::Result<PreparedConnection> { ) -> anyhow::Result<PreparedConnection> {
let mode = request.args().packet_delivery().clone(); let mode = request.args().packet_delivery().clone();
@@ -77,11 +77,16 @@ pub(crate) async fn prepare_connection(
}; };
check()?; check()?;
let args = setup_request.args(); let args = setup_request.args();
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?; let identity = super::prepare_identity(args, restricted_desktop || non_tunnel)?;
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui")); #[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_files = identity let identity_files = identity
.as_ref() .as_ref()
.map(|identity| identity.write_files(directory)) .map(|identity| identity.write_files(directory.as_deref()))
.transpose()?; .transpose()?;
let host = args.host_identity().context("Authenticated host identity is missing")?; let host = args.host_identity().context("Authenticated host identity is missing")?;
let profile = crate::hip_source::profile( let profile = crate::hip_source::profile(
@@ -181,8 +186,8 @@ mod tests {
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo}; use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
#[tokio::test] #[tokio::test]
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() { async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() {
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] { for (restricted_desktop, non_tunnel) in [(true, false), (false, true), (true, true)] {
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into()); 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![])) let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
.with_certificate(Some("/identity.pem".into())); .with_certificate(Some("/identity.pem".into()));
@@ -192,7 +197,7 @@ mod tests {
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal"); wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
} }
let request = serde_json::from_value(wire).unwrap(); let request = serde_json::from_value(wire).unwrap();
let error = prepare_connection(request, brokered_macos, CancellationToken::new()) let error = prepare_connection(request, restricted_desktop, CancellationToken::new())
.await .await
.err() .err()
.unwrap(); .unwrap();
+12 -8
View File
@@ -20,7 +20,7 @@ pub(super) struct AttemptInput {
pub desktop_uid: Option<u32>, pub desktop_uid: Option<u32>,
pub edited_report: Option<Arc<str>>, pub edited_report: Option<Arc<str>>,
pub session_id: Option<Uuid>, pub session_id: Option<Uuid>,
pub brokered_macos: bool, pub restricted_desktop: bool,
pub registry: Arc<crate::session_registry::SessionRegistry>, pub registry: Arc<crate::session_registry::SessionRegistry>,
pub lifecycle: LifecycleHandle, pub lifecycle: LifecycleHandle,
} }
@@ -31,6 +31,7 @@ struct TunnelInput {
source: Arc<openconnect::HipSource>, source: Arc<openconnect::HipSource>,
session_id: Option<Uuid>, session_id: Option<Uuid>,
registry: Arc<crate::session_registry::SessionRegistry>, registry: Arc<crate::session_registry::SessionRegistry>,
#[cfg(unix)]
desktop_uid: Option<u32>, desktop_uid: Option<u32>,
} }
@@ -55,7 +56,7 @@ pub(super) fn spawn(
let request = input.connection.request.clone(); let request = input.connection.request.clone();
let resources = input.connection.resources.clone(); let resources = input.connection.resources.clone();
let desktop_uid = input.desktop_uid; let desktop_uid = input.desktop_uid;
let brokered = input.brokered_macos; let brokered = input.restricted_desktop;
let edited = input.edited_report.clone(); let edited = input.edited_report.clone();
let setup_cancel = cancellation.clone(); let setup_cancel = cancellation.clone();
let execution = tokio::task::spawn_blocking(move || { let execution = tokio::task::spawn_blocking(move || {
@@ -105,6 +106,7 @@ pub(super) fn spawn(
source, source,
session_id: input.session_id, session_id: input.session_id,
registry: input.registry.clone(), registry: input.registry.clone(),
#[cfg(unix)]
desktop_uid: input.desktop_uid, desktop_uid: input.desktop_uid,
}; };
input.connection.request.release_script_tun_bootstrap(); input.connection.request.release_script_tun_bootstrap();
@@ -253,12 +255,14 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
), ),
gpapi::script_tun::PacketDelivery::ScriptTun(request) => { gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session"); ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
let (builder, script_tun) = super::script_tun::builder( #[cfg(unix)]
member.gateway.server(), let owner = input.desktop_uid.context("Desktop identity is unavailable")?;
member.authentication.cookie(), #[cfg(windows)]
request, let owner = input
input.desktop_uid.context("Desktop identity is unavailable")?, .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)?;
(builder, Some(script_tun)) (builder, Some(script_tun))
} }
}; };
+145 -125
View File
@@ -1,40 +1,19 @@
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller. //! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
use super::{LifecycleEvent, LifecycleHandle}; use super::{LifecycleEvent, LifecycleHandle};
use anyhow::{Context, bail, ensure}; use anyhow::{Context, bail, ensure};
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message}; use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message};
use openconnect::{Vpn, VpnBuilder, tunnel::Event}; use openconnect::{Vpn, tunnel::Event};
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use tokio::{net::UnixStream, sync::mpsc, time::Instant}; use tokio::{sync::mpsc, time::Instant};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
pub(super) struct PreparedScriptTun { #[cfg(unix)]
pub control: std::os::unix::net::UnixStream, #[path = "script_tun/unix.rs"]
pub bootstrap: Bootstrap, mod platform;
} #[cfg(windows)]
#[path = "script_tun/windows.rs"]
pub(super) fn builder( mod platform;
server: &str, pub(super) use platform::{PreparedScriptTun, builder};
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)] #[derive(Debug)]
pub(super) struct NetworkChanged; pub(super) struct NetworkChanged;
@@ -53,7 +32,7 @@ enum Native {
pub(super) async fn run( pub(super) async fn run(
identity: Identity, identity: Identity,
vpn: Arc<Vpn>, vpn: Arc<Vpn>,
prepared: PreparedScriptTun, mut prepared: PreparedScriptTun,
approval: &crate::hip_source::HipApproval, approval: &crate::hip_source::HipApproval,
lifecycle: &LifecycleHandle, lifecycle: &LifecycleHandle,
cancellation: CancellationToken, cancellation: CancellationToken,
@@ -62,6 +41,8 @@ pub(super) async fn run(
registry: Arc<crate::session_registry::SessionRegistry>, registry: Arc<crate::session_registry::SessionRegistry>,
sessions: &mut gpapi::session::desktop::GatewaySessions, sessions: &mut gpapi::session::desktop::GatewaySessions,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let channel = prepared.connect().await?;
let mut control = ConsumerControl::new(channel);
let attempt = identity.attempt; let attempt = identity.attempt;
let (native_tx, native) = mpsc::channel(64); let (native_tx, native) = mpsc::channel(64);
let observed = native_tx.clone(); let observed = native_tx.clone();
@@ -77,7 +58,7 @@ pub(super) async fn run(
monitor: monitor.clone(), monitor: monitor.clone(),
}) })
.await; .await;
if event_result.is_err() { if event_result.is_err() || cancellation.is_cancelled() {
monitor.stop().await; monitor.stop().await;
return Ok(()); return Ok(());
} }
@@ -91,31 +72,50 @@ pub(super) async fn run(
tokio::pin!(worker); tokio::pin!(worker);
let mut worker_done = false; let mut worker_done = false;
let stop = cancellation.child_token(); let stop = cancellation.child_token();
let supervisor = supervise(identity, prepared, native, stop.clone(), events); let result = {
tokio::pin!(supervisor); let supervisor = supervise(
let mut supervisor_done = false; identity,
let mut approval_poll = tokio::time::interval(Duration::from_millis(250)); &mut control,
let result = loop { std::mem::take(&mut prepared.bootstrap),
tokio::select! { native,
biased; stop.clone(),
result = &mut supervisor => { supervisor_done = true; break result; } events,
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); } );
_ = approval_poll.tick() => { tokio::pin!(supervisor);
if !approval.approval_is_valid() || !registry.has_session(session_id) { let mut supervisor_done = false;
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation); 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
}; };
stop.cancel(); control.stop().await;
if !supervisor_done { let cleanup = prepared.stop_worker();
let _ = supervisor.await;
}
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
monitor.stop().await; monitor.stop().await;
if result.is_ok() {
cleanup?;
} else if let Err(error) = cleanup {
log::warn!("Could not stop packet worker: {error:#}");
}
result result
} }
@@ -128,93 +128,113 @@ enum WorkerState {
Suspending, Suspending,
} }
// The same control loop runs against native observations in production and a // Own the channel independently of its supervision future so run() can drain
// generic socket consumer in tests; VPN ownership stays in run(). // 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.
async fn supervise( async fn supervise(
identity: Identity, identity: Identity,
mut prepared: PreparedScriptTun, control: &mut ConsumerControl,
mut bootstrap: Bootstrap,
mut native: mpsc::Receiver<Native>, mut native: mpsc::Receiver<Native>,
cancellation: CancellationToken, cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>, events: mpsc::Sender<LifecycleEvent>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let attempt = identity.attempt; let attempt = identity.attempt;
prepared.control.set_nonblocking(true)?; let ConsumerControl { output, messages, .. } = control;
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 network = None;
let mut session = None; let mut session = None;
let mut worker = WorkerState::Preparing; let mut worker = WorkerState::Preparing;
let mut online = false; let mut online = false;
let mut was_connected = false; let mut was_connected = false;
let mut deadline: Option<Instant> = None; let mut deadline: Option<Instant> = None;
let result = async { loop {
loop { tokio::select! {
tokio::select! { biased;
biased; _ = cancellation.cancelled() => break,
_ = 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"),
_ = 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 = messages.recv() => match message.context("Script-tun control reader stopped")?? { Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => { worker = WorkerState::Ready;
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(&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(_) => {},
} }
} Message::Activated if worker == WorkerState::Activating => {
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() { ensure!(online, "Script-tun activation completed while VPN was offline");
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating; ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
deadline = Some(Instant::now() + Duration::from_secs(10)); 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));
}
}
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));
}
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
} }
} }
Ok(()) if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
}.await; send(output, &Message::Activate).await?;
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await; worker = WorkerState::Activating;
drop(output); deadline = Some(Instant::now() + Duration::from_secs(10));
reader.abort(); }
let _ = reader.await; }
result Ok(())
} }
fn observed_network( fn observed_network(
@@ -243,5 +263,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa
Ok(()) Ok(())
} }
#[cfg(test)] #[cfg(all(test, unix))]
mod tests; mod tests;
@@ -1,6 +1,8 @@
use super::*; use super::*;
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
use openconnect::{VpnSessionInfo, tunnel::Configuration}; use openconnect::{VpnSessionInfo, tunnel::Configuration};
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use tokio::net::UnixStream;
// A generic consumer, with no proxy settings or private worker protocol. // A generic consumer, with no proxy settings or private worker protocol.
struct Consumer { struct Consumer {
@@ -23,16 +25,26 @@ impl Consumer {
launch_id: uuid::Uuid::new_v4(), launch_id: uuid::Uuid::new_v4(),
}; };
let cancel = CancellationToken::new(); let cancel = CancellationToken::new();
let task = tokio::spawn(supervise( let stopped = cancel.clone();
identity, let task = tokio::spawn(async move {
PreparedScriptTun { let mut prepared = PreparedScriptTun {
control, control: Some(control),
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(), bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
}, };
observations, let channel = prepared.connect().await?;
cancel.clone(), let mut control = ConsumerControl::new(channel);
events, let result = supervise(
)); identity,
&mut control,
prepared.bootstrap,
observations,
stopped,
events,
)
.await;
control.stop().await;
result
});
Self { Self {
control: UnixStream::from_std(child).unwrap(), control: UnixStream::from_std(child).unwrap(),
native, native,
@@ -291,3 +303,36 @@ async fn reconnect_during_activation_returns_clear_error_without_connected() {
); );
assert!(consumer.events.try_recv().is_err()); 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());
}
@@ -0,0 +1,44 @@
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(())
}
}
@@ -0,0 +1,69 @@
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()?)
}
}
@@ -0,0 +1,92 @@
//! 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(())
}
@@ -0,0 +1,72 @@
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());
}
}
+159
View File
@@ -0,0 +1,159 @@
//! 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(())
}
+1
View File
@@ -344,6 +344,7 @@ impl WsServer {
} }
} }
#[cfg(unix)]
pub fn context(&self) -> Arc<WsServerContext> { pub fn context(&self) -> Arc<WsServerContext> {
Arc::clone(&self.ctx) Arc::clone(&self.ctx)
} }
+34
View File
@@ -1,5 +1,38 @@
# Changelog # 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 ## 3.3.0
### Added ### Added
@@ -22,6 +55,7 @@
- Fixed server addresses losing custom ports when pasted as URLs. - Fixed server addresses losing custom ports when pasted as URLs.
- Fixed gateway login address handling for servers with explicit ports. - 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 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 supplied server certificate pins not being enforced during tunnel setup.
- Fixed delayed clicks activating a different control after a Native Shell view changed. - Fixed delayed clicks activating a different control after a Native Shell view changed.
+16 -1
View File
@@ -20,7 +20,6 @@ browser-launcher = { path = "../browser-launcher", default-features = false, fea
tiny_http = { version = "0.12", optional = true } tiny_http = { version = "0.12", optional = true }
tempfile = { workspace = true, optional = true } tempfile = { workspace = true, optional = true }
uuid = { version = "1", optional = true, features = ["v4"] } uuid = { version = "1", optional = true, features = ["v4"] }
uzers = { workspace = true, optional = true }
# Webview auth dependencies # Webview auth dependencies
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
@@ -28,6 +27,7 @@ regex = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true } tokio-util = { workspace = true, optional = true }
html-escape = { version = "0.3", optional = true } html-escape = { version = "0.3", optional = true }
url = { workspace = true, 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] [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
webkit2gtk = { version = "2", optional = true } webkit2gtk = { version = "2", optional = true }
@@ -60,6 +60,9 @@ webview-auth = [
"dep:tokio-util", "dep:tokio-util",
"dep:html-escape", "dep:html-escape",
"dep:url", "dep:url",
"dep:serde_json",
"dep:webview2-com",
"dep:windows",
"dep:gtk", "dep:gtk",
"dep:webkit2gtk", "dep:webkit2gtk",
"dep:block2", "dep:block2",
@@ -94,3 +97,15 @@ release-devtools = ["webview-auth", "tauri/devtools"]
[dev-dependencies] [dev-dependencies]
tempfile.workspace = true 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" }
+4 -65
View File
@@ -3,7 +3,6 @@ use std::{
io::ErrorKind, io::ErrorKind,
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}, os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
path::{Path, PathBuf}, path::{Path, PathBuf},
time::Duration,
}; };
use anyhow::{Context, bail}; use anyhow::{Context, bail};
@@ -14,16 +13,9 @@ use tokio::{
time::timeout, time::timeout,
}; };
const CALLBACK_SCHEME: &str = "globalprotectcallback"; mod protocol;
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC"; pub use protocol::validate_auth_callback;
const PROTOCOL_VERSION: u8 = 1; use protocol::*;
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")] #[cfg(target_os = "macos")]
mod macos; mod macos;
@@ -232,62 +224,9 @@ fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
Ok(()) 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)] #[cfg(test)]
mod tests { mod tests {
use std::time::Duration;
use tempfile::tempdir; use tempfile::tempdir;
use super::*; use super::*;
+73
View File
@@ -0,0 +1,73 @@
//! 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(())
}
+129
View File
@@ -0,0 +1,129 @@
//! 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"));
}
}
+1
View File
@@ -8,6 +8,7 @@ use gpapi::{
mod browser; mod browser;
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
#[cfg_attr(windows, path = "callback/windows.rs")]
mod callback; mod callback;
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
+6 -1
View File
@@ -12,12 +12,17 @@ mod platform_impl;
#[path = "webview/macos.rs"] #[path = "webview/macos.rs"]
mod platform_impl; mod platform_impl;
#[cfg(windows)]
#[path = "webview/windows.rs"]
mod platform_impl;
#[cfg(not(any( #[cfg(not(any(
windows,
target_os = "macos", target_os = "macos",
target_os = "linux", target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "openbsd" target_os = "openbsd"
)))] )))]
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets"); compile_error!("webview-auth is only supported on Windows, macOS and GTK/WebKitGTK Unix targets");
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme}; pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
+2 -2
View File
@@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken;
#[derive(Debug)] #[derive(Debug)]
pub(crate) enum AuthDataLocation { pub(crate) enum AuthDataLocation {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
Headers, Headers,
Body, Body,
} }
@@ -155,7 +155,7 @@ impl AuthMessenger {
} }
} }
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) { pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
use log::warn; use log::warn;
+44 -24
View File
@@ -1,6 +1,8 @@
use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
use anyhow::bail; 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"))] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint}; use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
use gpapi::{ use gpapi::{
@@ -8,24 +10,51 @@ use gpapi::{
error::ServerTlsError, error::ServerTlsError,
gp_params::GpParams, gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform}, os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::{redact::redact_uri, window::get_title_bar_height}, utils::redact::redact_uri,
}; };
use log::{info, warn}; use log::{info, warn};
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use tauri::Manager; use tauri::Manager;
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent}; #[cfg(not(windows))]
use tauri::WebviewUrl;
use tauri::{AppHandle, WindowEvent};
use tokio::{sync::oneshot, time}; use tokio::{sync::oneshot, time};
use crate::auth_prelogin; use crate::auth_prelogin;
#[cfg(not(windows))]
use super::address_bar::TOOLBAR_HEIGHT; use super::address_bar::TOOLBAR_HEIGHT;
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger}; use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming}; 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); const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
pub trait PlatformWebviewExt { pub(super) trait PlatformWebviewExt {
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>; fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>; fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
@@ -54,7 +83,7 @@ pub trait PlatformWebviewExt {
} }
} }
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub trait GetHeader { pub trait GetHeader {
fn get_header(&self, key: &str) -> Option<String>; fn get_header(&self, key: &str) -> Option<String>;
} }
@@ -125,19 +154,7 @@ impl<'a> WebviewAuthenticator<'a> {
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> { pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_messenger = Arc::new(AuthMessenger::new()); let auth_messenger = Arc::new(AuthMessenger::new());
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default()) let auth_window = create_auth_window(app_handle, self.window_title, native_theme(self.window_theme))?;
.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"))] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?; set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
@@ -170,7 +187,7 @@ impl<'a> WebviewAuthenticator<'a> {
async fn wait_for_auth( async fn wait_for_auth(
&self, &self,
auth_window: &WebviewWindow, auth_window: &AuthWindow,
auth_messenger: Arc<AuthMessenger>, auth_messenger: Arc<AuthMessenger>,
) -> anyhow::Result<SamlAuthData> { ) -> anyhow::Result<SamlAuthData> {
let mut recovery = Recovery::default(); let mut recovery = Recovery::default();
@@ -310,13 +327,16 @@ impl<'a> WebviewAuthenticator<'a> {
async fn setup_auth_window( async fn setup_auth_window(
&self, &self,
auth_window: &WebviewWindow, auth_window: &AuthWindow,
auth_messenger: Arc<AuthMessenger>, auth_messenger: Arc<AuthMessenger>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
info!("Setting up auth window..."); info!("Setting up auth window...");
if self.clean { if self.clean {
info!("Clearing all browsing data..."); 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()?; auth_window.clear_all_browsing_data()?;
} }
@@ -361,7 +381,7 @@ impl<'a> WebviewAuthenticator<'a> {
Ok(()) Ok(())
} }
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) { fn handle_not_found(&self, auth_window: &AuthWindow, auth_messenger: &Arc<AuthMessenger>) {
let visible = auth_window.is_visible().unwrap_or(false); let visible = auth_window.is_visible().unwrap_or(false);
if visible { if visible {
return; return;
@@ -370,7 +390,7 @@ impl<'a> WebviewAuthenticator<'a> {
auth_messenger.schedule_raise_window(2); auth_messenger.schedule_raise_window(2);
} }
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> { fn update_recovery(&self, auth_window: &AuthWindow, status: RecoveryStatus) -> anyhow::Result<()> {
if status != RecoveryStatus::Hidden { if status != RecoveryStatus::Hidden {
self.raise_window(auth_window); self.raise_window(auth_window);
} }
@@ -397,7 +417,7 @@ impl<'a> WebviewAuthenticator<'a> {
fn load_restarted_sign_in( fn load_restarted_sign_in(
&self, &self,
auth_window: &WebviewWindow, auth_window: &AuthWindow,
messenger: &Arc<AuthMessenger>, messenger: &Arc<AuthMessenger>,
auth_request: String, auth_request: String,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
@@ -415,7 +435,7 @@ impl<'a> WebviewAuthenticator<'a> {
Ok(()) Ok(())
} }
fn raise_window(&self, auth_window: &WebviewWindow) { fn raise_window(&self, auth_window: &AuthWindow) {
let visible = auth_window.is_visible().unwrap_or(false); let visible = auth_window.is_visible().unwrap_or(false);
if visible { if visible {
return; return;
+380
View File
@@ -0,0 +1,380 @@
//! 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(())
}
+334
View File
@@ -0,0 +1,334 @@
//! 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
}
+128
View File
@@ -0,0 +1,128 @@
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
);
}
}
+4 -1
View File
@@ -16,4 +16,7 @@ which = { workspace = true, optional = true }
[features] [features]
default = [] default = []
launcher = ["dep:open", "dep:webbrowser", "dep:which"] launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"]
[target.'cfg(windows)'.dependencies]
winreg = { version = "0.55", optional = true }
+5 -2
View File
@@ -1,8 +1,11 @@
#[cfg(all(feature = "launcher", windows))]
#[path = "platform/windows.rs"]
mod platform;
#[cfg(all(feature = "launcher", target_os = "macos"))] #[cfg(all(feature = "launcher", target_os = "macos"))]
#[path = "platform/macos.rs"] #[path = "platform/macos.rs"]
mod platform; mod platform;
#[cfg(all(feature = "launcher", not(target_os = "macos")))] #[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
#[path = "platform/generic.rs"] #[path = "platform/generic.rs"]
mod platform; mod platform;
@@ -38,7 +41,7 @@ impl<'a> Browser<'a> {
} }
} }
#[cfg(all(feature = "launcher", not(target_os = "macos")))] #[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
pub(crate) fn as_str(&self) -> &str { pub(crate) fn as_str(&self) -> &str {
match self { match self {
Browser::Auto => "auto", Browser::Auto => "auto",
@@ -0,0 +1,35 @@
//! 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)
})
}
+10 -5
View File
@@ -5,11 +5,16 @@ fn main() {
let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap(); let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap();
let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui"); let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui");
let gp_service_binary = workspace_dir.join("target/debug/gpservice"); let suffix = if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let gp_client_binary = workspace_dir.join("target/debug/gpclient"); ".exe"
let gp_auth_binary = workspace_dir.join("target/debug/gpauth"); } else {
let gp_gui_helper_binary = workspace_dir.join("target/debug/gpgui-helper"); ""
let gp_gui_binary = gpgui_dir.join("target/debug/gpgui"); };
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}"));
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display()); println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display()); println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display());
+1 -1
View File
@@ -89,7 +89,7 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> { fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> {
let executable = executable.canonicalize().ok()?; let executable = executable.canonicalize().ok()?;
let bin_dir = executable.parent()?; let bin_dir = executable.parent()?;
let binary = bin_dir.join(binary_name); let binary = bin_dir.join(format!("{binary_name}{}", std::env::consts::EXE_SUFFIX));
if is_file(&binary) { if is_file(&binary) {
return Some(binary); return Some(binary);
} }
-1
View File
@@ -2,7 +2,6 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619"; 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_WINDOWS: &str = "6.3.3-650";
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915"; 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")] #[cfg(target_os = "linux")]
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer"; pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
+1
View File
@@ -1,2 +1,3 @@
pub mod binary_paths; pub mod binary_paths;
pub mod constants; pub mod constants;
pub mod paths;
+32
View File
@@ -0,0 +1,32 @@
//! 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")
}
+22 -7
View File
@@ -6,9 +6,7 @@ edition.workspace = true
license = "MIT" license = "MIT"
[dependencies] [dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
common = { path = "../common" } common = { path = "../common" }
directories = { workspace = true, optional = true }
anyhow.workspace = true anyhow.workspace = true
base64.workspace = true base64.workspace = true
dns-lookup = { workspace = true, optional = true } dns-lookup = { workspace = true, optional = true }
@@ -16,8 +14,10 @@ log.workspace = true
reqwest.workspace = true reqwest.workspace = true
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2" rustls-pemfile = "2"
rustls-platform-verifier = "0.7"
p12-keystore = "0.4.1" p12-keystore = "0.4.1"
sec1 = { version = "0.8.1", default-features = false, features = ["der"] } pkcs12 = { version = "=0.2.0-pre.0", default-features = false }
cms = { version = "=0.3.0-pre.1", default-features = false }
pem.workspace = true pem.workspace = true
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] } pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
x509-cert = { version = "0.3", default-features = false } x509-cert = { version = "0.3", default-features = false }
@@ -34,7 +34,6 @@ thiserror.workspace = true
chacha20poly1305 = { version = "0.11", features = ["zeroize"] } chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
url.workspace = true url.workspace = true
regex.workspace = true regex.workspace = true
uzers = { workspace = true, optional = true }
serde_urlencoded.workspace = true serde_urlencoded.workspace = true
md5.workspace = true md5.workspace = true
sha2.workspace = true sha2.workspace = true
@@ -43,7 +42,6 @@ chrono.workspace = true
humantime.workspace = true humantime.workspace = true
netdev = { workspace = true, optional = true } netdev = { workspace = true, optional = true }
socket2 = { version = "0.6", features = ["all"], optional = true } socket2 = { version = "0.6", features = ["all"], optional = true }
os_info = { version = "3", default-features = false, optional = true }
snow.workspace = true snow.workspace = true
zeroize = { workspace = true, features = ["serde"] } zeroize = { workspace = true, features = ["serde"] }
getrandom = "0.4" getrandom = "0.4"
@@ -64,8 +62,15 @@ oslog = { version = "0.2", default-features = false, optional = true }
gtk = { version = "0.18", optional = true } gtk = { version = "0.18", optional = true }
[target.'cfg(target_os="linux")'.dependencies] [target.'cfg(target_os="linux")'.dependencies]
directories = { workspace = true, optional = true }
libloading = { version = "0.9", 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] [build-dependencies]
cc = "1" cc = "1"
pkg-config = "0.3" pkg-config = "0.3"
@@ -78,8 +83,18 @@ tokio = { workspace = true, features = ["test-util"] }
[features] [features]
default = ["desktop"] default = ["desktop"]
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"] 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"] tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"] clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
webview-auth = [] webview-auth = []
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"] 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"] }
+16 -2
View File
@@ -10,6 +10,7 @@ pub enum AnchorSource {
UnixMac, UnixMac,
UnixRandom, UnixRandom,
MacosIokit, MacosIokit,
WindowsSmbios,
} }
impl From<AnchorSource> for u8 { impl From<AnchorSource> for u8 {
@@ -18,6 +19,7 @@ impl From<AnchorSource> for u8 {
AnchorSource::UnixMac => 1, AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2, AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3, AnchorSource::MacosIokit => 3,
AnchorSource::WindowsSmbios => 4,
} }
} }
} }
@@ -41,6 +43,7 @@ impl TryFrom<u8> for AnchorSource {
1 => Ok(Self::UnixMac), 1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom), 2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit), 3 => Ok(Self::MacosIokit),
4 => Ok(Self::WindowsSmbios),
value => Err(InvalidAnchorSource(value)), value => Err(InvalidAnchorSource(value)),
} }
} }
@@ -65,6 +68,7 @@ impl DeviceAnchor {
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(), AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".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::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(); let mut input = domain.to_vec();
input.extend_from_slice(seed.as_ref()); input.extend_from_slice(seed.as_ref());
@@ -81,7 +85,7 @@ mod tests {
#[test] #[test]
fn preserves_existing_hardware_ids_for_all_sources() { fn preserves_existing_hardware_ids_for_all_sources() {
let cases: [(AnchorSource, &[u8], &str); 3] = [ let cases: [(AnchorSource, &[u8], &str); 4] = [
( (
AnchorSource::UnixMac, AnchorSource::UnixMac,
&[0, 17, 34, 51, 68, 85], &[0, 17, 34, 51, 68, 85],
@@ -97,6 +101,11 @@ mod tests {
b"12345678-1234-5678-9abc-def012345678", b"12345678-1234-5678-9abc-def012345678",
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34", "K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
), ),
(
AnchorSource::WindowsSmbios,
b"12345678-1234-5678-9abc-def012345678",
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
),
]; ];
for (source, seed, expected) in cases { for (source, seed, expected) in cases {
let anchor = DeviceAnchor::derive(source, seed); let anchor = DeviceAnchor::derive(source, seed);
@@ -124,12 +133,17 @@ mod tests {
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1"); 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::UnixRandom).unwrap(), "2");
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3"); 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!( assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(), serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac AnchorSource::UnixMac
); );
assert!(serde_json::from_str::<AnchorSource>("0").is_err()); assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err()); assert!(serde_json::from_str::<AnchorSource>("5").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err()); assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
} }
} }
+99 -10
View File
@@ -22,11 +22,23 @@ pub enum ServerTlsErrorKind {
} }
impl ServerTlsError { impl ServerTlsError {
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> { pub(crate) fn from_request(
Some(Self { 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 {
server: server.origin().ascii_serialization(), server: server.origin().ascii_serialization(),
kind: classify(error)?, 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)
}
} }
} }
@@ -60,6 +72,10 @@ impl ServerTlsErrorKind {
} }
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<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); let mut source = Some(error);
while let Some(error) = source { while let Some(error) = source {
if let Some(tls) = error.downcast_ref::<ServerTlsError>() { if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
@@ -71,6 +87,14 @@ pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKi
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => { rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
ServerTlsErrorKind::ClientCertificateRequired 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, _ => ServerTlsErrorKind::Other,
}); });
} }
@@ -123,6 +147,39 @@ mod tests {
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None); 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<()>) { fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
server_with_client_auth(tls, SslVerifyMode::NONE) server_with_client_auth(tls, SslVerifyMode::NONE)
} }
@@ -226,8 +283,8 @@ mod tests {
.await .await
.unwrap_err(); .unwrap_err();
worker.join().unwrap(); worker.join().unwrap();
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap(); let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error, false).unwrap();
assert_eq!(tls.kind, ServerTlsErrorKind::Other); assert_eq!(ServerTlsErrorKind::from_error(&tls), Some(ServerTlsErrorKind::Other));
} }
#[tokio::test] #[tokio::test]
@@ -314,6 +371,38 @@ 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, &params, 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] #[tokio::test]
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() { async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
use crate::{ use crate::{
@@ -411,10 +500,10 @@ mod tests {
.await .await
.unwrap_err(); .unwrap_err();
assert_eq!( assert_eq!(
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error) ServerTlsErrorKind::from_error(
.unwrap() &ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error, false).unwrap()
.kind, ),
ServerTlsErrorKind::Certificate Some(ServerTlsErrorKind::Certificate)
); );
} }
+102 -7
View File
@@ -18,7 +18,7 @@ use crate::{
gp_params::GpParams, gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput}, params::gateway_login::{self, GatewayLoginInput},
session::GatewayAuthentication, session::GatewayAuthentication,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, redact::redact_uri, remove_url_scheme, xml::ElementExt},
}; };
pub enum GatewayLogin { pub enum GatewayLogin {
@@ -181,14 +181,14 @@ async fn receive_gateway_login(
log_gateway_login_context(context, client_ip, gp_params); log_gateway_login_context(context, client_ip, gp_params);
let res = client let res = client
.post(login_url) .post(&login_url)
.form(&request_params.body) .form(&request_params.body)
.send() .send()
.await .await
.map_err(|e| { .map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match crate::error::ServerTlsError::from_request(origin, &e) { match crate::error::ServerTlsError::from_request(origin, &e, gp_params.has_client_identity()) {
Some(tls) => anyhow::anyhow!(tls), Some(tls) => tls,
None => anyhow::anyhow!(PortalError::NetworkError(e)), None => anyhow::anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
@@ -200,14 +200,30 @@ async fn receive_gateway_login(
.map(<[u8]>::to_vec); .map(<[u8]>::to_vec);
let endpoint = res.remote_addr(); let endpoint = res.remote_addr();
let url = res.url().clone(); 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| { let res = parse_gp_response(res).await.map_err(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) { // Redirect paths and query strings can contain authentication tokens. Log
return anyhow::anyhow!(tls); // 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 gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
return anyhow::anyhow!(crate::error::AuthenticationRejected); return anyhow::anyhow!(crate::error::AuthenticationRejected);
} }
warn!("Gateway login response failed: {}", err.reason);
anyhow::anyhow!("Gateway login error: {}", err.reason) anyhow::anyhow!("Gateway login error: {}", err.reason)
})?; })?;
@@ -429,6 +445,85 @@ mod tests {
.build() .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] #[tokio::test]
async fn gateway_login_cancels_stalled_headers_and_body() { async fn gateway_login_cancels_stalled_headers_and_body() {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
+13 -13
View File
@@ -6,7 +6,7 @@ use zeroize::Zeroize;
use crate::{ use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile}, os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::{ClientIdentity, create_identity}, utils::request::ClientIdentity,
}; };
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)] #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
@@ -160,21 +160,21 @@ impl GpParams {
self.prepared_identity.as_ref() 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> { pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
let mut builder = crate::utils::request::client_builder() let builder = if let Some(identity) = &self.prepared_identity {
.tls_info(true) identity.client_builder(self.ignore_tls_errors)?
.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() { } else if let Some(cert) = self.certificate.as_deref() {
info!("Using client certificate authentication..."); info!("Using client certificate authentication...");
builder = builder.identity(create_identity( ClientIdentity::load(cert, self.sslkey.as_deref(), self.key_password.as_deref())?
cert, .client_builder(self.ignore_tls_errors)?
self.sslkey.as_deref(), } else {
self.key_password.as_deref(), crate::utils::request::client_builder().danger_accept_invalid_certs(self.ignore_tls_errors)
)?); };
} let builder = builder.tls_info(true).user_agent(self.user_agent());
Ok(builder) Ok(builder)
} }
} }
+3
View File
@@ -31,3 +31,6 @@ pub mod clap;
#[cfg(feature = "desktop")] #[cfg(feature = "desktop")]
pub mod script_tun; pub mod script_tun;
#[cfg(all(feature = "desktop", windows))]
pub mod windows;
+8 -8
View File
@@ -201,15 +201,15 @@ pub async fn retrieve_config(
result = async { result = async {
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| { let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match ServerTlsError::from_request(&server_url, &e) { match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
Some(tls) => anyhow::anyhow!(tls), Some(tls) => tls,
None => anyhow::anyhow!(PortalError::NetworkError(e)), None => anyhow::anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
parse_gp_response(res).await.or_else(|err| { parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
return Err(anyhow::anyhow!(tls)); return Err(tls);
} }
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected)); return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
@@ -274,15 +274,15 @@ async fn retrieve_csc_config(
let res = client.post(&url).form(&params).send().await.map_err(|e| { let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match ServerTlsError::from_request(&server_url, &e) { match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
Some(tls) => anyhow::anyhow!(tls), Some(tls) => tls,
None => anyhow::anyhow!(PortalError::NetworkError(e)), None => anyhow::anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
parse_gp_response(res).await.or_else(|err| { parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
return Err(anyhow::anyhow!(tls)); return Err(tls);
} }
if err.status == StatusCode::NOT_FOUND { if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string())); bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
+4 -4
View File
@@ -152,15 +152,15 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
let res = request.send().await.map_err(|e| { let res = request.send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match crate::error::ServerTlsError::from_request(&server_url, &e) { match crate::error::ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
Some(error) => anyhow!(error), Some(error) => error,
None => anyhow!(PortalError::NetworkError(e)), None => anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
let res_xml = parse_gp_response(res).await.or_else(|err| { let res_xml = parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) { if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
return Err(anyhow!(tls)); return Err(tls);
} }
if err.status == StatusCode::NOT_FOUND { if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string())) bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
+37 -1
View File
@@ -236,7 +236,7 @@ impl<'a> SamlAuthLauncher<'a> {
} }
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
{ if self.browser.is_none() {
if self.hidpi { if self.hidpi {
auth_cmd.arg("--hidpi"); auth_cmd.arg("--hidpi");
} }
@@ -409,6 +409,42 @@ mod tests {
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors")); 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] #[test]
fn os_profile_sets_os_from_profile() { fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux) let profile = OsProfileBuilder::new(ClientOs::Linux)
+21
View File
@@ -1,20 +1,41 @@
#[cfg(unix)]
mod command_runner; mod command_runner;
#[cfg(windows)]
#[path = "windows/command_runner.rs"]
mod command_runner;
#[cfg(unix)]
mod command_traits; mod command_traits;
#[cfg(windows)]
#[path = "windows/command_traits.rs"]
mod command_traits;
#[cfg(unix)]
mod desktop_child; mod desktop_child;
#[cfg(unix)]
mod desktop_session_env; mod desktop_session_env;
#[cfg(unix)]
pub(crate) mod gui_helper_launcher; pub(crate) mod gui_helper_launcher;
pub use command_traits::CommandExt; pub use command_traits::CommandExt;
pub mod auth_launcher; pub mod auth_launcher;
#[cfg(unix)]
pub mod desktop_launcher; pub mod desktop_launcher;
#[cfg(unix)]
pub mod gui_launcher; pub mod gui_launcher;
#[cfg(any(target_os = "linux", test))] #[cfg(any(target_os = "linux", test))]
pub mod gui_switch; pub mod gui_switch;
#[cfg(any(target_os = "linux", test))] #[cfg(any(target_os = "linux", test))]
mod nsh_runtime; mod nsh_runtime;
#[cfg(unix)]
pub mod users; pub mod users;
#[cfg(unix)]
pub mod collection;
#[cfg(windows)]
#[path = "windows/collection.rs"]
pub mod collection; pub mod collection;
pub mod rendering_recovery; pub mod rendering_recovery;
#[cfg(windows)]
#[path = "windows/user_process.rs"]
pub mod user_process;
@@ -49,11 +49,17 @@ impl RecoveryState {
} }
} }
#[cfg(unix)]
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool { pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
use std::os::unix::process::ExitStatusExt; use std::os::unix::process::ExitStatusExt;
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15)) !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 { pub fn eligible(command: &Command) -> bool {
eligible_with_inheritance(command, true) eligible_with_inheritance(command, true)
} }
@@ -0,0 +1,42 @@
//! 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),
}
}
}
@@ -0,0 +1,198 @@
//! 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));
}
}
@@ -0,0 +1,12 @@
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)
}
}
@@ -0,0 +1,309 @@
//! 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,19 +187,28 @@ mod tests {
#[test] #[test]
fn credential_round_trips_a_validated_device_anchor() { fn credential_round_trips_a_validated_device_anchor() {
let anchor = DeviceAnchor { use crate::device_anchor::AnchorSource;
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source: crate::device_anchor::AnchorSource::UnixMac, for (source, wire_source) in [
}; (AnchorSource::UnixMac, 1),
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5") (AnchorSource::UnixRandom, 2),
.unwrap() (AnchorSource::MacosIokit, 3),
.with_device_anchor(anchor.clone()) (AnchorSource::WindowsSmbios, 4),
.unwrap(); ] {
let frame = credential.encode_frame().unwrap(); let anchor = DeviceAnchor {
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap(); hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
assert_eq!(payload["device_anchor"]["source"], 1); source,
let decoded = SessionCredential::decode_frame(&frame).unwrap(); };
assert_eq!(decoded.device_anchor(), Some(&anchor)); 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));
}
} }
#[test] #[test]
@@ -209,7 +218,7 @@ mod tests {
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap(); 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]); let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
for source in [0, 4] { for source in [0, u8::MAX] {
payload["device_anchor"] = serde_json::json!({ payload["device_anchor"] = serde_json::json!({
"hardware_id": hardware_id, "hardware_id": hardware_id,
"source": source "source": source
@@ -11,6 +11,8 @@ pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult}
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport}; pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
pub const MAX_CREDENTIAL_FRAME: usize = 512; 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_PRELUDE: usize = 256;
pub const MAX_PRODUCT_VERSION: usize = 64; pub const MAX_PRODUCT_VERSION: usize = 64;
pub const HIP_PROTOCOL_VERSION: u16 = 1; pub const HIP_PROTOCOL_VERSION: u16 = 1;
@@ -29,6 +29,11 @@ use linux as platform;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use macos as platform; use macos as platform;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as platform;
mod binding; mod binding;
use super::detection; use super::detection;
pub mod native; pub mod native;
@@ -475,6 +480,7 @@ fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow
}) })
} }
#[cfg(unix)]
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> { fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
let output = CollectorCommands::new(control) let output = CollectorCommands::new(control)
.run(name, args)? .run(name, args)?
@@ -0,0 +1,148 @@
//! 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())) Ok(builder.interface(binding.interface()))
} }
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> { fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
if let std::net::SocketAddr::V6(source) = binding.source() { if let std::net::SocketAddr::V6(source) = binding.source() {
anyhow::ensure!( anyhow::ensure!(
@@ -0,0 +1,133 @@
//! 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(())
}
+269
View File
@@ -44,3 +44,272 @@ void gp_key_free(unsigned char *data, size_t length) {
gnutls_free(data); 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,11 +1,22 @@
use std::ffi::{c_char, c_int}; use std::ffi::{c_char, c_int};
use pkcs8::SecretDocument; use pkcs8::SecretDocument;
use pkcs8::der::{Encode, asn1::ObjectIdentifier};
use zeroize::Zeroizing; use zeroize::Zeroizing;
use crate::utils::request::RequestIdentityError; use crate::utils::request::RequestIdentityError;
unsafe extern "C" { 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( fn gp_key_import(
input: *const u8, input: *const u8,
length: usize, length: usize,
@@ -14,9 +25,58 @@ unsafe extern "C" {
output: *mut *mut u8, output: *mut *mut u8,
output_length: *mut usize, output_length: *mut usize,
) -> c_int; ) -> 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); 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 { struct ExportedKey {
data: *mut u8, data: *mut u8,
length: usize, length: usize,
@@ -64,3 +124,55 @@ pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str
_ => Err(RequestIdentityError::InvalidKey.into()), _ => 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()),
}
}
@@ -0,0 +1,18 @@
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)
}
+9 -4
View File
@@ -1,4 +1,9 @@
mod client_key;
mod issuer;
pub(super) use client_key::{ClientKey, validate_certificate};
pub(super) mod pkcs12; pub(super) mod pkcs12;
mod pkcs12_format;
#[cfg(any( #[cfg(any(
target_os = "macos", target_os = "macos",
@@ -7,14 +12,14 @@ pub(super) mod pkcs12;
target_os = "openbsd" target_os = "openbsd"
))] ))]
#[path = "gnutls.rs"] #[path = "gnutls.rs"]
mod legacy_key; mod platform_import;
#[cfg(not(any( #[cfg(not(any(
target_os = "macos", target_os = "macos",
target_os = "linux", target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "openbsd" target_os = "openbsd"
)))] )))]
#[path = "unsupported.rs"] #[path = "portable_import.rs"]
mod legacy_key; mod platform_import;
pub(super) use legacy_key::decrypt as decrypt_key; pub(super) use platform_import::{archive, decrypt as decrypt_key};
@@ -0,0 +1,307 @@
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());
}
}
}
+47 -33
View File
@@ -1,22 +1,37 @@
use p12_keystore::Pkcs12Archive; use p12_keystore::Pkcs12Archive;
use rustls::{ use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
sign::CertifiedKey, use super::{
ClientKey,
pkcs12_format::{self, ArchiveBackend},
}; };
use crate::utils::{client_tls, request::RequestIdentityError};
use crate::utils::request::{RequestIdentityError, pem_request_identity}; pub(in crate::utils) fn certified_key(
bytes: &[u8],
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> { passphrase: Option<&str>,
) -> anyhow::Result<std::sync::Arc<rustls::sign::CertifiedKey>> {
anyhow::ensure!( anyhow::ensure!(
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)), passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
"PKCS#12 passphrases containing NUL are not supported" "PKCS#12 passphrases containing NUL are not supported"
); );
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| { if pkcs12_format::backend(bytes)? == ArchiveBackend::NativeRc4 {
if passphrase.is_none() { let (certificate, key) = super::archive(bytes, passphrase)?;
RequestIdentityError::NoPassphrase("PKCS#12") let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
} else { return client_tls::pem_certified_key(&certificate, key.as_bytes());
RequestIdentityError::InvalidPkcs12(error) }
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() =>
{
RequestIdentityError::NoPassphrase("PKCS#12")
}
error => RequestIdentityError::InvalidPkcs12(error),
})?; })?;
if archive.keys.is_empty() || archive.certs.is_empty() { if archive.keys.is_empty() || archive.certs.is_empty() {
return Err(RequestIdentityError::IncompletePkcs12.into()); return Err(RequestIdentityError::IncompletePkcs12.into());
@@ -25,7 +40,8 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh
return Err(RequestIdentityError::AmbiguousPkcs12.into()); return Err(RequestIdentityError::AmbiguousPkcs12.into());
} }
let key = &archive.keys[0].key; let key = &archive.keys[0].key;
let provider = rustls::crypto::ring::default_provider(); let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
let signing_key = ClientKey::load(&private_key)?;
let mut certs = Vec::new(); let mut certs = Vec::new();
for bag in &archive.certs { for bag in &archive.certs {
if !certs if !certs
@@ -35,38 +51,36 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh
certs.push(&bag.cert); certs.push(&bag.cert);
} }
} }
let matches: Vec<_> = certs let mut matches = Vec::new();
.iter() for (index, cert) in certs.iter().enumerate() {
.enumerate() if signing_key.matches_certificate(cert.as_der())? {
.filter_map(|(index, cert)| { matches.push(index);
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec())); }
CertifiedKey::from_der( }
vec![CertificateDer::from(cert.as_der().to_vec())], let leaf = match matches.first() {
private_key, Some(leaf) => *leaf,
&provider, None => return Err(RequestIdentityError::KeyMismatch.into()),
)
.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 current = certs.remove(leaf);
let mut chain = Vec::new(); let mut chain = Vec::new();
loop { loop {
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes()); chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
if current.subject() == current.issuer() { if super::issuer::is_issuer(current.as_der(), current.as_der())? {
break; break;
} }
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else { 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 {
break; break;
}; };
current = certs.remove(parent); current = certs.remove(parent);
} }
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?; let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?; let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
pem_request_identity(&chain, key.as_bytes()) client_tls::pem_certified_key(&chain, key.as_bytes())
} }
@@ -0,0 +1,137 @@
//! 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(&parameters).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(&parameters).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)
));
}
}
}
@@ -0,0 +1,46 @@
//! 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()
}),
)
}
@@ -0,0 +1,41 @@
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()
}
}
@@ -1,7 +0,0 @@
pub(in crate::utils) fn decrypt(
_bytes: &[u8],
_pem: bool,
_passphrase: Option<&str>,
) -> anyhow::Result<pkcs8::SecretDocument> {
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
}
+99
View File
@@ -0,0 +1,99 @@
//! 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()
}
}
+2 -1
View File
@@ -90,7 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
} }
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?, "ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
"EC PRIVATE KEY" => { "EC PRIVATE KEY" => {
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?; // The signing provider validates both named and explicitly encoded curves.
SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?;
return Ok(block.encoded()); return Ok(block.encoded());
} }
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()), _ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
+2 -2
View File
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use common::constants::GP_SERVICE_LOCK_FILE; use common::paths::service_lock_file;
use thiserror::Error; use thiserror::Error;
use tokio::fs; use tokio::fs;
@@ -109,7 +109,7 @@ impl LockInfo {
} }
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> { pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await gpservice_lock_info_at(service_lock_file()).await
} }
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> { pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
+1
View File
@@ -3,6 +3,7 @@ pub mod xml;
pub mod base64; pub mod base64;
mod certificate; mod certificate;
pub mod checksum; pub mod checksum;
mod client_tls;
pub mod crypto; pub mod crypto;
#[cfg(feature = "desktop")] #[cfg(feature = "desktop")]
pub mod endpoint; pub mod endpoint;
+57 -57
View File
@@ -1,34 +1,40 @@
use std::{fmt, fs, io::Write, path::Path, sync::Arc}; use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::{Context, ensure}; use anyhow::{Context, ensure};
use reqwest::Identity; use rustls::sign::CertifiedKey;
use zeroize::Zeroizing; use zeroize::Zeroizing;
use super::{certificate::pkcs12, identity_encoding}; use super::{certificate::pkcs12, client_tls, identity_encoding};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError { pub enum RequestIdentityError {
#[error("Failed to find the private key")] #[error("No private key was found. Choose the matching key file")]
NoKey, NoKey,
#[error("No passphrase provided")] #[error("This certificate or key is password-protected. Enter its password")]
NoPassphrase(&'static str), NoPassphrase(&'static str),
#[error("Failed to decrypt private key")] #[error("Could not unlock the certificate or key. Check the password and file")]
DecryptError(&'static str), DecryptError(&'static str),
#[error( #[error("This certificate or key uses unsupported encryption. Re-export it with AES encryption")]
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
UnsupportedEncryption, UnsupportedEncryption,
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")] #[error("This private key format is not supported. Choose a PEM key or a PKCS#12 certificate file")]
UnsupportedKeyFormat, UnsupportedKeyFormat,
#[error("Invalid private key")] #[error(
"This client certificate uses an unsupported key type ({0}). Ask your VPN administrator for an RSA or P-256 certificate"
)]
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")]
InvalidKey, InvalidKey,
#[error("Invalid certificate or certificate chain")] #[error("The certificate file is invalid. Choose a different certificate file")]
InvalidCertificate, InvalidCertificate,
#[error("The PKCS#12 file must contain both a client certificate and its private key")] #[error("The PKCS#12 file must contain both a client certificate and its private key")]
IncompletePkcs12, IncompletePkcs12,
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")] #[error("Could not open the PKCS#12 file. Check the password or choose another file")]
InvalidPkcs12(#[source] p12_keystore::error::Error), InvalidPkcs12(#[source] p12_keystore::error::Error),
#[error("The PKCS#12 file must contain one matching client identity")] #[error(
"The certificate file contains more than one matching identity. Choose a file with one client certificate and key"
)]
AmbiguousPkcs12, AmbiguousPkcs12,
} }
@@ -38,7 +44,7 @@ pub enum RequestIdentityError {
#[derive(Clone)] #[derive(Clone)]
pub struct ClientIdentity { pub struct ClientIdentity {
material: Arc<IdentityMaterial>, material: Arc<IdentityMaterial>,
identity: Identity, certified_key: Arc<CertifiedKey>,
} }
struct IdentityMaterial { struct IdentityMaterial {
@@ -68,14 +74,14 @@ impl ClientIdentity {
}; };
let key = identity_encoding::private_key(&key_bytes, passphrase)?; let key = identity_encoding::private_key(&key_bytes, passphrase)?;
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?; let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
let identity = pem_request_identity(&certificate, &key)?; let certified_key = client_tls::pem_certified_key(&certificate, &key)?;
Ok(Self { Ok(Self {
material: Arc::new(IdentityMaterial { material: Arc::new(IdentityMaterial {
certificate, certificate,
key: Some(key), key: Some(key),
passphrase: None, passphrase: None,
}), }),
identity, certified_key,
}) })
} }
@@ -86,12 +92,12 @@ impl ClientIdentity {
key: Option<Zeroizing<Vec<u8>>>, key: Option<Zeroizing<Vec<u8>>>,
passphrase: Option<&str>, passphrase: Option<&str>,
) -> anyhow::Result<Self> { ) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key { let (certified_key, passphrase) = match &key {
Some(key) => (pem_request_identity(&certificate, key)?, None), Some(key) => (client_tls::pem_certified_key(&certificate, key)?, None),
None => { None => {
let identity = pkcs12::identity(&certificate, passphrase)?; let certified_key = pkcs12::certified_key(&certificate, passphrase)?;
( (
identity, certified_key,
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())), Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
) )
} }
@@ -102,7 +108,7 @@ impl ClientIdentity {
key, key,
passphrase, passphrase,
}), }),
identity, certified_key,
}) })
} }
@@ -115,8 +121,8 @@ impl ClientIdentity {
pub fn key_password(&self) -> Option<&str> { pub fn key_password(&self) -> Option<&str> {
self.material.passphrase.as_ref().map(|value| value.as_str()) self.material.passphrase.as_ref().map(|value| value.as_str())
} }
pub(crate) fn request_identity(&self) -> Identity { pub(crate) fn client_builder(&self, ignore_tls_errors: bool) -> anyhow::Result<reqwest::ClientBuilder> {
self.identity.clone() client_tls::identity_client_builder(self.certified_key.clone(), ignore_tls_errors)
} }
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> { pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
@@ -149,29 +155,6 @@ 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>>> { fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new( Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?, fs::read(path).context("Failed to read client identity")?,
@@ -208,12 +191,6 @@ pub fn client_builder() -> reqwest::ClientBuilder {
reqwest::Client::builder().tls_backend_rustls() 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -222,6 +199,29 @@ mod tests {
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem"); 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"); 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] #[test]
fn pem_without_key_reports_missing_key_even_with_passphrase() { fn pem_without_key_reports_missing_key_even_with_passphrase() {
let mut source = tempfile::NamedTempFile::new().unwrap(); let mut source = tempfile::NamedTempFile::new().unwrap();
@@ -247,21 +247,21 @@ mod tests {
} }
#[test] #[test]
fn create_identity_preserves_password_errors_and_builds_a_request_client() { fn identity_loading_preserves_password_errors_and_builds_a_request_client() {
let mut source = tempfile::NamedTempFile::new().unwrap(); let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(CERTIFICATE).unwrap(); source.write_all(CERTIFICATE).unwrap();
source.write_all(ENCRYPTED_KEY).unwrap(); source.write_all(ENCRYPTED_KEY).unwrap();
for (password, missing) in [(None, true), (Some("wrong"), false)] { for (password, missing) in [(None, true), (Some("wrong"), false)] {
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err(); let error = ClientIdentity::load(source.path().to_str().unwrap(), None, password).unwrap_err();
match error.downcast_ref::<RequestIdentityError>() { match error.downcast_ref::<RequestIdentityError>() {
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing), Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing), Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
other => panic!("Unexpected identity error: {other:?}"), other => panic!("Unexpected identity error: {other:?}"),
} }
} }
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap(); let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
drop(source); drop(source);
client_builder().identity(identity).build().unwrap(); identity.client_builder(false).unwrap().build().unwrap();
} }
#[test] #[test]
@@ -283,7 +283,7 @@ mod tests {
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files); drop(files);
assert!(!Path::new(&path).exists()); assert!(!Path::new(&path).exists());
client_builder().identity(identity.request_identity()).build().unwrap(); identity.client_builder(false).unwrap().build().unwrap();
} }
} }
@@ -13,6 +13,9 @@ pub async fn shutdown_signal() {
.await; .await;
}; };
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! { tokio::select! {
_ = ctrl_c => {}, _ = ctrl_c => {},
_ = terminate => {}, _ = terminate => {},
+176
View File
@@ -0,0 +1,176 @@
//! Windows user identity and private local IPC.
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
use std::{io, ptr};
mod pipes;
pub use pipes::{PacketPipe, connect_service_admission, connect_service_worker, create_service_admission_pipe};
use tokio::net::windows::named_pipe::NamedPipeServer;
use windows_sys::Win32::{
Foundation::{CloseHandle, LocalFree},
Security::{Authorization::ConvertSidToStringSidW, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser},
System::Threading::{GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION},
};
pub fn current_user_sid() -> io::Result<String> {
unsafe {
let mut token = ptr::null_mut();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let result = token_user_sid(token);
CloseHandle(token);
result
}
}
/// An authenticated pipe client's primary token, retained for its user-session worker.
/// Windows user identity is a SID and token; it is never represented as a Unix UID.
pub struct PipeClientIdentity {
sid: String,
token: OwnedHandle,
}
impl PipeClientIdentity {
pub fn sid(&self) -> &str {
&self.sid
}
pub fn primary_token(&self) -> BorrowedHandle<'_> {
self.token.as_handle()
}
/// Call after reading the client's admission request. Impersonation stays on
/// this thread and ends before returning; no asynchronous work can run in it.
pub fn from_pipe(pipe: &NamedPipeServer) -> io::Result<Self> {
use windows_sys::Win32::{
Security::{
DuplicateTokenEx, RevertToSelf, SecurityImpersonation, TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TokenPrimary,
},
System::{
Pipes::ImpersonateNamedPipeClient,
Threading::{GetCurrentThread, OpenThreadToken},
},
};
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
// Continuing a service thread as its client would corrupt its privilege
// boundary. Windows documents terminating if RevertToSelf fails.
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
unsafe {
if ImpersonateNamedPipeClient(pipe.as_raw_handle()) == 0 {
return Err(io::Error::last_os_error());
}
let _revert = Revert;
let mut token = ptr::null_mut();
if OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, 1, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let token = OwnedHandle::from_raw_handle(token);
let sid = token_user_sid(token.as_raw_handle())?;
let mut primary = ptr::null_mut();
if DuplicateTokenEx(
token.as_raw_handle(),
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,
ptr::null(),
SecurityImpersonation,
TokenPrimary,
&mut primary,
) == 0
{
return Err(io::Error::last_os_error());
}
Ok(Self {
sid,
token: OwnedHandle::from_raw_handle(primary),
})
}
}
}
/// Resolve a local IPC peer from its OS process token.
pub fn process_user_sid(pid: u32) -> io::Result<String> {
unsafe {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if process.is_null() {
return Err(io::Error::last_os_error());
}
let mut token = ptr::null_mut();
if OpenProcessToken(process, TOKEN_QUERY, &mut token) == 0 {
let error = io::Error::last_os_error();
CloseHandle(process);
return Err(error);
}
CloseHandle(process);
let result = token_user_sid(token);
CloseHandle(token);
result
}
}
unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result<String> {
unsafe {
let mut length = 0;
GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut length);
// TOKEN_USER contains pointers; retain pointer alignment in its backing allocation.
let mut buffer = vec![0usize; (length as usize).div_ceil(std::mem::size_of::<usize>())];
if GetTokenInformation(token, TokenUser, buffer.as_mut_ptr().cast(), length, &mut length) == 0 {
return Err(io::Error::last_os_error());
}
let user = &*buffer.as_ptr().cast::<TOKEN_USER>();
let mut text = ptr::null_mut();
if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 {
return Err(io::Error::last_os_error());
}
let mut length = 0;
while *text.add(length) != 0 {
length += 1;
}
let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
LocalFree(text.cast());
Ok(sid)
}
}
/// Only the owning user and SYSTEM can access authentication callbacks.
pub fn create_user_pipe(name: &str, first_instance: bool) -> io::Result<NamedPipeServer> {
pipes::user_pipe(&current_user_sid()?, name, first_instance)
}
/// Query a registered service without requiring access to its SYSTEM process token.
pub fn service_process_id(name: &str) -> io::Result<u32> {
use windows_sys::Win32::System::Services::*;
let name: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
unsafe {
let manager = OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT);
if manager.is_null() {
return Err(io::Error::last_os_error());
}
let service = OpenServiceW(manager, name.as_ptr(), SERVICE_QUERY_STATUS);
if service.is_null() {
let error = io::Error::last_os_error();
CloseServiceHandle(manager);
return Err(error);
}
let mut status = SERVICE_STATUS_PROCESS::default();
let mut length = 0;
let success = QueryServiceStatusEx(
service,
SC_STATUS_PROCESS_INFO,
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
std::mem::size_of_val(&status) as u32,
&mut length,
);
let result = if success == 0 {
Err(io::Error::last_os_error())
} else {
Ok(status.dwProcessId)
};
CloseServiceHandle(service);
CloseServiceHandle(manager);
result
}
}
+202
View File
@@ -0,0 +1,202 @@
//! Local service admission and worker pipes with explicit user access.
use super::PipeClientIdentity;
use std::{
fs::OpenOptions,
io,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle},
},
ptr,
time::Duration,
};
use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer, ServerOptions};
use windows_sys::Win32::{
Foundation::{ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0, WAIT_TIMEOUT},
Security::{Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, SECURITY_ATTRIBUTES},
Storage::FileSystem::*,
System::{
IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED},
Pipes::*,
Threading::{CreateEventW, WaitForSingleObject},
},
};
// Generic write also grants FILE_CREATE_PIPE_INSTANCE. Clients receive only
// data/metadata access; creating another instance remains SYSTEM-only.
const CLIENT_ACCESS: u32 = FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES;
fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(Some(0)).collect()
}
fn with_security<T>(sddl: &str, operation: impl FnOnce(&SECURITY_ATTRIBUTES) -> io::Result<T>) -> io::Result<T> {
struct Descriptor(*mut std::ffi::c_void);
impl Drop for Descriptor {
fn drop(&mut self) {
unsafe {
LocalFree(self.0);
}
}
}
let mut pointer = ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(wide(sddl).as_ptr(), 1, &mut pointer, ptr::null_mut())
} == 0
{
return Err(io::Error::last_os_error());
}
let descriptor = Descriptor(pointer);
operation(&SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: 0,
})
}
fn server(sddl: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
with_security(sddl, |attributes| unsafe {
ServerOptions::new()
.first_pipe_instance(first)
.reject_remote_clients(true)
.create_with_security_attributes_raw(name, (attributes as *const SECURITY_ATTRIBUTES).cast_mut().cast())
})
}
pub(super) fn user_pipe(sid: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
server(&format!("D:P(A;;GA;;;SY)(A;;GA;;;{sid})"), name, first)
}
pub fn create_service_admission_pipe(first: bool) -> io::Result<NamedPipeServer> {
server(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;AU)"),
common::paths::SERVICE_PIPE,
first,
)
}
fn client(name: &str, message: bool, impersonation: bool) -> io::Result<NamedPipeClient> {
let file = OpenOptions::new()
.read(true)
.write(true)
.access_mode(CLIENT_ACCESS)
.custom_flags(FILE_FLAG_OVERLAPPED)
.security_qos_flags(if impersonation {
SECURITY_IMPERSONATION
} else {
SECURITY_IDENTIFICATION
})
.open(name)?;
let pipe = unsafe { NamedPipeClient::from_raw_handle(file.into_raw_handle()) }?;
let mut pid = 0;
if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut pid) } == 0 {
return Err(io::Error::last_os_error());
}
if pid == 0 || pid != super::service_process_id(common::paths::SERVICE_NAME)? {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Pipe does not belong to the registered VPN service",
));
}
if message {
let mode = PIPE_READMODE_MESSAGE;
if unsafe { SetNamedPipeHandleState(pipe.as_raw_handle(), &mode, ptr::null(), ptr::null()) } == 0 {
return Err(io::Error::last_os_error());
}
}
Ok(pipe)
}
/// Verify the service before the first request permits it to impersonate this user.
pub fn connect_service_admission() -> io::Result<NamedPipeClient> {
client(common::paths::SERVICE_PIPE, false, true)
}
pub fn connect_service_worker(name: &str, message: bool) -> io::Result<NamedPipeClient> {
client(name, message, false)
}
impl PipeClientIdentity {
pub fn create_control_pipe(&self, name: &str) -> io::Result<NamedPipeServer> {
server(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
name,
true,
)
}
pub fn create_packet_pipe(&self, name: &str) -> io::Result<PacketPipe> {
let name = wide(name);
with_security(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
|attributes| {
let handle = unsafe {
CreateNamedPipeW(
name.as_ptr(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS,
1,
256 * 1024,
256 * 1024,
0,
attributes,
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(PacketPipe(unsafe { OwnedHandle::from_raw_handle(handle) }))
},
)
}
}
/// Raw Win32 overlapped I/O, deliberately never registered with Tokio/Mio IOCP.
pub struct PacketPipe(OwnedHandle);
impl PacketPipe {
pub fn connect(&mut self, expected_pid: u32, timeout: Duration) -> io::Result<()> {
let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
if event.is_null() {
return Err(io::Error::last_os_error());
}
let event = unsafe { OwnedHandle::from_raw_handle(event) };
let mut overlap = OVERLAPPED {
hEvent: event.as_raw_handle(),
..Default::default()
};
if unsafe { ConnectNamedPipe(self.0.as_raw_handle(), &mut overlap) } == 0 {
let error = io::Error::last_os_error();
match error.raw_os_error().map(|code| code as u32) {
Some(ERROR_PIPE_CONNECTED) => {}
Some(ERROR_IO_PENDING) => {
let status = unsafe {
WaitForSingleObject(
event.as_raw_handle(),
timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
)
};
let mut bytes = 0;
if status != WAIT_OBJECT_0 {
// Complete cancellation before OVERLAPPED/event storage is released.
unsafe {
CancelIoEx(self.0.as_raw_handle(), &overlap);
GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 1);
}
if status == WAIT_TIMEOUT {
return Err(io::Error::new(io::ErrorKind::TimedOut, "Packet worker did not connect"));
}
return Err(io::Error::last_os_error());
}
if unsafe { GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 0) } == 0 {
return Err(io::Error::last_os_error());
}
}
_ => return Err(error),
}
}
let mut pid = 0;
if unsafe { GetNamedPipeClientProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
return Err(io::Error::last_os_error());
}
if pid != expected_pid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Unexpected packet pipe client",
));
}
Ok(())
}
pub fn into_handle(self) -> OwnedHandle {
self.0
}
}
@@ -0,0 +1,150 @@
//! Supported desktop identities and actionable failures for unsupported inputs.
#![cfg(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
))]
use gpapi::utils::request::{ClientIdentity, RequestIdentityError};
use openssl::{
asn1::Asn1Time,
bn::BigNum,
hash::MessageDigest,
pkey::PKey,
stack::Stack,
x509::{X509, X509NameBuilder},
};
use std::{fs, path::PathBuf};
use zeroize::Zeroizing;
fn fixture(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/files/client-identity")
.join(name)
}
fn assert_unsupported_key(certificate: &str, key: &str) {
let error = ClientIdentity::load(
fixture(certificate).to_str().unwrap(),
Some(fixture(key).to_str().unwrap()),
None,
)
.unwrap_err();
assert!(
matches!(
error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::UnsupportedKeyAlgorithm(_))
),
"{error:#}"
);
let message = error.to_string();
assert!(message.contains("unsupported"), "{message}");
assert!(message.contains("VPN administrator"), "{message}");
assert!(
!message.contains("password") && !message.contains("does not match"),
"{message}"
);
}
#[test]
fn compressed_ec_certificate_reports_an_unsupported_encoding() {
assert_unsupported_key("ec-compressed-cert.pem", "ec-pkcs8.pem");
}
#[test]
fn compressed_ec_private_key_reports_an_unsupported_encoding() {
assert_unsupported_key("ec-compressed-cert.pem", "ec-compressed.pem");
}
#[test]
fn explicit_ec_parameters_report_an_unsupported_encoding() {
assert_unsupported_key("ec-explicit-cert.pem", "ec-explicit.pem");
}
#[test]
fn p521_key_reports_the_known_tls_capability_limit() {
assert_unsupported_key("ec-p521-cert.pem", "ec-p521.pem");
}
#[test]
fn rsa_pss_key_reports_the_known_tls_capability_limit() {
assert_unsupported_key("rsa-pss-cert.pem", "rsa-pss.pem");
}
fn legacy_archive(name: &str) {
let path = fixture(name);
let bytes = fs::read(&path).unwrap();
let identity = ClientIdentity::load(path.to_str().unwrap(), None, Some("fixture-password"))
.unwrap_or_else(|error| panic!("{name}: {error:#}"));
assert_eq!(identity.certificate_data(), bytes);
assert!(ClientIdentity::load(path.to_str().unwrap(), None, Some("incorrect")).is_err());
}
fn unsupported_archive(name: &str) {
let path = fixture(name);
let bytes = fs::read(&path).unwrap();
for password in [None, Some("fixture-password"), Some("incorrect"), Some("")] {
for error in [
ClientIdentity::load(path.to_str().unwrap(), None, password).unwrap_err(),
ClientIdentity::from_data(Zeroizing::new(bytes.clone()), None, password).unwrap_err(),
] {
assert!(
matches!(
error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::UnsupportedEncryption)
),
"{name}: {error:#}"
);
assert!(error.to_string().contains("AES"), "{error}");
}
}
}
#[test]
fn legacy_rc2_128_pkcs12_explains_the_unsupported_encryption() {
unsupported_archive("legacy-RC2-128.p12");
}
#[test]
fn legacy_rc4_128_pkcs12_is_usable() {
legacy_archive("legacy-RC4-128.p12");
}
#[test]
fn legacy_two_key_3des_pkcs12_explains_the_unsupported_encryption() {
unsupported_archive("legacy-2DES.p12");
}
#[test]
fn renewed_pkcs12_with_one_key_is_accepted_without_artificial_ambiguity() {
let key = PKey::private_key_from_pem(&fs::read(fixture("rsa-pkcs8.pem")).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "Public renewed identity").unwrap();
let name = name.build();
let mut certs = Vec::new();
for serial in [10, 11] {
let mut builder = X509::builder().unwrap();
builder.set_version(2).unwrap();
builder.set_subject_name(&name).unwrap();
builder.set_issuer_name(&name).unwrap();
builder.set_pubkey(&key).unwrap();
builder
.set_serial_number(&BigNum::from_u32(serial).unwrap().to_asn1_integer().unwrap())
.unwrap();
builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
builder.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
builder.sign(&key, MessageDigest::sha256()).unwrap();
certs.push(builder.build());
}
let mut extra = Stack::new().unwrap();
extra.push(certs[0].clone()).unwrap();
let mut builder = openssl::pkcs12::Pkcs12::builder();
builder.name("renewed").pkey(&key).cert(&certs[1]).ca(extra);
let archive = builder.build2("fixture-password").unwrap().to_der().unwrap();
// Independent oracle for this bag order. Native bag-order permutation tests
// establish selection; localKeyId alone does not override native ordering.
let parsed = openssl::pkcs12::Pkcs12::from_der(&archive)
.unwrap()
.parse2("fixture-password")
.unwrap();
assert_eq!(parsed.cert.unwrap().to_der().unwrap(), certs[1].to_der().unwrap());
ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap();
}
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more