mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 14:06:14 -05:00
Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6cf639887 | ||
|
|
197cd5748d | ||
|
|
907e161b12 | ||
|
|
b26a416f45 | ||
|
|
0212b7ff91 | ||
|
|
9001b768c1 | ||
|
|
a02dfd10ab | ||
|
|
6ebffad3c8 | ||
|
|
c84bfcc13a | ||
|
|
aa92251d47 | ||
|
|
b15bc2bfa5 | ||
|
|
d825e2b9c8 | ||
|
|
dcc74d805b | ||
|
|
43eda033e5 | ||
|
|
54b4d810d9 | ||
|
|
e108ce50dc | ||
|
|
18ce000640 | ||
|
|
14c4e24e0e | ||
|
|
37c88c7adb | ||
|
|
f2ec8c7770 | ||
|
|
1698397af3 | ||
|
|
eb8f919121 | ||
|
|
b4529398b0 | ||
|
|
c53911e7b8 | ||
|
|
580438e8eb | ||
|
|
92943e0a9d | ||
|
|
6f2f8e1265 | ||
|
|
f643180b59 | ||
|
|
3a643fe6ff | ||
|
|
66b1cf3c47 | ||
|
|
472806ca73 | ||
|
|
d7de2df53b | ||
|
|
6ef2f0497d | ||
|
|
0436a18e42 | ||
|
|
56489a4e90 | ||
|
|
6316f8d68e | ||
|
|
d9e00bc3c9 | ||
|
|
e284840d89 | ||
|
|
0df25fbd28 | ||
|
|
8e3bb8ff11 | ||
|
|
a7c571a2c1 | ||
|
|
2b38de10f6 | ||
|
|
4aa7b66313 | ||
|
|
ce5a19c131 | ||
|
|
e7ddc2ca2a | ||
|
|
4635b1b4b8 | ||
|
|
0cb246b0c5 | ||
|
|
fabc7d4461 | ||
|
|
d2fcf66be8 | ||
|
|
ae504dfbbe | ||
|
|
fca3076b64 | ||
|
|
c29c57639a | ||
|
|
da90bc80e3 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# Keep source and build scripts consistent on every platform.
|
||||
* text=auto eol=lf
|
||||
@@ -12,9 +12,6 @@ on:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
builder:
|
||||
required: true
|
||||
type: string
|
||||
@@ -88,7 +85,7 @@ jobs:
|
||||
- name: Build gpgui in Docker
|
||||
env:
|
||||
GPGUI_BUILDER: ${{ inputs.builder }}
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
run: |
|
||||
|
||||
@@ -12,9 +12,6 @@ on:
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
@@ -38,7 +35,7 @@ jobs:
|
||||
env:
|
||||
CARGO_INCREMENTAL: '0'
|
||||
CARGO_BUILD_JOBS: '2'
|
||||
GPGUI_BUILD_VERSION: ${{ inputs.build }}
|
||||
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
|
||||
GPGUI_GIT_COMMIT: ${{ inputs.gpgui_ref }}
|
||||
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
|
||||
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
name: Build Windows package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
gp_ref:
|
||||
type: string
|
||||
required: true
|
||||
gpgui_ref:
|
||||
type: string
|
||||
required: true
|
||||
channel:
|
||||
type: choice
|
||||
options: [snapshot, stable]
|
||||
default: snapshot
|
||||
build:
|
||||
type: string
|
||||
required: true
|
||||
architecture:
|
||||
type: choice
|
||||
options: [x64, arm64]
|
||||
required: true
|
||||
workflow_call:
|
||||
inputs:
|
||||
gp_ref:
|
||||
type: string
|
||||
required: true
|
||||
gpgui_ref:
|
||||
type: string
|
||||
required: true
|
||||
channel:
|
||||
type: string
|
||||
required: true
|
||||
build:
|
||||
type: string
|
||||
required: true
|
||||
architecture:
|
||||
type: string
|
||||
required: true
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
WINDOWS_UPDATE_PRIVATE_KEY:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ inputs.architecture == 'arm64' && 'windows-11-arm' || 'windows-2022' }}
|
||||
environment: windows-signing
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
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 }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ vars.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ vars.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_SIGNING_PROFILE: ${{ vars.AZURE_SIGNING_PROFILE }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
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 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 -BuildOnly `
|
||||
-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 failed; private diagnostics remain on the runner.'
|
||||
}
|
||||
Write-Host 'Windows compilation passed.'
|
||||
- name: Install Microsoft Artifact Signing tooling
|
||||
shell: pwsh
|
||||
run: Install-Module ArtifactSigning -RequiredVersion 0.1.20 -Repository PSGallery -Force -Scope CurrentUser
|
||||
- name: Log in to Azure with GitHub OIDC
|
||||
uses: azure/login@v3
|
||||
with:
|
||||
client-id: ${{ vars.AZURE_SIGNING_CLIENT_ID }}
|
||||
tenant-id: ${{ vars.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
|
||||
- name: Sign and package the Windows runtime
|
||||
shell: pwsh
|
||||
env:
|
||||
MSYS_ROOT: ${{ steps.msys2.outputs.msys2-location }}
|
||||
run: |
|
||||
& ./source/gpgui/scripts/build-windows.ps1 -Profile Release -SkipBuild -Sign `
|
||||
-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"
|
||||
- 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
|
||||
+10
-100
@@ -42,11 +42,6 @@ on:
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
build_windows:
|
||||
description: 'Build Windows x64 and ARM64 NSH installers'
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
push:
|
||||
paths-ignore:
|
||||
- LICENSE
|
||||
@@ -69,10 +64,8 @@ jobs:
|
||||
actions: read
|
||||
contents: read
|
||||
outputs:
|
||||
gp_sha: ${{ steps.identity.outputs.gp_sha }}
|
||||
gpgui_sha: ${{ steps.identity.outputs.gpgui_sha }}
|
||||
version: ${{ steps.identity.outputs.version }}
|
||||
build_version: ${{ steps.identity.outputs.build_version }}
|
||||
gp_sha: ${{ steps.sources.outputs.gp_sha }}
|
||||
gpgui_sha: ${{ steps.sources.outputs.gpgui_sha }}
|
||||
steps:
|
||||
- name: Validate stable refs
|
||||
env:
|
||||
@@ -121,12 +114,11 @@ jobs:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
|
||||
path: selected/gpgui
|
||||
- name: Record selected sources and versions
|
||||
id: identity
|
||||
- name: Record selected sources
|
||||
id: sources
|
||||
run: |
|
||||
python3 scripts/record-build-sources.py selected-sources/sources.json \
|
||||
--gp selected/gp --gpgui selected/gpgui \
|
||||
--build-version "${{ github.run_number }}.${{ github.run_attempt }}"
|
||||
--gp selected/gp --gpgui selected/gpgui
|
||||
- name: Retain selected sources for retries
|
||||
if: steps.restored.outputs.cached != 'true'
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -445,7 +437,6 @@ jobs:
|
||||
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: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
builder: gpgui-builder-tauri2
|
||||
verify_desktop_assets: true
|
||||
secrets:
|
||||
@@ -459,7 +450,6 @@ jobs:
|
||||
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: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
builder: gpgui-alpine-builder-tauri2
|
||||
artifact_suffix: -musl
|
||||
secrets:
|
||||
@@ -472,31 +462,9 @@ jobs:
|
||||
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: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
|
||||
build-windows:
|
||||
needs: validate-inputs
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
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: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
secrets:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
WINDOWS_UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
|
||||
|
||||
nix-source:
|
||||
needs: [validate-inputs, build-gpgui-glibc]
|
||||
strategy:
|
||||
@@ -691,7 +659,7 @@ jobs:
|
||||
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
|
||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
||||
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
|
||||
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -859,7 +827,7 @@ jobs:
|
||||
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
|
||||
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
|
||||
REQUEST_ID: ${{ format('{0}.{1}.macos', github.run_id, github.run_attempt) }}
|
||||
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
|
||||
WORKFLOW_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -1058,6 +1026,7 @@ jobs:
|
||||
nettle \
|
||||
gmp \
|
||||
gnome-keyring \
|
||||
libayatana-appindicator \
|
||||
polkit \
|
||||
webkit2-gtk_41
|
||||
pkgconf --exists libxml-2.0 liblz4 gnutls p11-kit-1 hogweed nettle gmp
|
||||
@@ -1066,7 +1035,7 @@ jobs:
|
||||
exec 3>&1
|
||||
(
|
||||
set -eu
|
||||
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
@@ -1150,7 +1119,7 @@ jobs:
|
||||
set -eu
|
||||
export AUTOCONF_VERSION=2.72
|
||||
export AUTOMAKE_VERSION=1.17
|
||||
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
|
||||
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
|
||||
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
|
||||
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
|
||||
|
||||
@@ -1222,7 +1191,6 @@ jobs:
|
||||
- build-gpgui-glibc
|
||||
- build-gpgui-musl
|
||||
- build-gpgui-nsh
|
||||
- build-windows
|
||||
- setup-bsd-matrix
|
||||
- build-gpgui-frontend
|
||||
- build-bsd
|
||||
@@ -1233,7 +1201,6 @@ jobs:
|
||||
NEEDS_JSON: ${{ toJson(needs) }}
|
||||
BSD_MATRIX_ENABLED: ${{ needs.setup-bsd-matrix.outputs.enabled }}
|
||||
IS_STABLE: ${{ (startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.channel == 'stable')) }}
|
||||
BUILD_WINDOWS: ${{ (github.event_name == 'workflow_dispatch' && inputs.build_windows) || (startsWith(github.ref, 'refs/tags/') && vars.BUILD_WINDOWS_ON_TAG == 'true') }}
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
@@ -1253,8 +1220,6 @@ jobs:
|
||||
continue
|
||||
elif name in {"build-gpgui-frontend", "build-bsd"} and result == "skipped" and not bsd_matrix_enabled:
|
||||
continue
|
||||
elif name == "build-windows" and result == "skipped" and os.environ["BUILD_WINDOWS"] != "true":
|
||||
continue
|
||||
elif result == "skipped":
|
||||
failed.append(f"{name}: {result}")
|
||||
|
||||
@@ -1321,61 +1286,6 @@ jobs:
|
||||
run: |
|
||||
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
|
||||
|
||||
publish-macos-assets:
|
||||
needs: [build-macos, gh-release]
|
||||
if: >-
|
||||
${{ !cancelled() &&
|
||||
needs.build-macos.result == 'success' && needs.gh-release.result == 'success' }}
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
uses: ./.github/workflows/publish-macos-assets.yaml
|
||||
with:
|
||||
build_run_id: ${{ github.run_id }}
|
||||
release_tag: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
|
||||
expected_gui: ${{ github.event_name == 'workflow_dispatch' && inputs.macos_gui || 'nsh' }}
|
||||
secrets: inherit
|
||||
|
||||
publish-windows-snapshot-feed:
|
||||
needs: [validate-inputs, gh-release, publish-macos-assets]
|
||||
if: >-
|
||||
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
|
||||
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_windows &&
|
||||
needs.gh-release.result == 'success' &&
|
||||
(!inputs.build_macos || needs.publish-macos-assets.result == 'success') }}
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/publish-windows-update-feed.yaml
|
||||
with:
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
release_tag: snapshot
|
||||
version: ${{ needs.validate-inputs.outputs.version }}
|
||||
channel: snapshot
|
||||
build: ${{ needs.validate-inputs.outputs.build_version }}
|
||||
highlights: Development snapshot.
|
||||
secrets: inherit
|
||||
|
||||
publish-macos-unix-snapshot-feeds:
|
||||
needs: [validate-inputs, gh-release, publish-macos-assets, publish-windows-snapshot-feed]
|
||||
if: >-
|
||||
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
|
||||
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_macos &&
|
||||
needs.gh-release.result == 'success' && needs.publish-macos-assets.result == 'success' &&
|
||||
(!inputs.build_windows || needs.publish-windows-snapshot-feed.result == 'success') }}
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/publish-update-feeds.yaml
|
||||
with:
|
||||
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
|
||||
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
|
||||
channel: snapshot
|
||||
release_tag: snapshot
|
||||
archive_name: ${{ format('GPConnect_{0}-snapshot.{1}_arm64.zip', needs.validate-inputs.outputs.version, needs.validate-inputs.outputs.build_version) }}
|
||||
expected_gui: ${{ inputs.macos_gui }}
|
||||
unix_platforms: ${{ (inputs.build_bsd || inputs.build_bsd_arm64) && 'linux,freebsd,openbsd' || 'linux' }}
|
||||
highlights: Development snapshot.
|
||||
secrets: inherit
|
||||
|
||||
publish-docker-image:
|
||||
needs:
|
||||
- validate-inputs
|
||||
|
||||
@@ -54,6 +54,7 @@ jobs:
|
||||
gettext \
|
||||
gmp \
|
||||
gnutls \
|
||||
libappindicator-gtk3 \
|
||||
libp11-kit \
|
||||
libsecret \
|
||||
libtool \
|
||||
|
||||
@@ -1,21 +1,6 @@
|
||||
name: Publish macOS assets
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
build_run_id:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
expected_gui:
|
||||
required: false
|
||||
default: nsh
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: false
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_run_id:
|
||||
|
||||
@@ -34,10 +34,6 @@ on:
|
||||
highlights:
|
||||
required: false
|
||||
type: string
|
||||
unix_snapshot_build:
|
||||
description: Verified Unix snapshot build when it differs from the macOS retry
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
required: false
|
||||
default: linux,freebsd,openbsd
|
||||
@@ -79,10 +75,6 @@ on:
|
||||
description: Stable release highlights, one per line
|
||||
required: false
|
||||
type: string
|
||||
unix_snapshot_build:
|
||||
description: Verified Unix snapshot build; omit when it matches the macOS build
|
||||
required: false
|
||||
type: string
|
||||
unix_platforms:
|
||||
description: Comma-separated Unix platforms with published assets (linux,freebsd,openbsd)
|
||||
required: true
|
||||
@@ -95,8 +87,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
# Feed verification runs host tools, so it can use Intel runner capacity.
|
||||
runs-on: macos-26-intel
|
||||
runs-on: ${{ vars.MACOS_RUNNER || 'macos-15' }}
|
||||
environment: macos-release
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -112,7 +103,6 @@ jobs:
|
||||
SPARKLE_VERSION: 2.9.2
|
||||
UPDATE_HIGHLIGHTS: ${{ inputs.highlights }}
|
||||
UNIX_PLATFORMS: ${{ inputs.unix_platforms }}
|
||||
UNIX_SNAPSHOT_BUILD: ${{ inputs.unix_snapshot_build }}
|
||||
SPARKLE_ARCHIVE_SHA256: b83e37436774556ed055e0244b297ef2c790e0737393bf65bf495fcbba6eed65
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
@@ -135,12 +125,6 @@ jobs:
|
||||
echo "unix_platforms must list published Unix targets separated by commas" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -n "$UNIX_SNAPSHOT_BUILD" ]]; then
|
||||
if [[ "$CHANNEL" != "snapshot" || ! "$UNIX_SNAPSHOT_BUILD" =~ ^(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*)){0,2}$ ]]; then
|
||||
echo "unix_snapshot_build requires a snapshot channel and one to three numeric components" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if [[ "$CHANNEL" == "snapshot" && "$RELEASE_TAG" != "snapshot" ]]; then
|
||||
echo "The snapshot channel must publish to the snapshot release" >&2
|
||||
exit 1
|
||||
@@ -359,7 +343,6 @@ jobs:
|
||||
echo "short_version=$short_version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Prepare Unix update manifest
|
||||
id: unix_manifest
|
||||
env:
|
||||
RELEASED_AT: ${{ steps.release.outputs.released_at }}
|
||||
run: |
|
||||
@@ -400,8 +383,7 @@ jobs:
|
||||
else
|
||||
printf 'Development snapshot after %s.\n' \
|
||||
"${{ steps.bundle.outputs.short_version }}" > "$highlights"
|
||||
unix_build="${UNIX_SNAPSHOT_BUILD:-${{ steps.bundle.outputs.version }}}"
|
||||
generate_args+=(--build "$unix_build")
|
||||
generate_args+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
released_at="$(date -u +%F)"
|
||||
fi
|
||||
|
||||
@@ -410,9 +392,6 @@ jobs:
|
||||
--released-at "$released_at" \
|
||||
--highlights-file "$highlights" \
|
||||
--output "$manifest"
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
echo "build=$unix_build" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Fetch current appcast
|
||||
id: current-appcast
|
||||
@@ -548,13 +527,6 @@ jobs:
|
||||
--channel "$CHANNEL" \
|
||||
--archive-url "https://github.com/$REPOSITORY/releases/download/$RELEASE_TAG/$ARCHIVE_NAME"
|
||||
|
||||
- name: Preserve other platform feeds
|
||||
run: |
|
||||
python3 scripts/preserve-update-feeds.py \
|
||||
--base-url "${FEED_URL%/appcast.xml}" \
|
||||
--directory gpgui/apps/update-feed-worker/public \
|
||||
--exclude appcast.xml --exclude latest.json
|
||||
|
||||
- name: Deploy update feed worker
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
@@ -608,7 +580,7 @@ jobs:
|
||||
--version "${{ steps.bundle.outputs.short_version }}"
|
||||
)
|
||||
if [[ "$CHANNEL" == "snapshot" ]]; then
|
||||
expected+=(--build "${{ steps.unix_manifest.outputs.build }}")
|
||||
expected+=(--build "${{ steps.bundle.outputs.version }}")
|
||||
fi
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl --fail --location --silent --show-error \
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
name: Publish Windows update feed
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
gpgui_ref:
|
||||
required: true
|
||||
type: string
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
required: true
|
||||
type: string
|
||||
channel:
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
required: true
|
||||
type: string
|
||||
highlights:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
GH_PAT:
|
||||
required: true
|
||||
CLOUDFLARE_ACCOUNT_ID:
|
||||
required: false
|
||||
CLOUDFLARE_API_TOKEN:
|
||||
required: false
|
||||
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" }
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
name: Verify public Windows release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Published snapshot or stable release tag
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
description: Base product version
|
||||
required: true
|
||||
type: string
|
||||
build:
|
||||
description: Numeric snapshot build; empty for stable
|
||||
type: string
|
||||
gpgui_ref:
|
||||
description: Matching GUI source ref containing the pinned update tools
|
||||
required: true
|
||||
default: release/next
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
architecture: [x64, arm64]
|
||||
runs-on: ${{ matrix.architecture == 'arm64' && 'windows-11-arm' || 'windows-2022' }}
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
PRODUCT_VERSION: ${{ inputs.version }}
|
||||
BUILD_VERSION: ${{ inputs.build }}
|
||||
ARCHITECTURE: ${{ matrix.architecture }}
|
||||
WINDOWS_UPDATE_PUBLIC_KEY: ${{ vars.WINDOWS_UPDATE_PUBLIC_KEY }}
|
||||
WINDOWS_SIGNING_PUBLISHER: ${{ vars.WINDOWS_SIGNING_PUBLISHER }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.release_tag == 'snapshot' && 'release/next' || inputs.release_tag }}
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/checkout-private
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
ref: ${{ inputs.gpgui_ref }}
|
||||
path: gpgui
|
||||
- name: Download, verify, install and uninstall the public installer
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:PRODUCT_VERSION -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid product version.' }
|
||||
if (!$env:WINDOWS_UPDATE_PUBLIC_KEY -or !$env:WINDOWS_SIGNING_PUBLISHER) { throw 'Configure the update key and signing publisher.' }
|
||||
$displayVersion = $env:PRODUCT_VERSION
|
||||
if ($env:RELEASE_TAG -eq 'snapshot') {
|
||||
if ($env:BUILD_VERSION -notmatch '^\d+(\.\d+){0,2}$') { throw 'Invalid snapshot build.' }
|
||||
$displayVersion += "-snapshot.$env:BUILD_VERSION"
|
||||
} elseif ($env:RELEASE_TAG -ne "v$env:PRODUCT_VERSION" -or $env:BUILD_VERSION) { throw 'Stable release identity does not match.' }
|
||||
$name = "GPConnect_${displayVersion}_windows-$env:ARCHITECTURE-setup.exe"
|
||||
$downloads = Join-Path $env:RUNNER_TEMP 'public-windows-release'
|
||||
New-Item -ItemType Directory $downloads | Out-Null
|
||||
foreach ($asset in @($name, "$name.sha256", "$name.sig")) {
|
||||
gh release download $env:RELEASE_TAG --repo $env:GITHUB_REPOSITORY --pattern $asset --dir $downloads
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not download $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 checksum file.' }
|
||||
$hash = (Get-FileHash $installer).Hash
|
||||
if ($hash -ne $Matches[1]) { throw 'Installer checksum mismatch.' }
|
||||
if ([Diagnostics.FileVersionInfo]::GetVersionInfo($installer).ProductVersion -ne $displayVersion) { throw 'Installer version mismatch.' }
|
||||
& ./scripts/test-windows-signature.ps1 -Files $installer -Publisher $env:WINDOWS_SIGNING_PUBLISHER
|
||||
. ./gpgui/scripts/windows-updates/Get-WinSparkle.ps1
|
||||
$tools = Get-WinSparkleTools (Join-Path $env:RUNNER_TEMP 'winsparkle-tools') -Architecture $env:ARCHITECTURE
|
||||
$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.' }
|
||||
& ./scripts/test-windows-installer.ps1 -Installer $installer -Architecture $env:ARCHITECTURE -Build $env:BUILD_VERSION
|
||||
@{ release = $env:RELEASE_TAG; version = $displayVersion; architecture = $env:ARCHITECTURE;
|
||||
sha256 = $hash.ToLowerInvariant(); publisher = $env:WINDOWS_SIGNING_PUBLISHER;
|
||||
authenticode = 'Valid'; timestamped = $true; update_signature = 'Valid';
|
||||
installed_signatures = 'Valid'; install_uninstall = 'Passed'
|
||||
} | ConvertTo-Json | Set-Content verification.json -Encoding utf8
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: windows-release-verification-${{ matrix.architecture }}
|
||||
path: verification.json
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
@@ -16,6 +16,3 @@ gen
|
||||
|
||||
# Nix files
|
||||
result
|
||||
|
||||
# Packages & test assets
|
||||
*.ipa
|
||||
Generated
+23
-15
@@ -292,7 +292,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "auth"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"block2",
|
||||
@@ -547,7 +547,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "browser-launcher"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"log",
|
||||
@@ -911,7 +911,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
@@ -2115,7 +2115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpapi"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2124,7 +2124,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
"clap-verbosity-flag",
|
||||
"cms",
|
||||
"common",
|
||||
"directories",
|
||||
"dns-lookup",
|
||||
@@ -2143,7 +2142,6 @@ dependencies = [
|
||||
"oslog",
|
||||
"p12-keystore",
|
||||
"pem",
|
||||
"pkcs12",
|
||||
"pkcs8",
|
||||
"pkg-config",
|
||||
"proptest",
|
||||
@@ -2151,7 +2149,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"rustls-pemfile",
|
||||
"rustls-platform-verifier",
|
||||
"sec1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
@@ -2176,7 +2174,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpauth"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"auth",
|
||||
@@ -2195,7 +2193,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpclient"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2226,7 +2224,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpgui-helper"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2247,7 +2245,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gphip"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"askama",
|
||||
@@ -2264,7 +2262,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpservice"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -2299,7 +2297,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gptunnel"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"gpapi",
|
||||
"log",
|
||||
@@ -2311,7 +2309,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gpvpnc"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
@@ -3825,7 +3823,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openconnect"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
dependencies = [
|
||||
"autotools",
|
||||
"cc",
|
||||
@@ -4882,6 +4880,16 @@ dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"
|
||||
dependencies = [
|
||||
"der",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
|
||||
+2
-1
@@ -11,7 +11,7 @@ members = [
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.91"
|
||||
version = "3.4.0"
|
||||
version = "3.2.0"
|
||||
authors = ["Kevin Yue <[email protected]>"]
|
||||
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
edition = "2024"
|
||||
@@ -24,6 +24,7 @@ base64 = { version = "0.23", default-features = false, features = ["std"] }
|
||||
chrono = "0.4"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap-verbosity-flag = "3"
|
||||
ctrlc = "3.4"
|
||||
directories = "6.0"
|
||||
dns-lookup = "4.0.2"
|
||||
env_logger = "0.11"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# GlobalProtect-openconnect
|
||||
|
||||
A GlobalProtect VPN client built on OpenConnect. It provides command-line tools (`gpclient`) and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
|
||||
> **Disclaimer**: GP Connect is an independent third-party client for GlobalProtect VPN networks. It is not affiliated with or endorsed by Palo Alto Networks, Inc.
|
||||
A GlobalProtect VPN client built on OpenConnect with support for SSO authentication. It provides command-line tools and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
|
||||
|
||||
<p align="center">
|
||||
<picture>
|
||||
@@ -24,89 +22,147 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools
|
||||
- [macOS](#macos)
|
||||
- [Debian / Ubuntu](#debian--ubuntu)
|
||||
- [Arch Linux / Manjaro](#arch-linux--manjaro)
|
||||
- [Fedora / RHEL](#fedora--rhel)
|
||||
- [openSUSE](#opensuse)
|
||||
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
|
||||
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
|
||||
- [Other RPM-based Distributions](#other-rpm-based-distributions)
|
||||
- [Alpine Linux](#alpine-linux)
|
||||
- [FreeBSD](#freebsd)
|
||||
- [OpenBSD](#openbsd)
|
||||
- [Gentoo](#gentoo)
|
||||
- [NixOS](#nixos)
|
||||
- [Docker](#docker)
|
||||
- [Official Docker Image](#official-docker-image)
|
||||
- [Other Distributions](#other-distributions)
|
||||
- [Building from Source](#building-from-source)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Frequently Asked Questions](#frequently-asked-questions)
|
||||
- [NetworkManager Integration](#networkmanager-integration)
|
||||
- [Licensing](#licensing)
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**)
|
||||
- **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
|
||||
- **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
|
||||
- **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
|
||||
- **Automated HIP Reports** – Built-in HIP report generation or custom scripts
|
||||
- **Multi-Portal & Direct Gateway** – Manage multiple saved portals or connect directly to a gateway
|
||||
- **Desktop Integration** – Theme-aware system tray icon, auto-connect on launch, and reconnect on wake
|
||||
- **Desktop Platform Support** – macOS, Linux, FreeBSD, and OpenBSD
|
||||
- **Dual Interface** – Available as both CLI and GUI applications
|
||||
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
|
||||
- **Browser Integration** – Authenticate using your default browser or any specified browser
|
||||
- **Multi-Portal Support** – Connect to multiple portals and gateways
|
||||
- **Direct Gateway Connection** – Bypass portal selection when needed
|
||||
- **Auto-Connect** – Automatically connect on system startup
|
||||
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME)
|
||||
|
||||
## Usage
|
||||
|
||||
### Command-Line Interface
|
||||
|
||||
The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
|
||||
The CLI is free and open source. Use it to authenticate, connect to portals or gateways, and generate HIP reports from the terminal.
|
||||
|
||||
#### Basic Commands
|
||||
|
||||
```bash
|
||||
# Connect to a portal server
|
||||
sudo gpclient connect <portal>
|
||||
Usage: gpclient [OPTIONS] <COMMAND>
|
||||
|
||||
# Connect using browser authentication (SSO / SAML)
|
||||
sudo gpclient connect <portal> --browser
|
||||
Commands:
|
||||
connect Connect to a portal server
|
||||
disconnect Disconnect from the server
|
||||
launch-gui Launch the GUI
|
||||
hip Generate HIP report
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
# Connect directly to a gateway server
|
||||
sudo gpclient connect <gateway> --as-gateway
|
||||
|
||||
# Connect with automatic HIP report generation
|
||||
sudo gpclient connect <portal> --hip
|
||||
|
||||
# Headless / remote server authentication (prints auth URL to open in any browser)
|
||||
sudo gpclient connect <portal> --browser manual
|
||||
|
||||
# Disconnect
|
||||
sudo gpclient disconnect
|
||||
Options:
|
||||
--ignore-tls-errors Ignore the TLS errors
|
||||
--lock-file <LOCK_FILE> Path to the gpclient PID lock file
|
||||
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
|
||||
-v, --verbose... Enable verbose output, -v for debug, -vv for trace
|
||||
-q, --quiet... Decrease logging verbosity, -q for warnings, -qq for errors
|
||||
-h, --help Print help (see more with '--help')
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
Run `gpclient --help` or `gpclient <command> --help` to view all available commands and options.
|
||||
|
||||
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
|
||||
|
||||
#### HIP reports
|
||||
|
||||
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --hip
|
||||
```
|
||||
|
||||
Use `--hip=/absolute/path/to/script` for a custom executable. It runs as the `gpclient` process user unless `--hip-user` specifies another user. No installed HIP script is discovered automatically. `--hip-user` applies only to custom executables.
|
||||
|
||||
`gpclient hip` generates a report on demand for inspection; see `gpclient hip --help` for report inputs. The GUI's HIP tab supports generated reports, edited XML, and HIP Off on all desktop platforms. Linux, FreeBSD, and OpenBSD also support desktop-user scripts and explicitly approved root scripts.
|
||||
|
||||
#### External Browser Authentication
|
||||
|
||||
Use `gpclient` directly for browser-based authentication. It opens the browser as your normal desktop user while keeping VPN tunnel setup privileged:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
For standalone CLI installations, use `--browser manual` (`--browser remote` before v3.0.6): open the printed URL and paste the resulting `globalprotectcallback:…` data into the terminal.
|
||||
|
||||
To reuse a saved portal cookie for later connections, add `--cookie-cache`:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser --cookie-cache
|
||||
```
|
||||
|
||||
Add `--gateway <gateway>` to select a particular gateway. Cookie caching is handled by `gpclient`. Its default cache file is `$HOME/.config/gpclient/cookie.json`, which normally belongs to root when running with `sudo`. To choose a predictable location, specify the path explicitly:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser --cookie-cache=/absolute/path/to/cookie.json
|
||||
```
|
||||
|
||||
**Browser Options:**
|
||||
|
||||
- Use `--browser` to automatically select an available browser
|
||||
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
|
||||
- Use `--browser manual` for standalone CLI installations or headless servers
|
||||
|
||||
### Graphical User Interface
|
||||
|
||||
- **macOS**: Open **GP Connect** from Applications.
|
||||
- **Linux / BSD**: Launch GP Connect from your application menu or run:
|
||||
```bash
|
||||
gpclient launch-gui
|
||||
```
|
||||
GP Connect provides a desktop interface for managing VPN connections. On macOS, open GP Connect from Applications. On Linux, FreeBSD, and OpenBSD, launch it from your application menu or via the terminal:
|
||||
|
||||
```bash
|
||||
gpclient launch-gui
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **On Linux, try Native Shell for lower memory usage.** Switch between Native Shell and Tauri in **Settings → General → Interface**.
|
||||
> **On Linux, try Native Shell for lower memory usage.** Switch to it in **Settings → General → Interface**.
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> The GUI version is partially open source. The background service ([gpservice](./apps/gpservice/)) is open source, while the GUI wrapper is proprietary.
|
||||
|
||||
## Installation
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
|
||||
|
||||
### macOS
|
||||
|
||||
Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
|
||||
GP Connect requires Apple silicon and macOS 13 or later. The macOS app includes both the desktop application and the free `gpclient` CLI. The CLI does not require a GUI license.
|
||||
|
||||
#### Option 1: Homebrew (Recommended)
|
||||
#### Option 1: Install with Homebrew
|
||||
|
||||
```bash
|
||||
brew install --cask yuezk/gp-connect/gp-connect
|
||||
```
|
||||
|
||||
#### Option 2: DMG Installer
|
||||
Open GP Connect from Applications, or connect from the terminal:
|
||||
|
||||
Download the `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page and drag GP Connect into Applications.
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
#### Option 2: Install from DMG
|
||||
|
||||
Download the GP Connect `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, open it, and drag GP Connect into Applications.
|
||||
|
||||
### Debian / Ubuntu
|
||||
|
||||
#### Option 1: PPA (Recommended)
|
||||
#### Option 1: Install from PPA (Recommended)
|
||||
|
||||
```bash
|
||||
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
|
||||
@@ -114,152 +170,392 @@ sudo apt-get update
|
||||
sudo apt-get install globalprotect-openconnect
|
||||
```
|
||||
|
||||
#### Option 2: DEB Package
|
||||
> [!Note]
|
||||
>
|
||||
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually:
|
||||
> ```bash
|
||||
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
|
||||
> ```
|
||||
|
||||
Download the latest `.deb` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
#### Option 2: Install from DEB Package
|
||||
|
||||
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo apt install ./globalprotect-openconnect_*.deb
|
||||
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb
|
||||
```
|
||||
|
||||
### Arch Linux / Manjaro
|
||||
|
||||
```bash
|
||||
# Official Extra repository
|
||||
sudo pacman -S globalprotect-openconnect
|
||||
#### Option 1: Install from AUR
|
||||
|
||||
# AUR (git main)
|
||||
Package: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
|
||||
|
||||
You can install it using an AUR helper like [`yay`](https://github.com/Jguer/yay):
|
||||
|
||||
```bash
|
||||
yay -S globalprotect-openconnect-git
|
||||
```
|
||||
|
||||
### Fedora / RHEL
|
||||
#### Option 2: Install from the Official Extra Repository
|
||||
|
||||
Enable the COPR repository:
|
||||
The package is also available in the official Arch Linux Extra repository.
|
||||
|
||||
Package: [globalprotect-openconnect](https://archlinux.org/packages/extra/x86_64/globalprotect-openconnect/)
|
||||
|
||||
> [!Note]
|
||||
>
|
||||
> Since the official package does not include the system tray support dependency, you need to install `libappindicator` manually:
|
||||
|
||||
```bash
|
||||
sudo pacman -S libappindicator globalprotect-openconnect
|
||||
```
|
||||
|
||||
#### Option 3: Install from Package
|
||||
|
||||
Download the latest package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
|
||||
```
|
||||
|
||||
### Fedora 38+ / Rawhide
|
||||
|
||||
#### Install from COPR
|
||||
|
||||
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for RPM-based distributions:
|
||||
|
||||
```bash
|
||||
sudo dnf copr enable yuezk/globalprotect-openconnect
|
||||
sudo dnf install globalprotect-openconnect
|
||||
```
|
||||
|
||||
### openSUSE
|
||||
### openSUSE Leap 15.6+ / Tumbleweed
|
||||
|
||||
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [OBS instructions](https://software.opensuse.org/download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
||||
#### Install from OBS (openSUSE Build Service)
|
||||
|
||||
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [installation instructions](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
|
||||
|
||||
### Other RPM-based Distributions
|
||||
|
||||
#### Install from RPM Package
|
||||
|
||||
Download the latest RPM package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
|
||||
```bash
|
||||
sudo rpm -i globalprotect-openconnect-*.rpm
|
||||
```
|
||||
|
||||
### Alpine Linux
|
||||
|
||||
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
|
||||
```
|
||||
|
||||
*(Requires `community` repository enabled for WebKitGTK and AppIndicator dependencies).*
|
||||
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
|
||||
```
|
||||
|
||||
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
|
||||
### OpenBSD
|
||||
|
||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
|
||||
|
||||
```bash
|
||||
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
|
||||
```
|
||||
|
||||
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
|
||||
### Gentoo
|
||||
|
||||
Available via the `guru` repository:
|
||||
Available via the `guru` and `lamdness` overlays:
|
||||
|
||||
```bash
|
||||
sudo eselect repository enable guru
|
||||
sudo emerge --sync guru
|
||||
sudo emerge --ask net-vpn/GlobalProtect-openconnect
|
||||
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
|
||||
```
|
||||
|
||||
### NixOS
|
||||
|
||||
Add the flake to your `flake.nix`:
|
||||
This repository includes a flake for NixOS integration.
|
||||
|
||||
#### Installation Steps
|
||||
|
||||
Add the flake input and NixOS module to your `flake.nix`:
|
||||
|
||||
The module builds the package with your NixOS configuration's `pkgs`, so the
|
||||
GlobalProtect GUI and the system use the same Nixpkgs dependency versions.
|
||||
It also enables Polkit and its setuid `pkexec` wrapper for privileged operations.
|
||||
|
||||
```nix
|
||||
{
|
||||
inputs.globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
||||
inputs = {
|
||||
# ... other inputs
|
||||
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, globalprotect-openconnect, ... }: {
|
||||
nixosConfigurations.<hostname> = nixpkgs.lib.nixosSystem {
|
||||
modules = [
|
||||
globalprotect-openconnect.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
}
|
||||
];
|
||||
outputs = { self, nixpkgs, globalprotect-openconnect, ... }:
|
||||
let
|
||||
system = "x86_64-linux"; # or "aarch64-linux" for ARM64
|
||||
hostname = "<your-host>";
|
||||
in {
|
||||
nixosConfigurations.${hostname} = nixpkgs.lib.nixosSystem {
|
||||
inherit system;
|
||||
|
||||
modules = [
|
||||
./configuration.nix
|
||||
globalprotect-openconnect.nixosModules.default
|
||||
{
|
||||
programs.globalprotect-openconnect.enable = true;
|
||||
|
||||
environment.systemPackages = [
|
||||
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Apply changes:
|
||||
Apply:
|
||||
|
||||
```bash
|
||||
sudo nixos-rebuild switch
|
||||
loginctl terminate-user "$USER"
|
||||
```
|
||||
|
||||
### Docker
|
||||
After logging back in to GNOME, enable AppIndicator support if needed:
|
||||
|
||||
Run the CLI client in an official Alpine container:
|
||||
```bash
|
||||
gnome-extensions enable [email protected]
|
||||
```
|
||||
|
||||
NixOS does not run an imperative package-uninstall hook when a package is
|
||||
removed from the system configuration. Remove an installed replacement VPN
|
||||
script from the app settings before removing the package.
|
||||
|
||||
The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. Both `prebuilt` and `fromSource` run natively on the host with packaged dependencies and installer paths. The `fromSource` package builds the current flake checkout, including its Git submodules:
|
||||
|
||||
```bash
|
||||
git submodule update --init --recursive
|
||||
nix build "git+file://$PWD?submodules=1#fromSource"
|
||||
```
|
||||
|
||||
Local source builds require initialized Git submodules and a flake URL with `submodules=1`, as shown above. For a remote source flake, use a Git URL with submodules enabled, such as `git+https://github.com/yuezk/GlobalProtect-openconnect?submodules=1#fromSource`. The `prebuilt` package and NixOS module do not require Git submodules. Build output (`target`, `.build`, and `node_modules`) is excluded from the source input. Updating release asset hashes changes the prebuilt package, independently of source builds.
|
||||
|
||||
Source builds also support downloading either desktop interface on NixOS. The
|
||||
downloader packages the verified Tauri or Native Shell archive with Nix, including
|
||||
its runtime libraries. Each installed interface has a garbage-collection root
|
||||
under `/var/lib/gpclient/nix-gui`, so its dependencies remain available after
|
||||
system upgrades. No Rust compilation or NixOS rebuild is needed for GUI downloads.
|
||||
Prebuilt packages gain this support when their release includes the updated
|
||||
service; adding the flake installer alone does not change older service binaries.
|
||||
|
||||
### Official Docker Image
|
||||
|
||||
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
|
||||
|
||||
```bash
|
||||
docker pull yuezk/globalprotect-openconnect:<version>
|
||||
```
|
||||
|
||||
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
|
||||
|
||||
Run it with access to the TUN device:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:latest \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal>
|
||||
```
|
||||
|
||||
For browser authentication in a headless environment, use manual browser authentication:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
*(Add `--network host` on Linux if VPN routes should apply to the host network).*
|
||||
On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine:
|
||||
|
||||
```bash
|
||||
gpclient connect <portal> --browser manual --browser-listen 192.168.107.15
|
||||
```
|
||||
|
||||
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
|
||||
|
||||
```bash
|
||||
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
yuezk/globalprotect-openconnect:<version> \
|
||||
connect <portal> --browser manual
|
||||
```
|
||||
|
||||
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
|
||||
|
||||
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
|
||||
|
||||
### Other Distributions
|
||||
|
||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
#### Manual Installation
|
||||
|
||||
```bash
|
||||
tar -xJf globalprotect-openconnect_*.bin.tar.xz
|
||||
cd globalprotect-openconnect_*
|
||||
sudo make install
|
||||
```
|
||||
1. **Install dependencies:**
|
||||
- WebKitGTK 4.1 (for example, `libwebkit2gtk-4.1-0` on Debian/Ubuntu)
|
||||
- `libsecret`
|
||||
- `libayatana-appindicator` or `libappindicator-gtk3`
|
||||
- polkit (`pkexec`) for GUI-launched VPN connections
|
||||
|
||||
2. **Download and extract:**
|
||||
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
|
||||
```bash
|
||||
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
|
||||
cd globalprotect-openconnect_${version}
|
||||
```
|
||||
|
||||
3. **Install:**
|
||||
```bash
|
||||
sudo make install
|
||||
```
|
||||
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites (Linux)
|
||||
The instructions below build the open-source components on Linux. For FreeBSD and OpenBSD, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
|
||||
|
||||
- [Rust](https://www.rust-lang.org/tools/install) 1.91 or later
|
||||
- Build tools: `make`, `pkg-config`, `autoconf`, `automake`, `libtool`, `gettext`
|
||||
- Libraries: `gmp`, `gnutls`, `nettle`, `libxml2`, `zlib`, `lz4`, `p11-kit`, `libsecret`, and `webkit2gtk-4.1` (or GTK 4 for Native Shell)
|
||||
- Polkit (`pkexec`) for privileged tunnel setup
|
||||
### Method 1: Using DevContainer
|
||||
|
||||
*(For FreeBSD and OpenBSD instructions, see [Building from Source on FreeBSD and OpenBSD](docs/bsd-source-build.md)).*
|
||||
This project includes a DevContainer configuration for Linux development. The repository's `rust-toolchain.toml` selects the Rust toolchain; rustup may need to download it on the first build.
|
||||
|
||||
### Build Steps
|
||||
#### Prerequisites
|
||||
|
||||
- [Docker](https://docs.docker.com/get-docker/)
|
||||
- [Visual Studio Code](https://code.visualstudio.com/) (optional, for IDE support)
|
||||
- [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (if using VS Code)
|
||||
|
||||
#### Build Steps
|
||||
|
||||
1. **Clone the repository:**
|
||||
```bash
|
||||
git clone https://github.com/yuezk/GlobalProtect-openconnect.git
|
||||
cd GlobalProtect-openconnect
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
2. **Build the DevContainer image:**
|
||||
```bash
|
||||
docker build -t gpoc-devcontainer .devcontainer/
|
||||
```
|
||||
|
||||
3. **Build the project:**
|
||||
|
||||
To build the open-source components, including the GUI helper, run:
|
||||
```bash
|
||||
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
|
||||
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
|
||||
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
|
||||
```
|
||||
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
|
||||
|
||||
4. **Locate build artifacts:**
|
||||
|
||||
The compiled binaries will be available in `target/release/`:
|
||||
- `gpclient` – CLI client
|
||||
- `gpservice` – Background service
|
||||
- `gpauth` – Authentication helper
|
||||
- `gpgui-helper` – GUI helper
|
||||
- `gp-hip-script-installer` – Privileged HIP script installer
|
||||
- `gp-vpnc-script-installer` – Privileged VPN script installer
|
||||
|
||||
The proprietary GP Connect desktop application is distributed separately. Use `INCLUDE_GUI=1` with `make build` to download its matching published Linux build for installation.
|
||||
|
||||
#### Alternative: Using VS Code
|
||||
|
||||
1. Open the project in VS Code
|
||||
2. When prompted, click "Reopen in Container" (or run **Dev Containers: Reopen in Container**)
|
||||
3. Once the container is ready, open a terminal and run:
|
||||
```bash
|
||||
make build
|
||||
```
|
||||
|
||||
### Method 2: Local Development Build
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
- [Rust 1.91 or later](https://www.rust-lang.org/tools/install)
|
||||
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
|
||||
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
|
||||
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
|
||||
- Node.js and pnpm if rebuilding the GUI helper frontend
|
||||
|
||||
#### Build Steps
|
||||
|
||||
1. **Download source code:**
|
||||
|
||||
Download `globalprotect-openconnect-${version}.tar.gz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
|
||||
|
||||
2. **Extract and build:**
|
||||
```bash
|
||||
tar -xzf globalprotect-openconnect-${version}.tar.gz
|
||||
cd globalprotect-openconnect-${version}
|
||||
make build
|
||||
```
|
||||
|
||||
3. **Install:**
|
||||
```bash
|
||||
sudo make install
|
||||
```
|
||||
|
||||
To stage the files for packaging instead of installing them into the system, use `make install DESTDIR=/absolute/path/to/staging`.
|
||||
|
||||
### Testing Your Build
|
||||
|
||||
Verify the CLI client is working correctly:
|
||||
|
||||
```bash
|
||||
git clone --recursive https://github.com/yuezk/GlobalProtect-openconnect.git
|
||||
cd GlobalProtect-openconnect
|
||||
make build
|
||||
sudo make install
|
||||
./target/release/gpclient --help
|
||||
```
|
||||
|
||||
**Build Options:**
|
||||
### Build Options
|
||||
|
||||
- `INCLUDE_GUI=1` – Download and install the matching desktop application bundle.
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication (uses external browser or manual mode).
|
||||
- `BUILD_GUI_HELPER=0` – Skip building the helper UI.
|
||||
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper
|
||||
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external browser or manual authentication
|
||||
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
|
||||
- `OFFLINE=1` – Build in offline mode using vendored dependencies
|
||||
|
||||
## Troubleshooting
|
||||
## Frequently Asked Questions
|
||||
|
||||
- **Headless / Remote Login**: When running without a desktop display or over SSH, use `--browser manual`. Open the printed URL in any browser and paste the callback URL back into the terminal.
|
||||
- **Diagnostics**: If you encounter issues, run `gpclient diagnostics` or follow the [diagnostics guide](docs/diagnostics.md) when opening an issue.
|
||||
When reporting a problem, follow the [diagnostics collection instructions](docs/diagnostics.md). A standalone script is available for versions without the diagnostics command; you do not need to upgrade first.
|
||||
|
||||
### Q: How do I resolve the "Secure Storage not ready" error?
|
||||
|
||||
Unlock your desktop keyring and ensure the application can access it. On Linux and BSD, check that a keyring service such as GNOME Keyring is installed and running in your desktop session. On macOS, check Keychain access.
|
||||
|
||||
Linux and BSD can use file storage when secure storage is unavailable during initial setup. An existing configuration that uses the keyring still needs access to that keyring.
|
||||
|
||||
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
### Q: How do I fix the "cannot open display" error when using CLI?
|
||||
|
||||
Run the client from a terminal in your normal desktop session and use an external browser:
|
||||
|
||||
```bash
|
||||
sudo gpclient connect <portal> --browser
|
||||
```
|
||||
|
||||
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
|
||||
|
||||
On a headless server, use `--browser manual` and complete authentication from another machine.
|
||||
|
||||
## NetworkManager Integration
|
||||
|
||||
@@ -268,10 +564,14 @@ sudo make install
|
||||
|
||||
## Licensing
|
||||
|
||||
- **CLI (`gpclient`)**: Free and open source (GPL-3.0).
|
||||
- **GUI (GP Connect)**: Commercial desktop application with a free trial.
|
||||
### Trial and Pricing
|
||||
|
||||
### Open Source Components
|
||||
The **CLI version** is completely free and open source.
|
||||
The **GUI version** is a paid application with a **7-day trial**. Start the trial in the app by verifying your email address with a one-time code. Installing the app alone does not start the trial.
|
||||
|
||||
### Open Source Licenses
|
||||
|
||||
This project consists of multiple components, each with its own license:
|
||||
|
||||
| Component | Type | License |
|
||||
|-----------|------|---------|
|
||||
|
||||
@@ -36,27 +36,6 @@ fn login_response() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
return String::from_utf8(request).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
@@ -65,7 +44,25 @@ async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
requests.push(read_request(&mut stream).await);
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
@@ -129,138 +126,6 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreachable_gateway_keeps_cached_cookie() {
|
||||
// Nothing listens here: the cached gateway login gets no answer at all.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let gateway = format!("http://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(handler.handle_impl().await.is_err());
|
||||
assert!(
|
||||
cache.exists(),
|
||||
"a login that got no answer must not delete the cookie cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_closing_without_response_keeps_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn portal_closing_without_response_keeps_cached_cookie() {
|
||||
closed_connection_keeps_cached_cookie(true).await;
|
||||
}
|
||||
|
||||
async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = tokio::spawn(async move {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
if portal_discovery {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
assert!(read_request(&mut stream).await.contains("/global-protect/prelogin.esp"));
|
||||
let body = "<prelogin-response><status>Success</status></prelogin-response>";
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
// Read the complete request, then close without sending HTTP headers.
|
||||
read_request(&mut stream).await
|
||||
})
|
||||
.await
|
||||
.expect("Connection-closing fixture timed out")
|
||||
});
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
&origin,
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
origin.clone(),
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let result = if portal_discovery {
|
||||
handler.connect_portal_with_prelogin(&origin).await
|
||||
} else {
|
||||
handler.handle_impl().await
|
||||
};
|
||||
let error = result.unwrap_err();
|
||||
let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else {
|
||||
panic!("Expected a network error, got {error:?}");
|
||||
};
|
||||
assert!(network.is_request());
|
||||
assert!(!network.is_connect());
|
||||
assert!(!network.is_timeout());
|
||||
assert!(cache.exists(), "an unanswered request must not delete the cookie cache");
|
||||
let request = worker.await.unwrap();
|
||||
assert!(request.contains("portal-cookie"));
|
||||
if portal_discovery {
|
||||
assert!(request.starts_with("POST /global-protect/getconfig.esp "));
|
||||
} else {
|
||||
assert!(request.starts_with("POST /ssl-vpn/login.esp "));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
@@ -646,62 +511,3 @@ printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_and_malformed_identities_fail_before_password_prompt_or_network_connection() {
|
||||
use gpapi::utils::request::RequestIdentityError;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let malformed = directory.path().join("invalid.p12");
|
||||
std::fs::write(&malformed, b"not a certificate archive").unwrap();
|
||||
let fixtures =
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/gpapi/tests/files/client-identity");
|
||||
|
||||
for (certificate, key, expected) in [
|
||||
(
|
||||
fixtures.join("rsa-pss-cert.pem"),
|
||||
Some(fixtures.join("rsa-pss.pem")),
|
||||
"algorithm",
|
||||
),
|
||||
(fixtures.join("legacy-RC2-128.p12"), None, "encryption"),
|
||||
(malformed, None, "malformed"),
|
||||
] {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let server = format!("https://{}", listener.local_addr().unwrap());
|
||||
let mut argv = vec![
|
||||
"test".to_owned(),
|
||||
server,
|
||||
"--as-gateway".to_owned(),
|
||||
"--certificate".to_owned(),
|
||||
certificate.to_string_lossy().into_owned(),
|
||||
];
|
||||
if let Some(key) = key {
|
||||
argv.extend(["--sslkey".to_owned(), key.to_string_lossy().into_owned()]);
|
||||
}
|
||||
let args = TestArgs::parse_from(argv).connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: false,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
let error = tokio::time::timeout(Duration::from_secs(2), handler.handle_attempt())
|
||||
.await
|
||||
.expect("identity failure must not wait for a password or server")
|
||||
.unwrap_err();
|
||||
match (expected, error.downcast_ref::<RequestIdentityError>()) {
|
||||
("algorithm", Some(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"))) => {}
|
||||
("encryption", Some(RequestIdentityError::UnsupportedEncryption)) => {}
|
||||
("malformed", Some(RequestIdentityError::InvalidPkcs12(_) | RequestIdentityError::InvalidCertificate)) => {}
|
||||
_ => panic!("{expected}: unexpected failure {error:#}"),
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(20), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"{expected}: local identity failure must precede network access"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -101,11 +101,6 @@ impl ConnectHandler<'_> {
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if is_network_error(&error) {
|
||||
warn!("Cached gateway authentication request failed: {error}");
|
||||
return Some(Err(error));
|
||||
}
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
@@ -790,8 +785,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn explicit_hip_user_resolves_to_the_selected_account() {
|
||||
// Build sandboxes may use a UID without an entry in the user database.
|
||||
assert_eq!(get_uid(&Some("root".to_string())).unwrap(), Some(0));
|
||||
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
|
||||
let name = current.name().to_string_lossy().into_owned();
|
||||
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -835,11 +831,3 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A failed request says nothing about whether a cached cookie is still valid.
|
||||
pub(super) fn is_network_error(error: &anyhow::Error) -> bool {
|
||||
matches!(
|
||||
error.downcast_ref::<gpapi::error::PortalError>(),
|
||||
Some(gpapi::error::PortalError::NetworkError(_))
|
||||
)
|
||||
}
|
||||
@@ -186,8 +186,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
match identity_error {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
| RequestIdentityError::UnsupportedKeyFormat
|
||||
| RequestIdentityError::UnsupportedKeyAlgorithm(_)
|
||||
| RequestIdentityError::KeyMismatch
|
||||
| RequestIdentityError::InvalidKey
|
||||
| RequestIdentityError::InvalidCertificate
|
||||
| RequestIdentityError::IncompletePkcs12
|
||||
@@ -208,12 +206,8 @@ impl<'a> ConnectHandler<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
||||
let message = if *cert_type == "PKCS#12" {
|
||||
"Enter the certificate file password:"
|
||||
} else {
|
||||
"Enter the private key password:"
|
||||
};
|
||||
let password = Password::new(message)
|
||||
let message = format!("Enter the {} passphrase:", cert_type);
|
||||
let password = Password::new(&message)
|
||||
.without_confirmation()
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
.prompt()?;
|
||||
@@ -292,11 +286,6 @@ impl<'a> ConnectHandler<'a> {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if gateway::is_network_error(&error) {
|
||||
warn!("Cached portal authentication request failed: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
|
||||
@@ -1,68 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 3.4.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added gateway selection and switching directly from the system tray or macOS menu bar.
|
||||
|
||||
### Improved
|
||||
|
||||
- Added a Retry Activation action to recover from temporary license activation failures without re-entering the key.
|
||||
- Made sign-in prompts and connection errors visible when connecting or switching gateways from the tray.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed a Native Shell crash after license activation.
|
||||
- Fixed the macOS Tauri interface opening unexpectedly after signing in from the tray while the main window was hidden.
|
||||
- Fixed the Native Shell update button text becoming unreadable when pressed.
|
||||
- Fixed Linux Nix builds using unavailable WebKitGTK dependencies.
|
||||
|
||||
## 3.3.1
|
||||
|
||||
### Improved
|
||||
|
||||
- Made client certificate errors clearer and added more detail to gateway sign-in logs.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Restored support for client certificates with private extensions and legacy RC4-encrypted PKCS#12 files.
|
||||
- Fixed certificate chain selection for PKCS#12 files containing multiple possible issuers.
|
||||
- Fixed certificate validation and recovery guidance in both desktop interfaces.
|
||||
- Fixed Native Shell Settings windows failing to activate from the macOS menu or reopening on the wrong page.
|
||||
- Fixed keyboard navigation and Escape handling in the macOS Native Shell interface.
|
||||
- Fixed AUR package builds and dependency metadata.
|
||||
|
||||
## 3.3.0
|
||||
|
||||
### Added
|
||||
|
||||
- Added Native Shell, a new desktop interface for macOS and Linux. macOS builds now use it by default.
|
||||
- Added an Interface setting on Linux to switch between Tauri and Native Shell.
|
||||
- Added tray icon appearance options for light and dark desktop panels on Linux, FreeBSD, and OpenBSD.
|
||||
- Added in-app feature highlights, with a setting to turn them off.
|
||||
|
||||
### Improved
|
||||
|
||||
- Made System VPN and Local Proxy modes selectable directly from the main window.
|
||||
- Refined connection details, saved-server selection, keyboard navigation, and dialog appearance.
|
||||
- Removed the need for OpenSSL compatibility configuration and external OpenSSL conversion tools.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed macOS VPN DNS configuration and cleanup, including split-tunnel connections.
|
||||
- Fixed background CLI reconnections failing after the initial connection.
|
||||
- Fixed server addresses losing custom ports when pasted as URLs.
|
||||
- Fixed gateway login address handling for servers with explicit ports.
|
||||
- Fixed browser sign-in registration when desktop-specific settings override the callback handler on Linux, FreeBSD, or OpenBSD.
|
||||
- Fixed Okta FastPass failing to open Okta Verify from the embedded sign-in window on Linux, FreeBSD, and OpenBSD.
|
||||
- Fixed supplied server certificate pins not being enforced during tunnel setup.
|
||||
- Fixed delayed clicks activating a different control after a Native Shell view changed.
|
||||
|
||||
### Command-line notes
|
||||
|
||||
- Deprecated `--fix-openssl` on Linux, FreeBSD, and OpenBSD. Existing commands still accept it, but it has no effect.
|
||||
|
||||
## 3.2.0
|
||||
|
||||
### Added
|
||||
|
||||
+5
-12
@@ -8,6 +8,7 @@ license = "MIT"
|
||||
[dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
common = { path = "../common" }
|
||||
directories = { workspace = true, optional = true }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
dns-lookup = { workspace = true, optional = true }
|
||||
@@ -15,10 +16,8 @@ log.workspace = true
|
||||
reqwest.workspace = true
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-pemfile = "2"
|
||||
rustls-platform-verifier = "0.7"
|
||||
p12-keystore = "0.4.1"
|
||||
pkcs12 = { version = "=0.2.0-pre.0", default-features = false }
|
||||
cms = { version = "=0.3.0-pre.1", default-features = false }
|
||||
sec1 = { version = "0.8.1", default-features = false, features = ["der"] }
|
||||
pem.workspace = true
|
||||
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
||||
x509-cert = { version = "0.3", default-features = false }
|
||||
@@ -44,6 +43,7 @@ chrono.workspace = true
|
||||
humantime.workspace = true
|
||||
netdev = { workspace = true, optional = true }
|
||||
socket2 = { version = "0.6", features = ["all"], optional = true }
|
||||
os_info = { version = "3", default-features = false, optional = true }
|
||||
snow.workspace = true
|
||||
zeroize = { workspace = true, features = ["serde"] }
|
||||
getrandom = "0.4"
|
||||
@@ -64,15 +64,8 @@ oslog = { version = "0.2", default-features = false, optional = true }
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
directories = { workspace = true, optional = true }
|
||||
libloading = { version = "0.9", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
os_info = { version = "3", default-features = false, optional = true }
|
||||
|
||||
[target.'cfg(target_os="windows")'.dependencies]
|
||||
os_info = { version = "3", default-features = false }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
pkg-config = "0.3"
|
||||
@@ -85,8 +78,8 @@ tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[features]
|
||||
default = ["desktop"]
|
||||
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
|
||||
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
|
||||
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:os_info", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
|
||||
tauri = ["desktop", "dep:tauri", "dep:gtk"]
|
||||
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
|
||||
webview-auth = []
|
||||
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
|
||||
@@ -22,23 +22,11 @@ pub enum ServerTlsErrorKind {
|
||||
}
|
||||
|
||||
impl ServerTlsError {
|
||||
pub(crate) fn from_request(
|
||||
server: &url::Url,
|
||||
error: &(dyn Error + 'static),
|
||||
has_client_identity: bool,
|
||||
) -> Option<anyhow::Error> {
|
||||
let kind = classify_with_identity(error, has_client_identity)?;
|
||||
let error = anyhow::Error::new(Self {
|
||||
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> {
|
||||
Some(Self {
|
||||
server: server.origin().ascii_serialization(),
|
||||
kind,
|
||||
});
|
||||
if has_client_identity && kind == ServerTlsErrorKind::ClientCertificateRequired {
|
||||
Some(error.context(
|
||||
"The VPN server could not use the configured client certificate. Check it with your VPN administrator",
|
||||
))
|
||||
} else {
|
||||
Some(error)
|
||||
}
|
||||
kind: classify(error)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,10 +60,6 @@ impl ServerTlsErrorKind {
|
||||
}
|
||||
|
||||
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
||||
classify_with_identity(error, false)
|
||||
}
|
||||
|
||||
fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bool) -> Option<ServerTlsErrorKind> {
|
||||
let mut source = Some(error);
|
||||
while let Some(error) = source {
|
||||
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
|
||||
@@ -87,14 +71,6 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
|
||||
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
|
||||
ServerTlsErrorKind::ClientCertificateRequired
|
||||
}
|
||||
rustls::Error::AlertReceived(
|
||||
rustls::AlertDescription::BadCertificate
|
||||
| rustls::AlertDescription::UnsupportedCertificate
|
||||
| rustls::AlertDescription::CertificateRevoked
|
||||
| rustls::AlertDescription::CertificateExpired
|
||||
| rustls::AlertDescription::CertificateUnknown
|
||||
| rustls::AlertDescription::UnknownCA,
|
||||
) if has_client_identity => ServerTlsErrorKind::ClientCertificateRequired,
|
||||
_ => ServerTlsErrorKind::Other,
|
||||
});
|
||||
}
|
||||
@@ -147,39 +123,6 @@ mod tests {
|
||||
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_identity_peer_errors_have_actionable_copy_without_becoming_server_trust_failures() {
|
||||
let server = url::Url::parse("https://vpn.example.com/private/login").unwrap();
|
||||
for alert in [
|
||||
rustls::AlertDescription::CertificateRequired,
|
||||
rustls::AlertDescription::BadCertificate,
|
||||
rustls::AlertDescription::UnknownCA,
|
||||
] {
|
||||
let error = rustls::Error::AlertReceived(alert);
|
||||
let configured = ServerTlsError::from_request(&server, &error, true).unwrap();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&configured),
|
||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
||||
);
|
||||
let message = configured.to_string();
|
||||
assert!(
|
||||
message.contains("configured client certificate") && message.contains("VPN administrator"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
!message.contains("password") && !message.contains("passphrase"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(!message.contains("/private/login"));
|
||||
}
|
||||
let trust_error = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer);
|
||||
let classified = ServerTlsError::from_request(&server, &trust_error, true).unwrap();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&classified),
|
||||
Some(ServerTlsErrorKind::Certificate)
|
||||
);
|
||||
}
|
||||
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
server_with_client_auth(tls, SslVerifyMode::NONE)
|
||||
}
|
||||
@@ -283,8 +226,8 @@ mod tests {
|
||||
.await
|
||||
.unwrap_err();
|
||||
worker.join().unwrap();
|
||||
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error, false).unwrap();
|
||||
assert_eq!(ServerTlsErrorKind::from_error(&tls), Some(ServerTlsErrorKind::Other));
|
||||
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap();
|
||||
assert_eq!(tls.kind, ServerTlsErrorKind::Other);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -371,38 +314,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
utils::request::ClientIdentity,
|
||||
};
|
||||
let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/client-identity");
|
||||
let identity = ClientIdentity::load(
|
||||
fixtures.join("rsa-critical-extension.pem").to_str().unwrap(),
|
||||
Some(fixtures.join("rsa-pkcs8.pem").to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()))
|
||||
.client_identity(Some(identity))
|
||||
.ignore_tls_errors(true)
|
||||
.build();
|
||||
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let error = prelogin(&address, ¶ms, PreloginOptions::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
worker.join().unwrap();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&error),
|
||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
||||
);
|
||||
assert!(error.to_string().contains("configured client certificate"), "{error:#}");
|
||||
assert!(!error.to_string().contains("passphrase"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
||||
use crate::{
|
||||
@@ -500,10 +411,10 @@ mod tests {
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(
|
||||
&ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error, false).unwrap()
|
||||
),
|
||||
Some(ServerTlsErrorKind::Certificate)
|
||||
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error)
|
||||
.unwrap()
|
||||
.kind,
|
||||
ServerTlsErrorKind::Certificate
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::{
|
||||
gp_params::GpParams,
|
||||
params::gateway_login::{self, GatewayLoginInput},
|
||||
session::GatewayAuthentication,
|
||||
utils::{normalize_server, parse_gp_response, redact::redact_uri, remove_url_scheme, xml::ElementExt},
|
||||
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
pub enum GatewayLogin {
|
||||
@@ -181,14 +181,14 @@ async fn receive_gateway_login(
|
||||
log_gateway_login_context(context, client_ip, gp_params);
|
||||
|
||||
let res = client
|
||||
.post(&login_url)
|
||||
.post(login_url)
|
||||
.form(&request_params.body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match crate::error::ServerTlsError::from_request(origin, &e, gp_params.has_client_identity()) {
|
||||
Some(tls) => tls,
|
||||
match crate::error::ServerTlsError::from_request(origin, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
@@ -200,30 +200,14 @@ async fn receive_gateway_login(
|
||||
.map(<[u8]>::to_vec);
|
||||
let endpoint = res.remote_addr();
|
||||
let url = res.url().clone();
|
||||
let http_version = res.version();
|
||||
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
// Redirect paths and query strings can contain authentication tokens. Log
|
||||
// only the redacted origin and whether the response is from the login path.
|
||||
warn!(
|
||||
"Gateway login response failed: status={}, reason={}, http={:?}, origin={}, port={:?}, redirected={}, login_endpoint={}, content_type={:?}, client_certificate={}, ignore_tls_errors={}",
|
||||
err.status,
|
||||
err.reason,
|
||||
http_version,
|
||||
redact_uri(&url.origin().ascii_serialization()),
|
||||
url.port_or_known_default(),
|
||||
url.as_str() != login_url,
|
||||
url.path() == "/ssl-vpn/login.esp",
|
||||
content_type,
|
||||
gp_params.has_client_identity(),
|
||||
gp_params.ignore_tls_errors(),
|
||||
);
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) {
|
||||
return tls;
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
|
||||
return anyhow::anyhow!(tls);
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return anyhow::anyhow!(crate::error::AuthenticationRejected);
|
||||
}
|
||||
warn!("Gateway login response failed: {}", err.reason);
|
||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||
})?;
|
||||
|
||||
@@ -445,85 +429,6 @@ mod tests {
|
||||
.build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_login_logs_http_context_without_credentials_or_redirect_tokens() {
|
||||
use std::cell::RefCell;
|
||||
|
||||
thread_local! {
|
||||
static MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
struct Logger;
|
||||
impl log::Log for Logger {
|
||||
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
let message = record.args().to_string();
|
||||
if message.starts_with("Gateway login response failed:") {
|
||||
MESSAGES.with_borrow_mut(|messages| messages.push(message));
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
log::set_logger(&Logger).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Warn);
|
||||
|
||||
for (status, reason, redirected) in [
|
||||
(403, None, false),
|
||||
(502, None, true),
|
||||
(401, Some("access denied"), false),
|
||||
] {
|
||||
let body = "<html>response-body-secret</html>";
|
||||
let mut responses = Vec::new();
|
||||
if redirected {
|
||||
responses.push(
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /path-secret?token=query-secret\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
);
|
||||
}
|
||||
let reason_header = reason
|
||||
.map(|reason| format!("x-private-pan-globalprotect: {reason}\r\n"))
|
||||
.unwrap_or_default();
|
||||
responses.push(format!(
|
||||
"HTTP/1.1 {status} Error\r\nContent-Type: text/html\r\nSet-Cookie: cookie-secret\r\n{reason_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
));
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(responses).await;
|
||||
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("username-secret", "password-secret").into();
|
||||
let error = client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
server.await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!("Gateway login error: {}", reason.unwrap_or("<none>"))
|
||||
);
|
||||
let messages = MESSAGES.with_borrow_mut(std::mem::take);
|
||||
assert_eq!(messages.len(), 1);
|
||||
let message = &messages[0];
|
||||
for expected in [
|
||||
format!("status={status}"),
|
||||
format!("reason={}", reason.unwrap_or("<none>")),
|
||||
format!("port={:?}", origin.port()),
|
||||
format!("redirected={redirected}"),
|
||||
format!("login_endpoint={}", !redirected),
|
||||
"http=HTTP/1.1".into(),
|
||||
"content_type=Some(\"text/html\")".into(),
|
||||
"client_certificate=false".into(),
|
||||
"ignore_tls_errors=false".into(),
|
||||
] {
|
||||
assert!(message.contains(&expected), "missing {expected}: {message}");
|
||||
}
|
||||
assert!(!message.contains("secret"), "sensitive data in diagnostic: {message}");
|
||||
assert!(!message.contains("127.0.0.1"), "unredacted origin: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_cancels_stalled_headers_and_body() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
@@ -6,7 +6,7 @@ use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
utils::request::ClientIdentity,
|
||||
utils::request::{ClientIdentity, create_identity},
|
||||
};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||
@@ -160,21 +160,21 @@ impl GpParams {
|
||||
self.prepared_identity.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn has_client_identity(&self) -> bool {
|
||||
self.prepared_identity.is_some() || self.certificate.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let builder = if let Some(identity) = &self.prepared_identity {
|
||||
identity.client_builder(self.ignore_tls_errors)?
|
||||
let mut builder = crate::utils::request::client_builder()
|
||||
.tls_info(true)
|
||||
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
.user_agent(self.user_agent());
|
||||
if let Some(identity) = &self.prepared_identity {
|
||||
builder = builder.identity(identity.request_identity());
|
||||
} else if let Some(cert) = self.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
ClientIdentity::load(cert, self.sslkey.as_deref(), self.key_password.as_deref())?
|
||||
.client_builder(self.ignore_tls_errors)?
|
||||
} else {
|
||||
crate::utils::request::client_builder().danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
};
|
||||
let builder = builder.tls_info(true).user_agent(self.user_agent());
|
||||
builder = builder.identity(create_identity(
|
||||
cert,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,15 +201,15 @@ pub async fn retrieve_config(
|
||||
result = async {
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
||||
Some(tls) => tls,
|
||||
match ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow::anyhow!(tls));
|
||||
}
|
||||
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
|
||||
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
|
||||
@@ -274,15 +274,15 @@ async fn retrieve_csc_config(
|
||||
|
||||
let res = client.post(&url).form(¶ms).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
||||
Some(tls) => tls,
|
||||
match ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow::anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
||||
|
||||
@@ -152,15 +152,15 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
||||
|
||||
let res = request.send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
match crate::error::ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
|
||||
Some(error) => error,
|
||||
match crate::error::ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(error) => anyhow!(error),
|
||||
None => anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
|
||||
return Err(tls);
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
|
||||
|
||||
@@ -72,7 +72,6 @@ impl SwitchListener {
|
||||
self.directory.path().join("control")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub async fn ready(&self) -> anyhow::Result<()> {
|
||||
let (mut socket, _) = self.listener.accept().await?;
|
||||
anyhow::ensure!(
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
//! Client identity capabilities, separate from peer certificate policy.
|
||||
use pkcs8::{
|
||||
ObjectIdentifier, PrivateKeyInfoRef,
|
||||
der::{
|
||||
Decode, Reader, Tag, TagNumber, Tagged,
|
||||
asn1::{AnyRef, BitStringRef, ContextSpecific, OctetStringRef},
|
||||
},
|
||||
};
|
||||
use rustls::pki_types::PrivateKeyDer;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "native_key.rs"]
|
||||
mod implementation;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "portable_key.rs"]
|
||||
mod implementation;
|
||||
|
||||
pub(in crate::utils) use implementation::ClientKey;
|
||||
|
||||
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
|
||||
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
|
||||
const EC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
|
||||
const ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
|
||||
const ED448: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.113");
|
||||
const P521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
|
||||
const DSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10040.4.1");
|
||||
|
||||
fn validate_algorithm(oid: ObjectIdentifier) -> Result<(), RequestIdentityError> {
|
||||
match oid {
|
||||
RSA | EC | ED25519 => Ok(()),
|
||||
RSA_PSS => Err(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS")),
|
||||
ED448 => Err(RequestIdentityError::UnsupportedKeyAlgorithm("Ed448")),
|
||||
DSA => Err(RequestIdentityError::UnsupportedKeyAlgorithm("DSA")),
|
||||
_ => Err(RequestIdentityError::UnsupportedKeyAlgorithm(
|
||||
"an unknown key algorithm",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_ec_parameters(parameters: Option<AnyRef<'_>>) -> Result<(), RequestIdentityError> {
|
||||
if let Some(parameters) = parameters {
|
||||
if parameters.tag() == Tag::ObjectIdentifier {
|
||||
let curve = parameters
|
||||
.decode_as::<ObjectIdentifier>()
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
if curve == P521 {
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm("P-521"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(
|
||||
"EC with explicit parameters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_ec_point(point: &[u8]) -> Result<(), RequestIdentityError> {
|
||||
if matches!(point.first(), Some(2 | 3)) {
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(
|
||||
"EC with compressed public keys",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_sec1(bytes: &[u8]) -> anyhow::Result<()> {
|
||||
let (parameters, point) = AnyRef::from_der(bytes)
|
||||
.and_then(|sequence| {
|
||||
sequence.sequence(|reader| {
|
||||
let version: u8 = reader.decode()?;
|
||||
if version != 1 {
|
||||
return Err(reader.error(Tag::Integer.value_error()));
|
||||
}
|
||||
let _: &OctetStringRef = reader.decode()?;
|
||||
let parameters = ContextSpecific::<AnyRef<'_>>::decode_explicit(reader, TagNumber(0))?.map(|field| field.value);
|
||||
let point =
|
||||
ContextSpecific::<BitStringRef<'_>>::decode_explicit(reader, TagNumber(1))?.map(|field| field.value);
|
||||
Ok((parameters, point))
|
||||
})
|
||||
})
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
validate_ec_parameters(parameters)?;
|
||||
if let Some(point) = point {
|
||||
validate_ec_point(point.as_bytes().ok_or(RequestIdentityError::InvalidKey)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_private_key(key: &PrivateKeyDer<'_>) -> anyhow::Result<()> {
|
||||
match key {
|
||||
PrivateKeyDer::Pkcs8(key) => {
|
||||
let info = PrivateKeyInfoRef::from_der(key.secret_pkcs8_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
validate_algorithm(info.algorithm.oid)?;
|
||||
if info.algorithm.oid == EC {
|
||||
validate_ec_parameters(info.algorithm.parameters)?;
|
||||
validate_sec1(info.private_key.as_bytes())?;
|
||||
}
|
||||
}
|
||||
PrivateKeyDer::Sec1(key) => validate_sec1(key.secret_sec1_der())?,
|
||||
PrivateKeyDer::Pkcs1(_) => {}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn validate_certificate(bytes: &[u8]) -> anyhow::Result<()> {
|
||||
let certificate = x509_cert::Certificate::from_der(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let public_key = certificate.tbs_certificate().subject_public_key_info();
|
||||
validate_algorithm(public_key.algorithm.oid)?;
|
||||
if public_key.algorithm.oid == EC {
|
||||
validate_ec_parameters(public_key.algorithm.parameters.as_ref().map(|value| value.into()))?;
|
||||
validate_ec_point(
|
||||
public_key
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -44,272 +44,3 @@ void gp_key_free(unsigned char *data, size_t length) {
|
||||
gnutls_free(data);
|
||||
}
|
||||
}
|
||||
|
||||
#include <gnutls/abstract.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Check only the signature, not whether this local certificate is trusted,
|
||||
* current, or has extensions understood by the client. */
|
||||
int gp_certificate_verify_signature(
|
||||
const unsigned char *certificate, size_t certificate_length,
|
||||
const unsigned char *issuer_key, size_t issuer_key_length,
|
||||
const unsigned char *message, size_t message_length,
|
||||
const unsigned char *signature, size_t signature_length) {
|
||||
gnutls_x509_crt_t child = NULL;
|
||||
gnutls_pubkey_t public_key = NULL;
|
||||
int result, algorithm;
|
||||
if (certificate_length > UINT_MAX || issuer_key_length > UINT_MAX ||
|
||||
message_length > UINT_MAX || signature_length > UINT_MAX) return -1;
|
||||
result = gnutls_global_init();
|
||||
if (result < 0) return -1;
|
||||
gnutls_datum_t child_data = {(unsigned char *)certificate, (unsigned int)certificate_length};
|
||||
gnutls_datum_t key_data = {(unsigned char *)issuer_key, (unsigned int)issuer_key_length};
|
||||
gnutls_datum_t data = {(unsigned char *)message, (unsigned int)message_length};
|
||||
gnutls_datum_t sig = {(unsigned char *)signature, (unsigned int)signature_length};
|
||||
result = gnutls_x509_crt_init(&child);
|
||||
if (result >= 0) result = gnutls_x509_crt_import(child, &child_data, GNUTLS_X509_FMT_DER);
|
||||
if (result >= 0) result = gnutls_pubkey_init(&public_key);
|
||||
if (result >= 0) result = gnutls_pubkey_import(public_key, &key_data, GNUTLS_X509_FMT_DER);
|
||||
if (result >= 0) {
|
||||
algorithm = gnutls_x509_crt_get_signature_algorithm(child);
|
||||
if (algorithm < 0) result = algorithm;
|
||||
else result = gnutls_pubkey_verify_data2(public_key, algorithm,
|
||||
GNUTLS_VERIFY_ALLOW_BROKEN | GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1, &data, &sig) >= 0;
|
||||
}
|
||||
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
|
||||
if (child != NULL) gnutls_x509_crt_deinit(child);
|
||||
gnutls_global_deinit();
|
||||
return result < 0 ? -1 : result;
|
||||
}
|
||||
|
||||
/* Stable private kinds, independent of the native enum values. */
|
||||
struct gp_client_key {
|
||||
gnutls_privkey_t signer;
|
||||
gnutls_pubkey_t public_key;
|
||||
};
|
||||
|
||||
void gp_client_key_delete(struct gp_client_key *key) {
|
||||
if (key == NULL) return;
|
||||
if (key->public_key != NULL) gnutls_pubkey_deinit(key->public_key);
|
||||
if (key->signer != NULL) gnutls_privkey_deinit(key->signer);
|
||||
free(key);
|
||||
gnutls_global_deinit();
|
||||
}
|
||||
|
||||
int gp_client_key_new(const unsigned char *data, size_t length, int *kind,
|
||||
struct gp_client_key **output) {
|
||||
gnutls_x509_privkey_t input = NULL;
|
||||
struct gp_client_key *key = NULL;
|
||||
int result, algorithm;
|
||||
*output = NULL;
|
||||
*kind = 9;
|
||||
if (length > UINT_MAX || gnutls_global_init() < 0) return 1;
|
||||
key = calloc(1, sizeof(*key));
|
||||
if (key == NULL) { gnutls_global_deinit(); return 1; }
|
||||
result = gnutls_x509_privkey_init(&input);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
|
||||
result = gnutls_x509_privkey_import2(input, &bytes, GNUTLS_X509_FMT_DER, NULL, 0);
|
||||
}
|
||||
if (result < 0) goto invalid;
|
||||
algorithm = gnutls_x509_privkey_get_pk_algorithm(input);
|
||||
if (algorithm == GNUTLS_PK_RSA_PSS) { *kind = 5; goto unsupported; }
|
||||
if (algorithm == GNUTLS_PK_DSA) { *kind = 7; goto unsupported; }
|
||||
if (algorithm == GNUTLS_PK_EDDSA_ED448) { *kind = 8; goto unsupported; }
|
||||
result = gnutls_privkey_init(&key->signer);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_privkey_import_x509(key->signer, input, GNUTLS_PRIVKEY_IMPORT_COPY);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_pubkey_init(&key->public_key);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_pubkey_import_privkey(key->public_key, key->signer, 0, 0);
|
||||
if (result < 0) goto invalid;
|
||||
if (algorithm == GNUTLS_PK_RSA) *kind = 0;
|
||||
else if (algorithm == GNUTLS_PK_EDDSA_ED25519) *kind = 4;
|
||||
else if (algorithm == GNUTLS_PK_ECDSA) {
|
||||
gnutls_ecc_curve_t curve;
|
||||
gnutls_datum_t x = {NULL, 0}, y = {NULL, 0};
|
||||
result = gnutls_pubkey_export_ecc_raw(key->public_key, &curve, &x, &y);
|
||||
gnutls_free(x.data);
|
||||
gnutls_free(y.data);
|
||||
if (result < 0) goto invalid;
|
||||
if (curve == GNUTLS_ECC_CURVE_SECP256R1) *kind = 1;
|
||||
else if (curve == GNUTLS_ECC_CURVE_SECP384R1) *kind = 2;
|
||||
else if (curve == GNUTLS_ECC_CURVE_SECP521R1) { *kind = 3; goto unsupported; }
|
||||
else { *kind = 6; goto unsupported; }
|
||||
} else goto unsupported;
|
||||
gnutls_x509_privkey_deinit(input);
|
||||
*output = key;
|
||||
return 0;
|
||||
unsupported:
|
||||
if (input != NULL) gnutls_x509_privkey_deinit(input);
|
||||
gp_client_key_delete(key);
|
||||
return 2;
|
||||
invalid:
|
||||
if (input != NULL) gnutls_x509_privkey_deinit(input);
|
||||
gp_client_key_delete(key);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int gp_client_key_public(struct gp_client_key *key, unsigned char **output, size_t *length) {
|
||||
gnutls_datum_t bytes = {NULL, 0};
|
||||
int result = gnutls_pubkey_export2(key->public_key, GNUTLS_X509_FMT_DER, &bytes);
|
||||
*output = bytes.data;
|
||||
*length = bytes.size;
|
||||
return result;
|
||||
}
|
||||
|
||||
int gp_client_key_matches(struct gp_client_key *key, const unsigned char *data, size_t length) {
|
||||
gnutls_x509_crt_t certificate = NULL;
|
||||
gnutls_pubkey_t public_key = NULL;
|
||||
unsigned char key_id[32], cert_id[32];
|
||||
size_t key_id_length = sizeof(key_id), cert_id_length = sizeof(cert_id);
|
||||
int result;
|
||||
if (length > UINT_MAX) return -1;
|
||||
result = gnutls_x509_crt_init(&certificate);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
|
||||
result = gnutls_x509_crt_import(certificate, &bytes, GNUTLS_X509_FMT_DER);
|
||||
}
|
||||
if (result >= 0) result = gnutls_pubkey_init(&public_key);
|
||||
if (result >= 0) result = gnutls_pubkey_import_x509(public_key, certificate, 0);
|
||||
if (result >= 0) result = gnutls_pubkey_get_key_id(key->public_key, GNUTLS_KEYID_USE_SHA256, key_id, &key_id_length);
|
||||
if (result >= 0) result = gnutls_pubkey_get_key_id(public_key, GNUTLS_KEYID_USE_SHA256, cert_id, &cert_id_length);
|
||||
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
|
||||
if (certificate != NULL) gnutls_x509_crt_deinit(certificate);
|
||||
if (result < 0) return result;
|
||||
return key_id_length == cert_id_length && !memcmp(key_id, cert_id, key_id_length);
|
||||
}
|
||||
|
||||
int gp_client_key_sign(struct gp_client_key *key, unsigned short scheme,
|
||||
const unsigned char *message, size_t length,
|
||||
unsigned char **output, size_t *output_length) {
|
||||
gnutls_sign_algorithm_t algorithm;
|
||||
unsigned int flags = 0;
|
||||
*output = NULL;
|
||||
*output_length = 0;
|
||||
if (length > UINT_MAX) return -1;
|
||||
switch (scheme) {
|
||||
case 0x0804: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA256; break;
|
||||
case 0x0805: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA384; break;
|
||||
case 0x0806: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA512; break;
|
||||
case 0x0401: algorithm = GNUTLS_SIGN_RSA_SHA256; break;
|
||||
case 0x0501: algorithm = GNUTLS_SIGN_RSA_SHA384; break;
|
||||
case 0x0601: algorithm = GNUTLS_SIGN_RSA_SHA512; break;
|
||||
case 0x0403: algorithm = GNUTLS_SIGN_ECDSA_SECP256R1_SHA256; break;
|
||||
case 0x0503: algorithm = GNUTLS_SIGN_ECDSA_SECP384R1_SHA384; break;
|
||||
case 0x0807: algorithm = GNUTLS_SIGN_EDDSA_ED25519; break;
|
||||
default: return -1;
|
||||
}
|
||||
if (scheme >= 0x0804 && scheme <= 0x0806)
|
||||
flags = GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH;
|
||||
gnutls_datum_t bytes = {(unsigned char *)message, (unsigned int)length};
|
||||
gnutls_datum_t signature = {NULL, 0};
|
||||
int result = gnutls_privkey_sign_data2(key->signer, algorithm, flags, &bytes, &signature);
|
||||
*output = signature.data;
|
||||
*output_length = signature.size;
|
||||
return result;
|
||||
}
|
||||
|
||||
#include <gnutls/pkcs12.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Invoked only after Rust has identified the supported RC4 archive scheme.
|
||||
* Integrity and identity-count checks precede the native leaf selection. */
|
||||
int gp_pkcs12_identity(const unsigned char *input, size_t length, const char *password,
|
||||
unsigned char **certificate, size_t *certificate_length,
|
||||
unsigned char **private_key, size_t *private_key_length) {
|
||||
gnutls_pkcs12_t archive = NULL;
|
||||
gnutls_x509_privkey_t key = NULL;
|
||||
gnutls_x509_crt_t *chain = NULL, *extra = NULL;
|
||||
unsigned int chain_length = 0, extra_length = 0;
|
||||
gnutls_datum_t exported_key = {NULL, 0};
|
||||
unsigned int key_count = 0, cert_count = 0;
|
||||
int result, status = 5;
|
||||
*certificate = NULL;
|
||||
*certificate_length = 0;
|
||||
*private_key = NULL;
|
||||
*private_key_length = 0;
|
||||
if (length > UINT_MAX || gnutls_global_init() < 0) return 5;
|
||||
result = gnutls_pkcs12_init(&archive);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)input, (unsigned int)length};
|
||||
result = gnutls_pkcs12_import(archive, &bytes, GNUTLS_X509_FMT_DER, 0);
|
||||
}
|
||||
if (result < 0) goto out;
|
||||
result = gnutls_pkcs12_verify_mac(archive, password);
|
||||
if (result == GNUTLS_E_MAC_VERIFY_FAILED) { status = 1; goto out; }
|
||||
if (result < 0 && result != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) goto out;
|
||||
for (int index = 0; ; index++) {
|
||||
gnutls_pkcs12_bag_t bag;
|
||||
result = gnutls_pkcs12_bag_init(&bag);
|
||||
if (result < 0) goto out;
|
||||
result = gnutls_pkcs12_get_bag(archive, index, bag);
|
||||
if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
|
||||
gnutls_pkcs12_bag_deinit(bag);
|
||||
break;
|
||||
}
|
||||
if (result >= 0 && gnutls_pkcs12_bag_get_type(bag, 0) == GNUTLS_BAG_ENCRYPTED)
|
||||
result = gnutls_pkcs12_bag_decrypt(bag, password);
|
||||
if (result < 0) {
|
||||
gnutls_pkcs12_bag_deinit(bag);
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1;
|
||||
else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4;
|
||||
goto out;
|
||||
}
|
||||
int count = gnutls_pkcs12_bag_get_count(bag);
|
||||
if (count < 0) { gnutls_pkcs12_bag_deinit(bag); goto out; }
|
||||
for (int item = 0; item < count; item++) {
|
||||
int type = gnutls_pkcs12_bag_get_type(bag, item);
|
||||
if (type == GNUTLS_BAG_PKCS8_KEY || type == GNUTLS_BAG_PKCS8_ENCRYPTED_KEY) key_count++;
|
||||
if (type == GNUTLS_BAG_CERTIFICATE) cert_count++;
|
||||
}
|
||||
gnutls_pkcs12_bag_deinit(bag);
|
||||
}
|
||||
if (key_count == 0 || cert_count == 0) { status = 2; goto out; }
|
||||
if (key_count != 1) { status = 3; goto out; }
|
||||
result = gnutls_pkcs12_simple_parse(archive, password, &key, &chain, &chain_length,
|
||||
&extra, &extra_length, NULL, GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED);
|
||||
if (result < 0) {
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1;
|
||||
else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4;
|
||||
else if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) status = 6;
|
||||
goto out;
|
||||
}
|
||||
if (key == NULL || chain_length == 0) { status = 2; goto out; }
|
||||
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER, NULL, GNUTLS_PKCS_PLAIN, &exported_key);
|
||||
if (result < 0) goto out;
|
||||
for (unsigned int index = 0; index < chain_length; index++) {
|
||||
gnutls_datum_t part = {NULL, 0};
|
||||
result = gnutls_x509_crt_export2(chain[index], GNUTLS_X509_FMT_PEM, &part);
|
||||
if (result < 0) goto out;
|
||||
if (part.size > SIZE_MAX - *certificate_length) { gnutls_free(part.data); goto out; }
|
||||
unsigned char *buffer = gnutls_realloc(*certificate, *certificate_length + part.size);
|
||||
if (buffer == NULL) { gnutls_free(part.data); goto out; }
|
||||
memcpy(buffer + *certificate_length, part.data, part.size);
|
||||
*certificate = buffer;
|
||||
*certificate_length += part.size;
|
||||
gnutls_free(part.data);
|
||||
}
|
||||
*private_key = exported_key.data;
|
||||
*private_key_length = exported_key.size;
|
||||
exported_key.data = NULL;
|
||||
exported_key.size = 0;
|
||||
status = 0;
|
||||
out:
|
||||
if (status != 0) {
|
||||
gp_key_free(*certificate, *certificate_length);
|
||||
*certificate = NULL;
|
||||
*certificate_length = 0;
|
||||
}
|
||||
gp_key_free(exported_key.data, exported_key.size);
|
||||
if (key != NULL) gnutls_x509_privkey_deinit(key);
|
||||
for (unsigned int index = 0; index < chain_length; index++) gnutls_x509_crt_deinit(chain[index]);
|
||||
for (unsigned int index = 0; index < extra_length; index++) gnutls_x509_crt_deinit(extra[index]);
|
||||
gnutls_free(chain);
|
||||
gnutls_free(extra);
|
||||
if (archive != NULL) gnutls_pkcs12_deinit(archive);
|
||||
gnutls_global_deinit();
|
||||
return status;
|
||||
}
|
||||
@@ -1,22 +1,11 @@
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use pkcs8::SecretDocument;
|
||||
use pkcs8::der::{Encode, asn1::ObjectIdentifier};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_certificate_verify_signature(
|
||||
certificate: *const u8,
|
||||
certificate_length: usize,
|
||||
issuer_key: *const u8,
|
||||
issuer_key_length: usize,
|
||||
message: *const u8,
|
||||
message_length: usize,
|
||||
signature: *const u8,
|
||||
signature_length: usize,
|
||||
) -> c_int;
|
||||
fn gp_key_import(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
@@ -25,58 +14,9 @@ unsafe extern "C" {
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_pkcs12_identity(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
password: *const c_char,
|
||||
certificate: *mut *mut u8,
|
||||
certificate_length: *mut usize,
|
||||
key: *mut *mut u8,
|
||||
key_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
pub(super) fn verify_certificate_signature(
|
||||
certificate: &x509_cert::Certificate,
|
||||
issuer: &x509_cert::Certificate,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
|
||||
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
|
||||
let mut issuer_key = issuer.tbs_certificate().subject_public_key_info().clone();
|
||||
if certificate.signature_algorithm().oid == RSA_PSS {
|
||||
if !matches!(issuer_key.algorithm.oid, RSA | RSA_PSS) {
|
||||
return Ok(false);
|
||||
}
|
||||
// GnuTLS's generic verifier takes PSS parameters from the imported key.
|
||||
// Give this verification operation the certificate's full AlgorithmIdentifier,
|
||||
// including salt length, rather than the default implied by its signature enum.
|
||||
// This temporary SPKI never changes the certificates sent to the server.
|
||||
issuer_key.algorithm = certificate.signature_algorithm().clone();
|
||||
}
|
||||
let issuer_key = issuer_key.to_der()?;
|
||||
let certificate = certificate.to_der()?;
|
||||
let result = unsafe {
|
||||
gp_certificate_verify_signature(
|
||||
certificate.as_ptr(),
|
||||
certificate.len(),
|
||||
issuer_key.as_ptr(),
|
||||
issuer_key.len(),
|
||||
message.as_ptr(),
|
||||
message.len(),
|
||||
signature.as_ptr(),
|
||||
signature.len(),
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => Ok(false),
|
||||
1 => Ok(true),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
|
||||
struct ExportedKey {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
@@ -124,55 +64,3 @@ pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str
|
||||
_ => Err(RequestIdentityError::InvalidKey.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn archive(
|
||||
bytes: &[u8],
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<(Zeroizing<Vec<u8>>, SecretDocument)> {
|
||||
let mut password = Zeroizing::new(passphrase.unwrap_or_default().as_bytes().to_vec());
|
||||
anyhow::ensure!(
|
||||
!password.contains(&0),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
password.push(0);
|
||||
let mut certificate = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
let mut key = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
let result = unsafe {
|
||||
gp_pkcs12_identity(
|
||||
bytes.as_ptr(),
|
||||
bytes.len(),
|
||||
password.as_ptr().cast(),
|
||||
&mut certificate.data,
|
||||
&mut certificate.length,
|
||||
&mut key.data,
|
||||
&mut key.length,
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => {
|
||||
anyhow::ensure!(
|
||||
!certificate.data.is_null() && certificate.length > 0,
|
||||
"Invalid certificate file"
|
||||
);
|
||||
anyhow::ensure!(!key.data.is_null() && key.length > 0, "Invalid private key");
|
||||
let certificate =
|
||||
Zeroizing::new(unsafe { std::slice::from_raw_parts(certificate.data, certificate.length) }.to_vec());
|
||||
let key = SecretDocument::try_from(unsafe { std::slice::from_raw_parts(key.data, key.length) })
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
Ok((certificate, key))
|
||||
}
|
||||
1 if passphrase.is_none() => Err(RequestIdentityError::NoPassphrase("PKCS#12").into()),
|
||||
1 => Err(RequestIdentityError::InvalidPkcs12(p12_keystore::error::Error::InvalidData).into()),
|
||||
2 => Err(RequestIdentityError::IncompletePkcs12.into()),
|
||||
3 => Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
4 => Err(RequestIdentityError::UnsupportedEncryption.into()),
|
||||
6 => Err(RequestIdentityError::KeyMismatch.into()),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
use pkcs8::der::{Decode, Encode};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
/// Identify the signing issuer, without applying trust, expiry or extension policy
|
||||
/// to a local identity. The VPN server remains responsible for those checks.
|
||||
pub(super) fn is_issuer(certificate: &[u8], issuer: &[u8]) -> anyhow::Result<bool> {
|
||||
let child = x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let parent = x509_cert::Certificate::from_der(issuer).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
if child.tbs_certificate().issuer() != parent.tbs_certificate().subject() {
|
||||
return Ok(false);
|
||||
}
|
||||
let signature = child
|
||||
.signature()
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
super::platform_import::verify_certificate_signature(&child, &parent, &child.tbs_certificate().to_der()?, signature)
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
mod client_key;
|
||||
mod issuer;
|
||||
pub(super) use client_key::{ClientKey, validate_certificate};
|
||||
|
||||
pub(super) mod pkcs12;
|
||||
mod pkcs12_format;
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
@@ -12,14 +7,14 @@ mod pkcs12_format;
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "gnutls.rs"]
|
||||
mod platform_import;
|
||||
mod legacy_key;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "portable_import.rs"]
|
||||
mod platform_import;
|
||||
#[path = "unsupported.rs"]
|
||||
mod legacy_key;
|
||||
|
||||
pub(super) use platform_import::{archive, decrypt as decrypt_key};
|
||||
pub(super) use legacy_key::decrypt as decrypt_key;
|
||||
@@ -1,307 +0,0 @@
|
||||
use std::{
|
||||
ffi::{c_int, c_void},
|
||||
fmt,
|
||||
ptr::NonNull,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use rustls::{
|
||||
SignatureAlgorithm, SignatureScheme,
|
||||
pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer},
|
||||
sign::{Signer, SigningKey},
|
||||
};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_client_key_new(data: *const u8, length: usize, kind: *mut c_int, output: *mut *mut c_void) -> c_int;
|
||||
fn gp_client_key_delete(key: *mut c_void);
|
||||
fn gp_client_key_public(key: *mut c_void, output: *mut *mut u8, length: *mut usize) -> c_int;
|
||||
fn gp_client_key_matches(key: *mut c_void, cert: *const u8, length: usize) -> c_int;
|
||||
fn gp_client_key_sign(
|
||||
key: *mut c_void,
|
||||
scheme: u16,
|
||||
message: *const u8,
|
||||
length: usize,
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
struct NativeKey(NonNull<c_void>);
|
||||
|
||||
// The handle is not thread-affine. All access and final release occur under its
|
||||
// Rust owner; shared operations use the mutex in ClientKey.
|
||||
unsafe impl Send for NativeKey {}
|
||||
|
||||
impl Drop for NativeKey {
|
||||
fn drop(&mut self) {
|
||||
unsafe { gp_client_key_delete(self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
struct NativeBytes {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
}
|
||||
impl Drop for NativeBytes {
|
||||
fn drop(&mut self) {
|
||||
unsafe { gp_key_free(self.data, self.length) };
|
||||
}
|
||||
}
|
||||
impl NativeBytes {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
fn copy(&self) -> anyhow::Result<Vec<u8>> {
|
||||
anyhow::ensure!(
|
||||
!self.data.is_null() && self.length > 0,
|
||||
"Client certificate operation failed"
|
||||
);
|
||||
Ok(unsafe { std::slice::from_raw_parts(self.data, self.length) }.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::utils) struct ClientKey {
|
||||
key: Arc<Mutex<NativeKey>>,
|
||||
kind: c_int,
|
||||
public_key: Vec<u8>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ClientKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ClientKey")
|
||||
.field("algorithm", &self.algorithm())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientKey {
|
||||
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
|
||||
super::validate_private_key(key)?;
|
||||
let bytes = key.secret_der();
|
||||
let mut kind = 0;
|
||||
let mut pointer = std::ptr::null_mut();
|
||||
let result = unsafe { gp_client_key_new(bytes.as_ptr(), bytes.len(), &mut kind, &mut pointer) };
|
||||
if result == 2 {
|
||||
let algorithm = match kind {
|
||||
3 => "P-521",
|
||||
5 => "RSA-PSS",
|
||||
6 => "an unsupported elliptic curve",
|
||||
7 => "DSA",
|
||||
8 => "Ed448",
|
||||
_ => "an unknown key algorithm",
|
||||
};
|
||||
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(algorithm).into());
|
||||
}
|
||||
if result != 0 {
|
||||
return Err(RequestIdentityError::InvalidKey.into());
|
||||
}
|
||||
let key = NativeKey(NonNull::new(pointer).ok_or(RequestIdentityError::InvalidKey)?);
|
||||
let mut exported = NativeBytes::new();
|
||||
let result = unsafe { gp_client_key_public(key.0.as_ptr(), &mut exported.data, &mut exported.length) };
|
||||
anyhow::ensure!(result == 0, "Could not read the client certificate's public key");
|
||||
Ok(Self {
|
||||
key: Arc::new(Mutex::new(key)),
|
||||
kind,
|
||||
public_key: exported.copy()?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result<bool> {
|
||||
let key = self
|
||||
.key
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("The client certificate is unavailable"))?;
|
||||
match unsafe { gp_client_key_matches(key.0.as_ptr(), certificate.as_ptr(), certificate.len()) } {
|
||||
1 => Ok(true),
|
||||
0 => Ok(false),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn schemes(&self) -> &'static [SignatureScheme] {
|
||||
use SignatureScheme::*;
|
||||
match self.kind {
|
||||
0 => &[
|
||||
RSA_PSS_SHA512,
|
||||
RSA_PSS_SHA384,
|
||||
RSA_PSS_SHA256,
|
||||
RSA_PKCS1_SHA512,
|
||||
RSA_PKCS1_SHA384,
|
||||
RSA_PKCS1_SHA256,
|
||||
],
|
||||
// Rustls does not expose the negotiated TLS version here. Keep TLS 1.3
|
||||
// curve/hash requirements; TLS 1.2 cross-curve hash offers remain unsupported.
|
||||
1 => &[ECDSA_NISTP256_SHA256],
|
||||
2 => &[ECDSA_NISTP384_SHA384],
|
||||
4 => &[ED25519],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SigningKey for ClientKey {
|
||||
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
|
||||
self
|
||||
.schemes()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|scheme| offered.contains(scheme))
|
||||
.map(|scheme| {
|
||||
Box::new(ClientSigner {
|
||||
key: self.clone(),
|
||||
scheme,
|
||||
}) as Box<dyn Signer>
|
||||
})
|
||||
}
|
||||
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
|
||||
Some(SubjectPublicKeyInfoDer::from(self.public_key.as_slice()))
|
||||
}
|
||||
fn algorithm(&self) -> SignatureAlgorithm {
|
||||
match self.kind {
|
||||
0 => SignatureAlgorithm::RSA,
|
||||
4 => SignatureAlgorithm::ED25519,
|
||||
_ => SignatureAlgorithm::ECDSA,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ClientSigner {
|
||||
key: ClientKey,
|
||||
scheme: SignatureScheme,
|
||||
}
|
||||
impl Signer for ClientSigner {
|
||||
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, rustls::Error> {
|
||||
let error = || rustls::Error::General("Could not sign with the client certificate".into());
|
||||
let key = self.key.key.lock().map_err(|_| error())?;
|
||||
let mut output = NativeBytes::new();
|
||||
let result = unsafe {
|
||||
gp_client_key_sign(
|
||||
key.0.as_ptr(),
|
||||
self.scheme.into(),
|
||||
message.as_ptr(),
|
||||
message.len(),
|
||||
&mut output.data,
|
||||
&mut output.length,
|
||||
)
|
||||
};
|
||||
if result != 0 {
|
||||
return Err(error());
|
||||
}
|
||||
output.copy().map_err(|_| error())
|
||||
}
|
||||
fn scheme(&self) -> SignatureScheme {
|
||||
self.scheme
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openssl::{
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Padding,
|
||||
sign::{RsaPssSaltlen, Verifier},
|
||||
};
|
||||
|
||||
fn fixture(name: &str) -> Vec<u8> {
|
||||
std::fs::read(
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn native_key(bytes: &[u8]) -> ClientKey {
|
||||
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
ClientKey::load(&key).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() {
|
||||
let bytes = fixture("rsa-pkcs8.pem");
|
||||
let key = native_key(&bytes);
|
||||
let oracle = PKey::private_key_from_pem(&bytes).unwrap();
|
||||
let message = b"client authentication regression";
|
||||
for (scheme, digest, pss) in [
|
||||
(SignatureScheme::RSA_PSS_SHA256, MessageDigest::sha256(), true),
|
||||
(SignatureScheme::RSA_PSS_SHA384, MessageDigest::sha384(), true),
|
||||
(SignatureScheme::RSA_PSS_SHA512, MessageDigest::sha512(), true),
|
||||
(SignatureScheme::RSA_PKCS1_SHA256, MessageDigest::sha256(), false),
|
||||
(SignatureScheme::RSA_PKCS1_SHA384, MessageDigest::sha384(), false),
|
||||
(SignatureScheme::RSA_PKCS1_SHA512, MessageDigest::sha512(), false),
|
||||
] {
|
||||
let signer = key.choose_scheme(&[scheme]).unwrap();
|
||||
assert_eq!(signer.scheme(), scheme);
|
||||
let signature = signer.sign(message).unwrap();
|
||||
let mut verifier = Verifier::new(digest, &oracle).unwrap();
|
||||
if pss {
|
||||
verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
|
||||
verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap();
|
||||
verifier.set_rsa_mgf1_md(digest).unwrap();
|
||||
}
|
||||
assert!(verifier.verify_oneshot(&signature, message).unwrap(), "{scheme:?}");
|
||||
}
|
||||
assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p256_signatures_verify_with_an_independent_backend() {
|
||||
let bytes = fixture("ec-pkcs8.pem");
|
||||
let key = native_key(&bytes);
|
||||
let oracle = PKey::private_key_from_pem(&bytes).unwrap();
|
||||
let signer = key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).unwrap();
|
||||
let message = b"native client key signature";
|
||||
let signature = signer.sign(message).unwrap();
|
||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap();
|
||||
assert!(verifier.verify_oneshot(&signature, message).unwrap());
|
||||
assert!(key.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_key_types_fail_at_import() {
|
||||
for (name, algorithm) in [("ec-p521.pem", "P-521"), ("rsa-pss.pem", "RSA-PSS")] {
|
||||
let bytes = fixture(name);
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let error = ClientKey::load(&private_key).unwrap_err();
|
||||
assert!(matches!(error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedKeyAlgorithm(actual)) if *actual == algorithm));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_remains_usable_when_shared_clients_sign_concurrently() {
|
||||
let key = native_key(&fixture("rsa-pkcs8.pem"));
|
||||
let mut workers = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let key = key.clone();
|
||||
workers.push(std::thread::spawn(move || {
|
||||
key
|
||||
.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
|
||||
.unwrap()
|
||||
.sign(b"shared identity")
|
||||
.unwrap()
|
||||
}));
|
||||
}
|
||||
let oracle = PKey::private_key_from_pem(&fixture("rsa-pkcs8.pem")).unwrap();
|
||||
for worker in workers {
|
||||
let signature = worker.join().unwrap();
|
||||
let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap();
|
||||
verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
|
||||
verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap();
|
||||
assert!(verifier.verify_oneshot(&signature, b"shared identity").unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,22 @@
|
||||
use p12_keystore::Pkcs12Archive;
|
||||
use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
|
||||
use super::{
|
||||
ClientKey,
|
||||
pkcs12_format::{self, ArchiveBackend},
|
||||
use rustls::{
|
||||
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
sign::CertifiedKey,
|
||||
};
|
||||
use crate::utils::{client_tls, request::RequestIdentityError};
|
||||
|
||||
pub(in crate::utils) fn certified_key(
|
||||
bytes: &[u8],
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<std::sync::Arc<rustls::sign::CertifiedKey>> {
|
||||
use crate::utils::request::{RequestIdentityError, pem_request_identity};
|
||||
|
||||
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> {
|
||||
anyhow::ensure!(
|
||||
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
if pkcs12_format::backend(bytes)? == ArchiveBackend::NativeRc4 {
|
||||
let (certificate, key) = super::archive(bytes, passphrase)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
return client_tls::pem_certified_key(&certificate, key.as_bytes());
|
||||
}
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| match error {
|
||||
p12_keystore::error::Error::UnsupportedEncryptionScheme | p12_keystore::error::Error::UnsupportedMacAlgorithm => {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
}
|
||||
p12_keystore::error::Error::MacError(_)
|
||||
| p12_keystore::error::Error::UnpadError
|
||||
| p12_keystore::error::Error::Pkcs5Error(_)
|
||||
if passphrase.is_none() =>
|
||||
{
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
error => RequestIdentityError::InvalidPkcs12(error),
|
||||
})?;
|
||||
if archive.keys.is_empty() || archive.certs.is_empty() {
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
@@ -40,8 +25,7 @@ pub(in crate::utils) fn certified_key(
|
||||
return Err(RequestIdentityError::AmbiguousPkcs12.into());
|
||||
}
|
||||
let key = &archive.keys[0].key;
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
let signing_key = ClientKey::load(&private_key)?;
|
||||
let provider = rustls::crypto::ring::default_provider();
|
||||
let mut certs = Vec::new();
|
||||
for bag in &archive.certs {
|
||||
if !certs
|
||||
@@ -51,36 +35,38 @@ pub(in crate::utils) fn certified_key(
|
||||
certs.push(&bag.cert);
|
||||
}
|
||||
}
|
||||
let mut matches = Vec::new();
|
||||
for (index, cert) in certs.iter().enumerate() {
|
||||
if signing_key.matches_certificate(cert.as_der())? {
|
||||
matches.push(index);
|
||||
}
|
||||
}
|
||||
let leaf = match matches.first() {
|
||||
Some(leaf) => *leaf,
|
||||
None => return Err(RequestIdentityError::KeyMismatch.into()),
|
||||
let matches: Vec<_> = certs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, cert)| {
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
CertifiedKey::from_der(
|
||||
vec![CertificateDer::from(cert.as_der().to_vec())],
|
||||
private_key,
|
||||
&provider,
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(index)
|
||||
})
|
||||
.collect();
|
||||
let leaf = match matches.as_slice() {
|
||||
[leaf] => *leaf,
|
||||
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
};
|
||||
let mut current = certs.remove(leaf);
|
||||
let mut chain = Vec::new();
|
||||
loop {
|
||||
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
|
||||
if super::issuer::is_issuer(current.as_der(), current.as_der())? {
|
||||
if current.subject() == current.issuer() {
|
||||
break;
|
||||
}
|
||||
let mut parent = None;
|
||||
for (index, candidate) in certs.iter().enumerate() {
|
||||
if super::issuer::is_issuer(current.as_der(), candidate.as_der())? {
|
||||
parent = Some(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(parent) = parent else {
|
||||
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
|
||||
break;
|
||||
};
|
||||
current = certs.remove(parent);
|
||||
}
|
||||
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
client_tls::pem_certified_key(&chain, key.as_bytes())
|
||||
pem_request_identity(&chain, key.as_bytes())
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
//! Select an archive importer from decoded encryption metadata, before passwords.
|
||||
use cms::encrypted_data::EncryptedData;
|
||||
use pkcs8::{
|
||||
ObjectIdentifier,
|
||||
der::{
|
||||
Decode, Encode,
|
||||
asn1::{ContextSpecific, OctetString},
|
||||
},
|
||||
};
|
||||
use pkcs12::{
|
||||
AuthenticatedSafe,
|
||||
pbe_params::{EncryptedPrivateKeyInfo, Pkcs12PbeParams},
|
||||
pfx::Pfx,
|
||||
safe_bag::SafeContents,
|
||||
};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
|
||||
const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6");
|
||||
const ENCRYPTED_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2");
|
||||
const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13");
|
||||
const RC4_128: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.1");
|
||||
const DES3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3");
|
||||
const RC2_40: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.6");
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ArchiveBackend {
|
||||
Rust,
|
||||
NativeRc4,
|
||||
}
|
||||
|
||||
fn invalid(_: pkcs8::der::Error) -> RequestIdentityError {
|
||||
RequestIdentityError::InvalidCertificate
|
||||
}
|
||||
|
||||
/// Inspect only visible metadata. Encrypted safe contents remain opaque until
|
||||
/// the selected importer verifies the MAC and decrypts them.
|
||||
pub(super) fn backend(bytes: &[u8]) -> Result<ArchiveBackend, RequestIdentityError> {
|
||||
let pfx = Pfx::from_der(bytes).map_err(invalid)?;
|
||||
if pfx.auth_safe.content_type != DATA {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
let contents = pfx.auth_safe.content.decode_as::<OctetString>().map_err(invalid)?;
|
||||
let safes = AuthenticatedSafe::from_der(contents.as_bytes()).map_err(invalid)?;
|
||||
let mut selected = ArchiveBackend::Rust;
|
||||
for safe in safes {
|
||||
if safe.content_type == ENCRYPTED_DATA {
|
||||
let encrypted = safe.content.decode_as::<EncryptedData>().map_err(invalid)?;
|
||||
let algorithm = encrypted.enc_content_info.content_enc_alg;
|
||||
inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?;
|
||||
} else if safe.content_type == DATA {
|
||||
let contents = safe.content.decode_as::<OctetString>().map_err(invalid)?;
|
||||
let bags = SafeContents::from_der(contents.as_bytes()).map_err(invalid)?;
|
||||
for bag in bags {
|
||||
if bag.bag_id == ENCRYPTED_KEY {
|
||||
let encrypted = ContextSpecific::<EncryptedPrivateKeyInfo>::from_der(&bag.bag_value).map_err(invalid)?;
|
||||
let algorithm = encrypted.value.encryption_algorithm;
|
||||
inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
}
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
fn inspect_algorithm(
|
||||
oid: ObjectIdentifier,
|
||||
parameters: Option<&pkcs8::der::Any>,
|
||||
selected: &mut ArchiveBackend,
|
||||
) -> Result<(), RequestIdentityError> {
|
||||
let parameters = parameters
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?
|
||||
.to_der()
|
||||
.map_err(invalid)?;
|
||||
if oid == PBES2 {
|
||||
pkcs8::pkcs5::pbes2::Parameters::from_der(¶meters).map_err(|error| match error.kind() {
|
||||
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
|
||||
_ => RequestIdentityError::InvalidCertificate,
|
||||
})?;
|
||||
} else if matches!(oid, RC4_128 | DES3 | RC2_40) {
|
||||
Pkcs12PbeParams::from_der(¶meters).map_err(invalid)?;
|
||||
if oid == RC4_128 {
|
||||
*selected = ArchiveBackend::NativeRc4;
|
||||
}
|
||||
} else {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn published_archive_formats_choose_their_importer_from_metadata() {
|
||||
for name in [
|
||||
"modern.p12",
|
||||
"legacy-rc2.p12",
|
||||
"empty-password.p12",
|
||||
"unicode-password.p12",
|
||||
"no-bag-ids.p12",
|
||||
] {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name);
|
||||
assert_eq!(
|
||||
backend(&std::fs::read(path).unwrap()).unwrap(),
|
||||
ArchiveBackend::Rust,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
backend(include_bytes!(
|
||||
"../../../tests/files/client-identity/legacy-RC4-128.p12"
|
||||
))
|
||||
.unwrap(),
|
||||
ArchiveBackend::NativeRc4
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_archive_encryption_is_terminal_before_password_handling() {
|
||||
for bytes in [
|
||||
include_bytes!("../../../tests/files/client-identity/legacy-RC2-128.p12").as_slice(),
|
||||
include_bytes!("../../../tests/files/client-identity/legacy-2DES.p12").as_slice(),
|
||||
] {
|
||||
assert!(matches!(
|
||||
backend(bytes),
|
||||
Err(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Portable certificate verification; native legacy import is unavailable here.
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use pkcs8::der::{Decode, Encode, asn1::AnyRef};
|
||||
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn archive(
|
||||
_bytes: &[u8],
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<(zeroize::Zeroizing<Vec<u8>>, pkcs8::SecretDocument)> {
|
||||
Err(RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
|
||||
pub(super) fn verify_certificate_signature(
|
||||
child: &x509_cert::Certificate,
|
||||
parent: &x509_cert::Certificate,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
let public_key = parent.tbs_certificate().subject_public_key_info();
|
||||
let key_algorithm = public_key.algorithm.to_der()?;
|
||||
let signature_algorithm = child.signature_algorithm().to_der()?;
|
||||
let key_algorithm = AnyRef::from_der(&key_algorithm)?.value();
|
||||
let signature_algorithm = AnyRef::from_der(&signature_algorithm)?.value();
|
||||
let key = public_key
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
Ok(
|
||||
rustls::crypto::ring::default_provider()
|
||||
.signature_verification_algorithms
|
||||
.all
|
||||
.iter()
|
||||
.any(|algorithm| {
|
||||
algorithm.public_key_alg_id().as_ref() == key_algorithm
|
||||
&& algorithm.signature_alg_id().as_ref() == signature_algorithm
|
||||
&& algorithm.verify_signature(key, message, signature).is_ok()
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use pkcs8::der::{Decode, Encode};
|
||||
use rustls::{
|
||||
SignatureAlgorithm, SignatureScheme,
|
||||
pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer},
|
||||
sign::{Signer, SigningKey},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(in crate::utils) struct ClientKey {
|
||||
key: Arc<dyn SigningKey>,
|
||||
}
|
||||
|
||||
impl ClientKey {
|
||||
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
|
||||
super::validate_private_key(key)?;
|
||||
let key = rustls::crypto::ring::default_provider()
|
||||
.key_provider
|
||||
.load_private_key(key.clone_key())
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
Ok(Self { key })
|
||||
}
|
||||
pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result<bool> {
|
||||
let certificate =
|
||||
x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let key = self.key.public_key().ok_or(RequestIdentityError::InvalidKey)?;
|
||||
Ok(certificate.tbs_certificate().subject_public_key_info().to_der()? == key.as_ref())
|
||||
}
|
||||
}
|
||||
impl SigningKey for ClientKey {
|
||||
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
|
||||
self.key.choose_scheme(offered)
|
||||
}
|
||||
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
|
||||
self.key.public_key()
|
||||
}
|
||||
fn algorithm(&self) -> SignatureAlgorithm {
|
||||
self.key.algorithm()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
//! Local identity matching is separate from the peer's certificate validation.
|
||||
use std::{io::Cursor, sync::Arc};
|
||||
|
||||
use pkcs8::der::Decode;
|
||||
use rustls::{
|
||||
ClientConfig, DigitallySignedStruct, SignatureScheme,
|
||||
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
|
||||
pki_types::{CertificateDer, ServerName, UnixTime},
|
||||
sign::{CertifiedKey, SingleCertAndKey},
|
||||
};
|
||||
use rustls_platform_verifier::BuilderVerifierExt;
|
||||
|
||||
use super::{
|
||||
certificate::{ClientKey, validate_certificate},
|
||||
request::RequestIdentityError,
|
||||
};
|
||||
|
||||
pub(super) fn pem_certified_key(certificate: &[u8], key: &[u8]) -> anyhow::Result<Arc<CertifiedKey>> {
|
||||
let certificates = rustls_pemfile::certs(&mut Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut Cursor::new(key))
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
let signing_key = Arc::new(ClientKey::load(&private_key)?);
|
||||
let leaf = certificates.first().ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
validate_certificate(leaf)?;
|
||||
if !signing_key.matches_certificate(leaf)? {
|
||||
return Err(RequestIdentityError::KeyMismatch.into());
|
||||
}
|
||||
for certificate in certificates.iter().skip(1) {
|
||||
x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
}
|
||||
// The local key has been matched without applying peer certificate policy.
|
||||
Ok(Arc::new(CertifiedKey::new(certificates, signing_key)))
|
||||
}
|
||||
|
||||
pub(super) fn identity_client_builder(
|
||||
identity: Arc<CertifiedKey>,
|
||||
ignore_server_certificate_errors: bool,
|
||||
) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let config = ClientConfig::builder_with_provider(provider.clone()).with_safe_default_protocol_versions()?;
|
||||
let config = if ignore_server_certificate_errors {
|
||||
config
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(IgnoreServerCertificateErrors {
|
||||
schemes: provider.signature_verification_algorithms.supported_schemes(),
|
||||
}))
|
||||
} else {
|
||||
// Match Reqwest's default system trust store, including private enterprise CAs.
|
||||
config.with_platform_verifier()?
|
||||
};
|
||||
let mut config = config.with_client_cert_resolver(Arc::new(SingleCertAndKey::from(identity)));
|
||||
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
Ok(super::request::client_builder().tls_backend_preconfigured(config))
|
||||
}
|
||||
|
||||
/// Equivalent to Reqwest's danger_accept_invalid_certs(true), used only when
|
||||
/// the user explicitly enables the existing ignore-certificate-errors setting.
|
||||
#[derive(Debug)]
|
||||
struct IgnoreServerCertificateErrors {
|
||||
schemes: Vec<SignatureScheme>,
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for IgnoreServerCertificateErrors {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_: &CertificateDer<'_>,
|
||||
_: &[CertificateDer<'_>],
|
||||
_: &ServerName<'_>,
|
||||
_: &[u8],
|
||||
_: UnixTime,
|
||||
) -> Result<ServerCertVerified, rustls::Error> {
|
||||
Ok(ServerCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
_: &[u8],
|
||||
_: &CertificateDer<'_>,
|
||||
_: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
_: &[u8],
|
||||
_: &CertificateDer<'_>,
|
||||
_: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
self.schemes.clone()
|
||||
}
|
||||
}
|
||||
@@ -90,8 +90,7 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
}
|
||||
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
|
||||
"EC PRIVATE KEY" => {
|
||||
// The signing provider validates both named and explicitly encoded curves.
|
||||
SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
return Ok(block.encoded());
|
||||
}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
|
||||
@@ -3,7 +3,6 @@ pub mod xml;
|
||||
pub mod base64;
|
||||
mod certificate;
|
||||
pub mod checksum;
|
||||
mod client_tls;
|
||||
pub mod crypto;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod endpoint;
|
||||
|
||||
@@ -1,40 +1,34 @@
|
||||
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use rustls::sign::CertifiedKey;
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{certificate::pkcs12, client_tls, identity_encoding};
|
||||
use super::{certificate::pkcs12, identity_encoding};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
#[error("No private key was found. Choose the matching key file")]
|
||||
#[error("Failed to find the private key")]
|
||||
NoKey,
|
||||
#[error("This certificate or key is password-protected. Enter its password")]
|
||||
#[error("No passphrase provided")]
|
||||
NoPassphrase(&'static str),
|
||||
#[error("Could not unlock the certificate or key. Check the password and file")]
|
||||
#[error("Failed to decrypt private key")]
|
||||
DecryptError(&'static str),
|
||||
#[error("This certificate or key uses unsupported encryption. Re-export it with AES encryption")]
|
||||
UnsupportedEncryption,
|
||||
#[error("This private key format is not supported. Choose a PEM key or a PKCS#12 certificate file")]
|
||||
UnsupportedKeyFormat,
|
||||
#[error(
|
||||
"This client certificate uses an unsupported key type ({0}). Ask your VPN administrator for an RSA or P-256 certificate"
|
||||
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
|
||||
)]
|
||||
UnsupportedKeyAlgorithm(&'static str),
|
||||
#[error("The private key does not match this certificate. Choose the matching key file")]
|
||||
KeyMismatch,
|
||||
#[error("The private key file is invalid. Choose a different key file")]
|
||||
UnsupportedEncryption,
|
||||
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
|
||||
UnsupportedKeyFormat,
|
||||
#[error("Invalid private key")]
|
||||
InvalidKey,
|
||||
#[error("The certificate file is invalid. Choose a different certificate file")]
|
||||
#[error("Invalid certificate or certificate chain")]
|
||||
InvalidCertificate,
|
||||
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
|
||||
IncompletePkcs12,
|
||||
#[error("Could not open the PKCS#12 file. Check the password or choose another file")]
|
||||
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
|
||||
InvalidPkcs12(#[source] p12_keystore::error::Error),
|
||||
#[error(
|
||||
"The certificate file contains more than one matching identity. Choose a file with one client certificate and key"
|
||||
)]
|
||||
#[error("The PKCS#12 file must contain one matching client identity")]
|
||||
AmbiguousPkcs12,
|
||||
}
|
||||
|
||||
@@ -44,7 +38,7 @@ pub enum RequestIdentityError {
|
||||
#[derive(Clone)]
|
||||
pub struct ClientIdentity {
|
||||
material: Arc<IdentityMaterial>,
|
||||
certified_key: Arc<CertifiedKey>,
|
||||
identity: Identity,
|
||||
}
|
||||
|
||||
struct IdentityMaterial {
|
||||
@@ -74,14 +68,14 @@ impl ClientIdentity {
|
||||
};
|
||||
let key = identity_encoding::private_key(&key_bytes, passphrase)?;
|
||||
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
|
||||
let certified_key = client_tls::pem_certified_key(&certificate, &key)?;
|
||||
let identity = pem_request_identity(&certificate, &key)?;
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
key: Some(key),
|
||||
passphrase: None,
|
||||
}),
|
||||
certified_key,
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -92,12 +86,12 @@ impl ClientIdentity {
|
||||
key: Option<Zeroizing<Vec<u8>>>,
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let (certified_key, passphrase) = match &key {
|
||||
Some(key) => (client_tls::pem_certified_key(&certificate, key)?, None),
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (pem_request_identity(&certificate, key)?, None),
|
||||
None => {
|
||||
let certified_key = pkcs12::certified_key(&certificate, passphrase)?;
|
||||
let identity = pkcs12::identity(&certificate, passphrase)?;
|
||||
(
|
||||
certified_key,
|
||||
identity,
|
||||
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
|
||||
)
|
||||
}
|
||||
@@ -108,7 +102,7 @@ impl ClientIdentity {
|
||||
key,
|
||||
passphrase,
|
||||
}),
|
||||
certified_key,
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -121,8 +115,8 @@ impl ClientIdentity {
|
||||
pub fn key_password(&self) -> Option<&str> {
|
||||
self.material.passphrase.as_ref().map(|value| value.as_str())
|
||||
}
|
||||
pub(crate) fn client_builder(&self, ignore_tls_errors: bool) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
client_tls::identity_client_builder(self.certified_key.clone(), ignore_tls_errors)
|
||||
pub(crate) fn request_identity(&self) -> Identity {
|
||||
self.identity.clone()
|
||||
}
|
||||
|
||||
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
|
||||
@@ -155,6 +149,29 @@ impl ClientIdentityFiles {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
let error_context =
|
||||
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
|
||||
let mut combined = Zeroizing::new(certificate.to_vec());
|
||||
combined.push(b'\n');
|
||||
combined.extend_from_slice(key);
|
||||
let identity = Identity::from_pem(&combined).context(error_context)?;
|
||||
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(error_context)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
|
||||
.context(error_context)?
|
||||
.context(error_context)?;
|
||||
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
|
||||
.context(error_context)?;
|
||||
client_builder()
|
||||
.no_proxy()
|
||||
.identity(identity.clone())
|
||||
.build()
|
||||
.context(error_context)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
Ok(Zeroizing::new(
|
||||
fs::read(path).context("Failed to read client identity")?,
|
||||
@@ -191,6 +208,12 @@ pub fn client_builder() -> reqwest::ClientBuilder {
|
||||
reqwest::Client::builder().tls_backend_rustls()
|
||||
}
|
||||
|
||||
/// General request clients may load an identity directly. Session owners call
|
||||
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -199,29 +222,6 @@ mod tests {
|
||||
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem");
|
||||
const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem");
|
||||
|
||||
#[test]
|
||||
fn unsupported_identity_errors_explain_the_action_without_blaming_passwords_or_key_matching() {
|
||||
for error in [
|
||||
RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"),
|
||||
RequestIdentityError::UnsupportedEncryption,
|
||||
RequestIdentityError::UnsupportedKeyFormat,
|
||||
] {
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.contains("unsupported") || message.contains("not supported"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("Ask ") || message.contains("Re-export ") || message.contains("Choose "),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
!message.contains("password") && !message.contains("does not match"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_without_key_reports_missing_key_even_with_passphrase() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
@@ -247,21 +247,21 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_loading_preserves_password_errors_and_builds_a_request_client() {
|
||||
fn create_identity_preserves_password_errors_and_builds_a_request_client() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(ENCRYPTED_KEY).unwrap();
|
||||
for (password, missing) in [(None, true), (Some("wrong"), false)] {
|
||||
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, password).unwrap_err();
|
||||
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("Unexpected identity error: {other:?}"),
|
||||
}
|
||||
}
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
drop(source);
|
||||
identity.client_builder(false).unwrap().build().unwrap();
|
||||
client_builder().identity(identity).build().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -283,7 +283,7 @@ mod tests {
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&path).exists());
|
||||
identity.client_builder(false).unwrap().build().unwrap();
|
||||
client_builder().identity(identity.request_identity()).build().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
//! 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();
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
//! A PKCS#12 CA rollover must send the intermediate that signed the client.
|
||||
use gpapi::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile},
|
||||
utils::request::ClientIdentity,
|
||||
};
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
bn::BigNum,
|
||||
ec::{EcGroup, EcKey},
|
||||
hash::MessageDigest,
|
||||
nid::Nid,
|
||||
pkey::{PKey, Private},
|
||||
ssl::{SslAcceptor, SslMethod, SslVerifyMode},
|
||||
stack::Stack,
|
||||
x509::{
|
||||
X509, X509NameBuilder,
|
||||
extension::{AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectKeyIdentifier},
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::TcpListener,
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
fn key() -> PKey<Private> {
|
||||
PKey::from_ec_key(EcKey::generate(&EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn certificate(
|
||||
name: &str,
|
||||
key: &PKey<Private>,
|
||||
issuer: Option<(&X509, &PKey<Private>)>,
|
||||
serial: u32,
|
||||
ca: bool,
|
||||
key_identifiers: bool,
|
||||
) -> X509 {
|
||||
let mut subject = X509NameBuilder::new().unwrap();
|
||||
subject.append_entry_by_text("CN", name).unwrap();
|
||||
let subject = subject.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
cert
|
||||
.set_serial_number(&BigNum::from_u32(serial).unwrap().to_asn1_integer().unwrap())
|
||||
.unwrap();
|
||||
cert.set_subject_name(&subject).unwrap();
|
||||
cert
|
||||
.set_issuer_name(issuer.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
|
||||
.unwrap();
|
||||
cert.set_pubkey(key).unwrap();
|
||||
cert
|
||||
.set_not_before(&Asn1Time::from_unix(1_700_000_000).unwrap())
|
||||
.unwrap();
|
||||
cert
|
||||
.set_not_after(&Asn1Time::from_unix(4_000_000_000).unwrap())
|
||||
.unwrap();
|
||||
let mut constraints = BasicConstraints::new();
|
||||
if ca {
|
||||
constraints.ca();
|
||||
}
|
||||
cert.append_extension(constraints.critical().build().unwrap()).unwrap();
|
||||
let mut usage = KeyUsage::new();
|
||||
if ca {
|
||||
usage.key_cert_sign();
|
||||
} else {
|
||||
usage.digital_signature();
|
||||
}
|
||||
cert.append_extension(usage.critical().build().unwrap()).unwrap();
|
||||
if key_identifiers {
|
||||
let identifier = SubjectKeyIdentifier::new()
|
||||
.build(&cert.x509v3_context(None, None))
|
||||
.unwrap();
|
||||
cert.append_extension(identifier).unwrap();
|
||||
if let Some((parent, _)) = issuer {
|
||||
let identifier = AuthorityKeyIdentifier::new()
|
||||
.keyid(true)
|
||||
.build(&cert.x509v3_context(Some(parent), None))
|
||||
.unwrap();
|
||||
cert.append_extension(identifier).unwrap();
|
||||
}
|
||||
}
|
||||
cert
|
||||
.sign(issuer.map(|(_, key)| key).unwrap_or(key), MessageDigest::sha256())
|
||||
.unwrap();
|
||||
cert.build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pkcs12_ca_rollover_authenticates_in_both_bag_orders() {
|
||||
for self_issued in [false, true] {
|
||||
let root_key = key();
|
||||
// Ordinary rollover also works without AKI/SKI. The self-issued chain
|
||||
// needs key identifiers so the independent server distinguishes its root.
|
||||
let root = certificate("Root", &root_key, None, 1, true, self_issued);
|
||||
let issuer_name = if self_issued { "Root" } else { "Issuing CA" };
|
||||
let old_key = key();
|
||||
let old = certificate(issuer_name, &old_key, Some((&root, &root_key)), 2, true, self_issued);
|
||||
let current_key = key();
|
||||
let current = certificate(
|
||||
issuer_name,
|
||||
¤t_key,
|
||||
Some((&root, &root_key)),
|
||||
3,
|
||||
true,
|
||||
self_issued,
|
||||
);
|
||||
let client_key = key();
|
||||
let leaf = certificate(
|
||||
"Client",
|
||||
&client_key,
|
||||
Some((¤t, ¤t_key)),
|
||||
4,
|
||||
false,
|
||||
self_issued,
|
||||
);
|
||||
for old_first in [true, false] {
|
||||
let mut ca = Stack::new().unwrap();
|
||||
let intermediates = if old_first { [&old, ¤t] } else { [¤t, &old] };
|
||||
for cert in intermediates {
|
||||
ca.push(cert.clone()).unwrap();
|
||||
}
|
||||
ca.push(root.clone()).unwrap();
|
||||
authenticate(&root, ¤t, &leaf, &client_key, ca).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn authenticate(root: &X509, current: &X509, leaf: &X509, client_key: &PKey<Private>, ca: Stack<X509>) {
|
||||
let archive = openssl::pkcs12::Pkcs12::builder()
|
||||
.pkey(client_key)
|
||||
.cert(leaf)
|
||||
.ca(ca)
|
||||
.build2("test")
|
||||
.unwrap()
|
||||
.to_der()
|
||||
.unwrap();
|
||||
let identity = ClientIdentity::from_data(Zeroizing::new(archive.clone()), None, Some("test")).unwrap();
|
||||
assert_eq!(
|
||||
identity.certificate_data(),
|
||||
archive,
|
||||
"OpenConnect must retain the original archive"
|
||||
);
|
||||
let profile = OsProfile::builder(ClientOs::Linux).build(HostSnapshot {
|
||||
runtime_os: ClientOs::Linux,
|
||||
identity: HostIdentity::application("test".into(), "test".into()),
|
||||
os_version: "test".into(),
|
||||
software_version: "test".into(),
|
||||
});
|
||||
let params = GpParams::builder(profile)
|
||||
.client_identity(Some(identity))
|
||||
.ignore_tls_errors(true)
|
||||
.build();
|
||||
let client = reqwest::Client::try_from(¶ms).unwrap();
|
||||
let server_key = key();
|
||||
let mut server = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
|
||||
server
|
||||
.set_certificate(&certificate("Server", &server_key, None, 5, false, false))
|
||||
.unwrap();
|
||||
server.set_private_key(&server_key).unwrap();
|
||||
server.cert_store_mut().add_cert(root.clone()).unwrap();
|
||||
server.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let server = server.build();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let address = format!("https://{}", listener.local_addr().unwrap());
|
||||
let expected_leaf = leaf.to_der().unwrap();
|
||||
let expected_issuer = current.to_der().unwrap();
|
||||
let worker = thread::spawn(move || {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let socket = loop {
|
||||
match listener.accept() {
|
||||
Ok((socket, _)) => break socket,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => {
|
||||
thread::sleep(Duration::from_millis(5))
|
||||
}
|
||||
Err(error) => return Err(error.to_string()),
|
||||
}
|
||||
};
|
||||
socket.set_nonblocking(false).unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
socket.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut socket = server.accept(socket).map_err(|error| error.to_string())?;
|
||||
assert_eq!(
|
||||
socket.ssl().peer_certificate().unwrap().to_der().unwrap(),
|
||||
expected_leaf
|
||||
);
|
||||
assert!(
|
||||
socket
|
||||
.ssl()
|
||||
.peer_cert_chain()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|cert| cert.to_der().unwrap() == expected_issuer)
|
||||
);
|
||||
let mut request = [0; 4096];
|
||||
socket.read(&mut request).map_err(|error| error.to_string())?;
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
let response = client.get(address).timeout(Duration::from_secs(5)).send().await;
|
||||
let server_result = worker.join().unwrap();
|
||||
assert!(server_result.is_ok(), "{server_result:?}; {response:?}");
|
||||
assert_eq!(response.unwrap().text().await.unwrap(), "ok");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pkcs12_pss_certificate_signature_parameters_authenticate() {
|
||||
let root = X509::from_pem(include_bytes!("files/client-identity/pss-chain-root.pem")).unwrap();
|
||||
let issuer = X509::from_pem(include_bytes!("files/client-identity/pss-chain-issuer.pem")).unwrap();
|
||||
let client_key = PKey::private_key_from_pem(include_bytes!("files/client-identity/rsa-pkcs8.pem")).unwrap();
|
||||
let wrong_key = PKey::from_rsa(openssl::rsa::Rsa::generate(2048).unwrap()).unwrap();
|
||||
let wrong_issuer = certificate("PSS Issuing CA", &wrong_key, None, 6, true, false);
|
||||
for certificate in [
|
||||
include_bytes!("files/client-identity/pss-chain-salt-20.pem").as_slice(),
|
||||
include_bytes!("files/client-identity/pss-chain-salt-32.pem").as_slice(),
|
||||
include_bytes!("files/client-identity/pss-chain-salt-48.pem").as_slice(),
|
||||
] {
|
||||
let leaf = X509::from_pem(certificate).unwrap();
|
||||
assert!(leaf.verify(&issuer.public_key().unwrap()).unwrap());
|
||||
for wrong_first in [true, false] {
|
||||
let mut ca = Stack::new().unwrap();
|
||||
let candidates = if wrong_first {
|
||||
[&wrong_issuer, &issuer]
|
||||
} else {
|
||||
[&issuer, &wrong_issuer]
|
||||
};
|
||||
for candidate in candidates {
|
||||
ca.push(candidate.clone()).unwrap();
|
||||
}
|
||||
ca.push(root.clone()).unwrap();
|
||||
authenticate(&root, &issuer, &leaf, &client_key, ca).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,419 +0,0 @@
|
||||
//! Issue #697: local identity matching must not apply a peer's extension policy.
|
||||
//! OpenSSL is an independent test oracle/server, never a product import backend.
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
net::TcpListener,
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile},
|
||||
utils::request::{ClientIdentity, RequestIdentityError},
|
||||
};
|
||||
use openssl::{
|
||||
asn1::{Asn1Object, Asn1OctetString, Asn1Time},
|
||||
ec::{EcGroup, EcKey},
|
||||
hash::MessageDigest,
|
||||
nid::Nid,
|
||||
pkey::{Id, PKey, Private},
|
||||
ssl::{SslAcceptor, SslConnector, SslMethod, SslVerifyMode, SslVersion},
|
||||
x509::{X509, X509Extension, X509NameBuilder},
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const PASSWORD: &str = "fixture-password";
|
||||
|
||||
fn key(family: &str) -> PKey<Private> {
|
||||
if family == "ec-p384" {
|
||||
let group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap();
|
||||
return PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
|
||||
}
|
||||
if family == "ed25519" {
|
||||
return PKey::generate_ed25519().unwrap();
|
||||
}
|
||||
let bytes: &[u8] = match family {
|
||||
"rsa" => include_bytes!("files/client-identity/rsa-pkcs8.pem"),
|
||||
"ec" => include_bytes!("files/client-identity/ec-pkcs8.pem"),
|
||||
_ => panic!("unknown key family"),
|
||||
};
|
||||
PKey::private_key_from_pem(bytes).unwrap()
|
||||
}
|
||||
|
||||
fn certificate(key: &PKey<Private>, extension: Option<(&str, bool, &[u8])>) -> X509 {
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "Public regression identity").unwrap();
|
||||
let name = name.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
cert.set_subject_name(&name).unwrap();
|
||||
cert.set_issuer_name(&name).unwrap();
|
||||
cert.set_pubkey(key).unwrap();
|
||||
cert
|
||||
.set_not_before(&Asn1Time::from_unix(1_700_000_000).unwrap())
|
||||
.unwrap();
|
||||
cert
|
||||
.set_not_after(&Asn1Time::from_unix(4_000_000_000).unwrap())
|
||||
.unwrap();
|
||||
if let Some((oid, critical, value)) = extension {
|
||||
let oid = Asn1Object::from_str(oid).unwrap();
|
||||
let value = Asn1OctetString::new_from_bytes(value).unwrap();
|
||||
cert
|
||||
.append_extension(X509Extension::new_from_der(&oid, critical, &value).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
let digest = if key.id() == Id::ED25519 {
|
||||
MessageDigest::null()
|
||||
} else {
|
||||
MessageDigest::sha256()
|
||||
};
|
||||
cert.sign(key, digest).unwrap();
|
||||
cert.build()
|
||||
}
|
||||
|
||||
fn private_extension() -> Option<(&'static str, bool, &'static [u8])> {
|
||||
Some(("1.3.6.1.4.1.55555.1", true, &[0x05, 0x00]))
|
||||
}
|
||||
|
||||
fn params(identity: ClientIdentity, ignore_tls_errors: bool) -> GpParams {
|
||||
let snapshot = HostSnapshot {
|
||||
runtime_os: ClientOs::Linux,
|
||||
identity: HostIdentity::application("regression-test".into(), "public-test-id".into()),
|
||||
os_version: "test".into(),
|
||||
software_version: "test".into(),
|
||||
};
|
||||
GpParams::builder(OsProfile::builder(ClientOs::Linux).build(snapshot))
|
||||
.client_identity(Some(identity))
|
||||
.ignore_tls_errors(ignore_tls_errors)
|
||||
.build()
|
||||
}
|
||||
|
||||
fn assert_usable(identity: ClientIdentity) {
|
||||
reqwest::Client::try_from(¶ms(identity.clone(), false)).unwrap();
|
||||
reqwest::Client::try_from(¶ms(identity.clone(), true)).unwrap();
|
||||
let restored = ClientIdentity::from_data(
|
||||
Zeroizing::new(identity.certificate_data().to_vec()),
|
||||
identity.key_data().map(|key| Zeroizing::new(key.to_vec())),
|
||||
identity.key_password(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(restored.certificate_data(), identity.certificate_data());
|
||||
let files = restored.write_files(None).unwrap();
|
||||
ClientIdentity::load(files.certificate(), files.key(), restored.key_password()).unwrap();
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Container {
|
||||
SeparatePem,
|
||||
CombinedPem,
|
||||
Der,
|
||||
Pkcs12,
|
||||
Snapshot,
|
||||
}
|
||||
|
||||
fn load(container: Container, cert: &X509, key: &PKey<Private>) -> anyhow::Result<ClientIdentity> {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("client.pem");
|
||||
let key_path = directory.path().join("client.key");
|
||||
let key_pem = key.private_key_to_pem_pkcs8().unwrap();
|
||||
fs::write(&key_path, &key_pem).unwrap();
|
||||
match container {
|
||||
Container::SeparatePem => {
|
||||
fs::write(&source, cert.to_pem().unwrap()).unwrap();
|
||||
ClientIdentity::load(source.to_str().unwrap(), Some(key_path.to_str().unwrap()), None)
|
||||
}
|
||||
Container::CombinedPem => {
|
||||
let mut combined = cert.to_pem().unwrap();
|
||||
combined.extend(&key_pem);
|
||||
fs::write(&source, combined).unwrap();
|
||||
ClientIdentity::load(source.to_str().unwrap(), None, None)
|
||||
}
|
||||
Container::Der => {
|
||||
fs::write(&source, cert.to_der().unwrap()).unwrap();
|
||||
fs::write(&key_path, key.private_key_to_pkcs8().unwrap()).unwrap();
|
||||
ClientIdentity::load(source.to_str().unwrap(), Some(key_path.to_str().unwrap()), None)
|
||||
}
|
||||
Container::Pkcs12 => {
|
||||
let mut archive = openssl::pkcs12::Pkcs12::builder();
|
||||
archive.name("public regression identity").pkey(key).cert(cert);
|
||||
let archive = archive.build2(PASSWORD).unwrap().to_der().unwrap();
|
||||
let source = directory.path().join("client.p12");
|
||||
fs::write(&source, archive).unwrap();
|
||||
ClientIdentity::load(source.to_str().unwrap(), None, Some(PASSWORD))
|
||||
}
|
||||
Container::Snapshot => ClientIdentity::from_data(
|
||||
Zeroizing::new(cert.to_pem().unwrap()),
|
||||
Some(Zeroizing::new(key_pem)),
|
||||
None,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn extension_matrix(container: Container) {
|
||||
let cases: &[(&str, Option<(&str, bool, &[u8])>)] = &[
|
||||
("no extensions", None),
|
||||
(
|
||||
"private noncritical",
|
||||
Some(("1.3.6.1.4.1.55555.1", false, &[0x05, 0x00])),
|
||||
),
|
||||
("private critical", private_extension()),
|
||||
// Netscape certificate type and Microsoft certificate template name are
|
||||
// realistic enterprise extensions that WebPKI does not interpret.
|
||||
(
|
||||
"Netscape client type",
|
||||
Some(("2.16.840.1.113730.1.1", true, &[0x03, 0x02, 0x07, 0x80])),
|
||||
),
|
||||
(
|
||||
"Microsoft template",
|
||||
Some(("1.3.6.1.4.1.311.20.2", true, &[0x1e, 0x02, 0x00, b'A'])),
|
||||
),
|
||||
(
|
||||
"critical key usage",
|
||||
Some(("2.5.29.15", true, &[0x03, 0x02, 0x07, 0x80])),
|
||||
),
|
||||
(
|
||||
"critical client EKU",
|
||||
Some((
|
||||
"2.5.29.37",
|
||||
true,
|
||||
&[0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02],
|
||||
)),
|
||||
),
|
||||
];
|
||||
for family in ["rsa", "ec", "ec-p384", "ed25519"] {
|
||||
let key = key(family);
|
||||
for &(name, extension) in cases {
|
||||
let cert = certificate(&key, extension);
|
||||
// The previous OpenSSL backend accepts this local certificate/key pair.
|
||||
let mut oracle = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
oracle.set_certificate(&cert).unwrap();
|
||||
oracle.set_private_key(&key).unwrap();
|
||||
oracle.check_private_key().unwrap();
|
||||
let identity =
|
||||
load(container, &cert, &key).unwrap_or_else(|error| panic!("{container:?}/{family}/{name}: {error:#}"));
|
||||
if !matches!(container, Container::Pkcs12) {
|
||||
assert_eq!(identity.certificate_data(), cert.to_pem().unwrap());
|
||||
}
|
||||
assert_usable(identity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_pem_extension_matrix() {
|
||||
extension_matrix(Container::SeparatePem);
|
||||
}
|
||||
#[test]
|
||||
fn combined_pem_extension_matrix() {
|
||||
extension_matrix(Container::CombinedPem);
|
||||
}
|
||||
#[test]
|
||||
fn der_extension_matrix() {
|
||||
extension_matrix(Container::Der);
|
||||
}
|
||||
#[test]
|
||||
fn pkcs12_extension_matrix() {
|
||||
extension_matrix(Container::Pkcs12);
|
||||
}
|
||||
#[test]
|
||||
fn snapshot_extension_matrix() {
|
||||
extension_matrix(Container::Snapshot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn critical_extensions_do_not_hide_a_mismatched_private_key() {
|
||||
for family in ["rsa", "ec"] {
|
||||
let cert = certificate(&key(family), private_extension());
|
||||
let wrong_family = if family == "rsa" { "ec" } else { "rsa" };
|
||||
let same_family_wrong_key = if family == "rsa" {
|
||||
PKey::from_rsa(openssl::rsa::Rsa::generate(2048).unwrap()).unwrap()
|
||||
} else {
|
||||
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
|
||||
PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap()
|
||||
};
|
||||
// PEM and service snapshots can carry mismatched material. OpenSSL's
|
||||
// PKCS#12 writer itself rejects a mismatch; existing archive fixtures cover it.
|
||||
for wrong_key in [key(wrong_family), same_family_wrong_key] {
|
||||
for container in [
|
||||
Container::SeparatePem,
|
||||
Container::CombinedPem,
|
||||
Container::Der,
|
||||
Container::Snapshot,
|
||||
] {
|
||||
let error = load(container, &cert, &wrong_key).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::KeyMismatch)
|
||||
),
|
||||
"{error:#}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_identity_preparation_keeps_critical_extensions_after_source_files_are_removed() {
|
||||
let key = key("rsa");
|
||||
let cert = certificate(&key, private_extension());
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("client.pem");
|
||||
let key_path = directory.path().join("client.key");
|
||||
fs::write(&source, cert.to_pem().unwrap()).unwrap();
|
||||
fs::write(&key_path, key.private_key_to_pem_pkcs8().unwrap()).unwrap();
|
||||
let identity = load(Container::Snapshot, &cert, &key).unwrap();
|
||||
let profile = params(identity, false).os_profile().clone();
|
||||
// Start with the unprepared path used by the reported gateway prelogin.
|
||||
let mut params = GpParams::builder(profile)
|
||||
.certificate(Some(source.to_string_lossy().into_owned()))
|
||||
.sslkey(Some(key_path.to_string_lossy().into_owned()))
|
||||
.build();
|
||||
reqwest::Client::try_from(¶ms).unwrap();
|
||||
params.prepare_client_identity().unwrap();
|
||||
drop(directory);
|
||||
reqwest::Client::try_from(¶ms).unwrap();
|
||||
assert_eq!(
|
||||
params.client_identity().unwrap().certificate_data(),
|
||||
cert.to_pem().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn critical_extension_in_a_chain_preserves_every_certificate() {
|
||||
let key = key("rsa");
|
||||
let cert = certificate(&key, private_extension());
|
||||
let mut chain = cert.to_pem().unwrap();
|
||||
chain.extend(include_bytes!("files/client-identity/root.pem"));
|
||||
let identity = ClientIdentity::from_data(
|
||||
Zeroizing::new(chain.clone()),
|
||||
Some(Zeroizing::new(key.private_key_to_pem_pkcs8().unwrap())),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_usable(identity);
|
||||
}
|
||||
|
||||
fn server(
|
||||
cert: &X509,
|
||||
key: &PKey<Private>,
|
||||
version: SslVersion,
|
||||
expected_client: Vec<u8>,
|
||||
accept_client: bool,
|
||||
) -> (String, thread::JoinHandle<bool>) {
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
|
||||
acceptor.set_certificate(cert).unwrap();
|
||||
acceptor.set_private_key(key).unwrap();
|
||||
acceptor.set_min_proto_version(Some(version)).unwrap();
|
||||
acceptor.set_max_proto_version(Some(version)).unwrap();
|
||||
// Model a VPN that understands this private extension. TLS still verifies
|
||||
// CertificateVerify; the server also checks the exact leaf bytes below.
|
||||
acceptor.set_verify_callback(
|
||||
SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT,
|
||||
move |_, _| accept_client,
|
||||
);
|
||||
let acceptor = acceptor.build();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let address = format!("https://{}", listener.local_addr().unwrap());
|
||||
let worker = thread::spawn(move || {
|
||||
// Bound failures even if client construction or connection fails.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
}
|
||||
};
|
||||
stream.set_nonblocking(false).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let Ok(mut stream) = acceptor.accept(stream) else {
|
||||
return false;
|
||||
};
|
||||
let peer = stream.ssl().peer_certificate().unwrap();
|
||||
assert_eq!(
|
||||
peer.to_der().unwrap(),
|
||||
expected_client,
|
||||
"the original signed certificate must be sent unchanged"
|
||||
);
|
||||
assert!(peer.verify(&peer.public_key().unwrap()).unwrap());
|
||||
let mut request = [0; 4096];
|
||||
if stream.read(&mut request).is_err() {
|
||||
return false;
|
||||
}
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
|
||||
.is_ok()
|
||||
});
|
||||
(address, worker)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn critical_extension_identity_completes_tls12_and_tls13_client_authentication() {
|
||||
let server_key = key("rsa");
|
||||
let server_cert = certificate(&server_key, None);
|
||||
for family in ["rsa", "ec", "ec-p384", "ed25519"] {
|
||||
let key = key(family);
|
||||
let cert = certificate(&key, private_extension());
|
||||
for container in [Container::SeparatePem, Container::Pkcs12] {
|
||||
for version in [SslVersion::TLS1_2, SslVersion::TLS1_3] {
|
||||
let identity = load(container, &cert, &key).unwrap();
|
||||
let client = reqwest::Client::try_from(¶ms(identity, true)).unwrap();
|
||||
let (address, worker) = server(&server_cert, &server_key, version, cert.to_der().unwrap(), true);
|
||||
let result = client.get(address).timeout(Duration::from_secs(5)).send().await;
|
||||
assert!(
|
||||
worker.join().unwrap(),
|
||||
"{family}/{container:?}/{version:?}: server did not complete client authentication"
|
||||
);
|
||||
assert_eq!(result.unwrap().text().await.unwrap(), "ok");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_extensions_do_not_disable_server_trust_or_peer_rejection() {
|
||||
let key = key("rsa");
|
||||
let cert = certificate(&key, private_extension());
|
||||
let server_cert = certificate(&key, None);
|
||||
for (ignore_server_errors, accept_client) in [(false, true), (true, false)] {
|
||||
for version in [SslVersion::TLS1_2, SslVersion::TLS1_3] {
|
||||
let identity = load(Container::SeparatePem, &cert, &key).unwrap();
|
||||
let client = reqwest::Client::try_from(¶ms(identity, ignore_server_errors)).unwrap();
|
||||
let (address, worker) = server(&server_cert, &key, version, cert.to_der().unwrap(), accept_client);
|
||||
let result = client.get(address).timeout(Duration::from_secs(5)).send().await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"server trust and peer rejection must still be enforced"
|
||||
);
|
||||
assert!(!worker.join().unwrap());
|
||||
let error = result.unwrap_err();
|
||||
assert!(
|
||||
!error.is_timeout(),
|
||||
"expected a TLS rejection, not a timeout: {error:?}"
|
||||
);
|
||||
let details = format!("{error:?}");
|
||||
if ignore_server_errors {
|
||||
assert!(
|
||||
details.contains("AlertReceived"),
|
||||
"expected the server's client-certificate rejection: {details}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
details.contains("InvalidCertificate"),
|
||||
"expected server certificate validation to fail: {details}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
//! Recorded 3.2 compatibility gap: TLS 1.2 ECDSA hashes are not curve-bound.
|
||||
//! OpenSSL is a test-only baseline and peer, never a product TLS backend.
|
||||
#![cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::{TcpListener, TcpStream},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile},
|
||||
utils::request::ClientIdentity,
|
||||
};
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
ec::{EcGroup, EcKey},
|
||||
hash::MessageDigest,
|
||||
nid::Nid,
|
||||
pkey::{PKey, Private},
|
||||
ssl::{SslAcceptor, SslConnector, SslMethod, SslVerifyMode, SslVersion},
|
||||
x509::{X509, X509NameBuilder},
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
fn identity(curve: Nid, name: &str) -> (PKey<Private>, X509) {
|
||||
let group = EcGroup::from_curve_name(curve).unwrap();
|
||||
let key = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
|
||||
let mut subject = X509NameBuilder::new().unwrap();
|
||||
subject.append_entry_by_text("CN", name).unwrap();
|
||||
let subject = subject.build();
|
||||
let mut certificate = X509::builder().unwrap();
|
||||
certificate.set_version(2).unwrap();
|
||||
certificate.set_subject_name(&subject).unwrap();
|
||||
certificate.set_issuer_name(&subject).unwrap();
|
||||
certificate.set_pubkey(&key).unwrap();
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
certificate.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
(key, certificate.build())
|
||||
}
|
||||
|
||||
fn sha256_only_tls12_peer(expected: &X509) -> (String, thread::JoinHandle<Result<(), String>>) {
|
||||
let (key, certificate) = identity(Nid::X9_62_PRIME256V1, "Public TLS 1.2 peer");
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
|
||||
acceptor.set_certificate(&certificate).unwrap();
|
||||
acceptor.set_private_key(&key).unwrap();
|
||||
acceptor.set_min_proto_version(Some(SslVersion::TLS1_2)).unwrap();
|
||||
acceptor.set_max_proto_version(Some(SslVersion::TLS1_2)).unwrap();
|
||||
// P-256 server authentication works with this list. The P-384 client must
|
||||
// also sign with SHA-256, which is allowed in TLS 1.2 but not TLS 1.3.
|
||||
acceptor.set_sigalgs_list("ECDSA+SHA256").unwrap();
|
||||
let expected = expected.to_der().unwrap();
|
||||
let pinned = expected.clone();
|
||||
acceptor.set_verify_callback(
|
||||
SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT,
|
||||
move |_, context| {
|
||||
context.error_depth() == 0
|
||||
&& context
|
||||
.current_cert()
|
||||
.is_some_and(|certificate| certificate.to_der().unwrap() == pinned)
|
||||
},
|
||||
);
|
||||
let acceptor = acceptor.build();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let worker = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => {
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(error) => return Err(format!("Accepting TLS peer: {error}")),
|
||||
}
|
||||
};
|
||||
stream.set_nonblocking(false).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
// SSL_accept checks the client's CertificateVerify proof of possession.
|
||||
let mut stream = acceptor
|
||||
.accept(stream)
|
||||
.map_err(|error| format!("Client authentication: {error}"))?;
|
||||
assert_eq!(stream.ssl().version2(), Some(SslVersion::TLS1_2));
|
||||
assert_eq!(stream.ssl().peer_certificate().unwrap().to_der().unwrap(), expected);
|
||||
let mut request = [0; 4096];
|
||||
let length = stream.read(&mut request).map_err(|error| error.to_string())?;
|
||||
assert!(length > 0);
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
(address, worker)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openssl_baseline_authenticates_p384_with_tls12_sha256() {
|
||||
let (key, certificate) = identity(Nid::SECP384R1, "Public P-384 client");
|
||||
let (address, peer) = sha256_only_tls12_peer(&certificate);
|
||||
let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
connector.set_certificate(&certificate).unwrap();
|
||||
connector.set_private_key(&key).unwrap();
|
||||
// This fixture isolates client authentication; the peer pins the exact leaf.
|
||||
connector.set_verify(SslVerifyMode::NONE);
|
||||
let socket = TcpStream::connect(address).unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
socket.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut stream = connector.build().connect("localhost", socket).unwrap();
|
||||
stream.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
|
||||
let mut response = [0; 1024];
|
||||
assert!(stream.read(&mut response).unwrap() > 0);
|
||||
peer.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "Known regression from 3.2: P-384 signs only SHA-384; Rustls SigningKey has no negotiated version to safely allow TLS 1.2 SHA-256 while preserving TLS 1.3 curve binding"]
|
||||
async fn p384_authenticates_with_tls12_sha256() {
|
||||
let (key, certificate) = identity(Nid::SECP384R1, "Public P-384 client");
|
||||
let identity = ClientIdentity::from_data(
|
||||
Zeroizing::new(certificate.to_pem().unwrap()),
|
||||
Some(Zeroizing::new(key.private_key_to_pem_pkcs8().unwrap())),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let snapshot = HostSnapshot {
|
||||
runtime_os: ClientOs::Linux,
|
||||
identity: HostIdentity::application("regression-test".into(), "public-test-id".into()),
|
||||
os_version: "test".into(),
|
||||
software_version: "test".into(),
|
||||
};
|
||||
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(snapshot))
|
||||
.client_identity(Some(identity))
|
||||
.ignore_tls_errors(true)
|
||||
.build();
|
||||
let client = reqwest::Client::try_from(¶ms).unwrap();
|
||||
let (address, peer) = sha256_only_tls12_peer(&certificate);
|
||||
let response = client
|
||||
.get(format!("https://{address}"))
|
||||
.timeout(Duration::from_secs(5))
|
||||
.send()
|
||||
.await;
|
||||
let authentication = peer.join().unwrap();
|
||||
assert!(authentication.is_ok(), "{authentication:?}; HTTP result: {response:?}");
|
||||
assert_eq!(response.unwrap().text().await.unwrap(), "ok");
|
||||
}
|
||||
@@ -114,10 +114,11 @@ fn malformed_rsa_pkcs1_is_rejected_before_connection() {
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::InvalidKey)
|
||||
));
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
}
|
||||
|
||||
fn check_archive(name: &str, password: &str) {
|
||||
@@ -603,15 +604,17 @@ fn mismatched_certificate_key_is_rejected_before_request_client_creation() {
|
||||
let certificate = fs::read(fixture("root.pem")).unwrap();
|
||||
let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
let error = load("root.pem", "rsa-pkcs8.pem", None).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::KeyMismatch)
|
||||
));
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
let error = ClientIdentity::from_data(certificate.into(), Some(key.into()), None).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::KeyMismatch)
|
||||
));
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -637,7 +640,7 @@ fn pkcs12_rejects_mismatched_and_multiple_identities() {
|
||||
let error = ClientIdentity::load(fixture(name).to_str().unwrap(), None, None).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous),
|
||||
Some(RequestIdentityError::KeyMismatch) => assert!(!ambiguous),
|
||||
Some(RequestIdentityError::InvalidCertificate) => assert!(!ambiguous),
|
||||
other => panic!("{name}: unexpected archive error: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ optional fixture-generation script, not identity import.
|
||||
| Files | Contents |
|
||||
| --- | --- |
|
||||
| `root.pem`, `rsa-cert.pem`, `ec-cert.pem` | Test root and issued RSA-2048 / P-256 client certificates, SHA256 signatures |
|
||||
| `rsa-critical-extension.pem` | Self-signed certificate for the existing RSA key with a private critical extension; issue #697 desktop validation regression |
|
||||
| `rsa-pkcs8.pem`, `ec-pkcs8.pem` | Plain PKCS#8 keys; expected normalized output |
|
||||
| `rsa-pkcs1.pem`, `ec-sec1.pem` | Same keys in traditional containers |
|
||||
| `{rsa,ec}-traditional-{aes128,aes192,aes256,des3}.pem` | Traditional encrypted PEM with AES-CBC or 3DES-CBC; password `fixture-password` |
|
||||
@@ -35,20 +34,13 @@ optional fixture-generation script, not identity import.
|
||||
| `modern.p12`, `unicode-password.p12` | Leaf/key/root, AES256-CBC/PBKDF2-SHA256, SHA256 MAC; RSA and EC respectively |
|
||||
| `certificate-only.pfx`, `key-only.pfx` | Incomplete PKCS#12 archives: certificate without key, and key without certificate; password `fixture-password` |
|
||||
| `legacy-rc2.p12` | Issue #437 case: RC2-40 certificate bags, SHA1/3DES key bag, SHA1 MAC |
|
||||
| `ec-p521.pem`, `ec-p521-cert.pem` | Valid P-521 identity; explicit unsupported-key error until HTTP negotiation parity exists |
|
||||
| `rsa-pss.pem`, `rsa-pss-cert.pem` | Valid RSA-PSS identity; explicit unsupported-key error until Rustls negotiation parity exists |
|
||||
| `pss-chain-{root,issuer}.pem`, `pss-chain-salt-{20,32,48}.pem` | RSA client certificates signed with RSA-PSS/SHA256 and different salt lengths; client key is `rsa-pkcs8.pem`. Regenerate with `generate-pss-chain.sh` |
|
||||
| `ec-{compressed,explicit}.pem`, matching `-cert.pem` files | Valid OpenSSL inputs rejected by the tested GnuTLS backend; actionable unsupported-encoding tests |
|
||||
| `legacy-RC4-128.p12` | SHA1/RC4-128 key encryption and SHA1/3DES certificate encryption; native archive import |
|
||||
| `legacy-RC2-128.p12`, `legacy-2DES.p12` | Unsupported archive encryption; terminal AES re-export guidance with any password |
|
||||
|
||||
|
||||
`tests/client_identity.rs` covers all supported key families, password failures,
|
||||
archive integrity, certificate/key matching, retained snapshots, private-file
|
||||
permissions and cleanup. `tests/identity_encoding.rs` covers PEM/DER, RSA PKCS#1,
|
||||
EC SEC1, traditional encrypted PEM, first-key selection, malformed encryption
|
||||
headers and archive extension capitalization. Desktop GnuTLS validates and signs client keys; portable builds keep the Rust
|
||||
implementation. Legacy encrypted-key imports use the private GnuTLS shim.
|
||||
headers and archive extension capitalization. Rustls validates RSA and EC keys
|
||||
on all supported targets; desktop legacy encrypted-key imports use GnuTLS.
|
||||
Legacy PKCS#12 SHA1/3DES keys use a consistent limit of 127 UTF-16 code units
|
||||
(256 bytes including the terminator), matching older supported GnuTLS releases.
|
||||
Longer passwords report a clear error without exposing the password.
|
||||
@@ -61,41 +53,6 @@ MAC. Decrypted output is compared with independent plaintext fixture keys.
|
||||
Unit tests in `utils/request.rs` cover missing keys, large local files and request
|
||||
client construction.
|
||||
|
||||
`tests/client_certificate_extensions.rs` covers issue #697 with generated
|
||||
RSA, P-256, P-384 and Ed25519 identities: no extensions, private critical and
|
||||
noncritical extensions, critical Netscape client type, Microsoft template,
|
||||
key usage and client EKU. Each is exercised as separate PEM, combined PEM,
|
||||
DER, PKCS#12 and a service snapshot, including snapshot/file round trips and
|
||||
request-client construction. Independent OpenSSL checks establish local key
|
||||
compatibility. TLS 1.2/1.3 tests verify client authentication with PEM and
|
||||
PKCS#12 and confirm the original signed certificate is sent unchanged. Negative
|
||||
cases retain key mismatch errors, server trust checks and server rejection of
|
||||
a client certificate. The checked-in critical-extension fixture also covers
|
||||
the shared certificate validation used by both desktop shells.
|
||||
|
||||
`tests/certificate_compatibility.rs` checks RC4-128 import, renewed identities and P-521 rejection,
|
||||
and typed, actionable errors for unsupported algorithms,
|
||||
EC encodings and archive encryption. The OpenConnect integration suite checks
|
||||
the real loader/handshake separately from these HTTP/import tests.
|
||||
|
||||
Desktop local matching and signing use GnuTLS. The VPN server validates client
|
||||
certificate extensions and trust; HTTP server trust still uses the platform
|
||||
verifier with Rustls/ring. RSA-PSS and P-521 key types deliberately fail before connecting
|
||||
until the HTTP transport can negotiate them correctly on both TLS versions.
|
||||
This differs from ordinary RSA keys producing RSA-PSS signatures, which remain
|
||||
supported. OpenSSL remains development-only.
|
||||
|
||||
`tests/client_certificate_chain.rs` checks mutual TLS with PKCS#12 CA rollover,
|
||||
including self-issued intermediates and both certificate bag orders. It also
|
||||
checks RSA-PSS certificate signatures with 20-, 32-, and 48-byte salts against
|
||||
a same-name, wrong-key issuer. The server must receive the original leaf and
|
||||
correct intermediate; OpenConnect must retain the original archive.
|
||||
|
||||
`tests/client_certificate_tls12_hash.rs` records the remaining TLS 1.2 P-384
|
||||
with SHA-256-only peer request gap: the OpenSSL baseline passes, while the
|
||||
replacement reproducer is explicitly ignored pending negotiated-version-aware
|
||||
signing. TLS 1.3 curve restrictions must remain intact.
|
||||
|
||||
The unencrypted, MAC-less `no-bag-ids.p12`, `mismatched.p12`, and
|
||||
`multiple-identities.p12` contain only the same public test keys/certificates.
|
||||
They exercise PKCS#12 bags without optional attributes, reversed certificate
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBiTCCAS+gAwIBAgIUHDc6Wcp0MUwwtwAhR3fEY3zLSXQwCgYIKoZIzj0EAwIw
|
||||
KjEoMCYGA1UEAwwfR1AgUHVibGljIGNvbXByZXNzZWQgUmVncmVzc2lvbjAeFw0y
|
||||
NjExMDcwMjA2MjZaFw0zNjExMDQwMjA2MjZaMCoxKDAmBgNVBAMMH0dQIFB1Ymxp
|
||||
YyBjb21wcmVzc2VkIFJlZ3Jlc3Npb24wOTATBgcqhkjOPQIBBggqhkjOPQMBBwMi
|
||||
AANCb8yN/N6VTBYHE1F66qyust8GzXKAd6pfo1cEItbJFaNTMFEwHQYDVR0OBBYE
|
||||
FIK3uCPt33xbuFkEkBQx2RBu3UIDMB8GA1UdIwQYMBaAFIK3uCPt33xbuFkEkBQx
|
||||
2RBu3UIDMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIhALe0rg77
|
||||
NMpcc8yKUnGcdWDu8GW1IE55TJf++RkJ+/JAAiBnlmSBnoZaTrPa5LEycfTJMKSN
|
||||
URn6fRsbCH1z4mQ6XQ==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,4 +0,0 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MFcCAQEEIMIgGXJZB//8Zp7TOavSyB+7LrPKFG4eQZ8Fxx30bTzUoAoGCCqGSM49
|
||||
AwEHoSQDIgADQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRU=
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -1,16 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICmTCCAj+gAwIBAgIUNb1E0mpnr5RBM1FR96iDr4We5r0wCgYIKoZIzj0EAwIw
|
||||
KDEmMCQGA1UEAwwdR1AgUHVibGljIGV4cGxpY2l0IFJlZ3Jlc3Npb24wHhcNMjYx
|
||||
MTA3MDIwNjI2WhcNMzYxMTA0MDIwNjI2WjAoMSYwJAYDVQQDDB1HUCBQdWJsaWMg
|
||||
ZXhwbGljaXQgUmVncmVzc2lvbjCCAUswggEDBgcqhkjOPQIBMIH3AgEBMCwGByqG
|
||||
SM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP///////////////zBbBCD/////
|
||||
AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12Ko6k+ez671VdpiGvGUd
|
||||
BrDMU7D2O848PifSYEsDFQDEnTYIhucEk2pmeOETnSa3gZ9+kARBBGsX0fLhLEJH
|
||||
+Lzm5WOkQPJ3A32BLeszoPShOUXYmMKWT+NC4v4af5uO5+tKfA+eFivOM1drMV7O
|
||||
y7ZAaDe/UfUCIQD/////AAAAAP//////////vOb6racXnoTzucrC/GMlUQIBAQNC
|
||||
AARCb8yN/N6VTBYHE1F66qyust8GzXKAd6pfo1cEItbJFapMj+oEjBtrobfNydlo
|
||||
CucLD5ewywG9O2mG6IMei49bo1MwUTAdBgNVHQ4EFgQUbJK+tR9aD33KGW9Ed7lV
|
||||
x1BX7qwwHwYDVR0jBBgwFoAUbJK+tR9aD33KGW9Ed7lVx1BX7qwwDwYDVR0TAQH/
|
||||
BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiAHTMFLSyvWxcE198z6beN5B4+0LnsW
|
||||
96Y06HhX5+uzaAIhANZHyKvAU4wDnTslafc7ch3ETQPBhWppgiTKHqE0+jUI
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,10 +0,0 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIIBaAIBAQQgwiAZclkH//xmntM5q9LIH7sus8oUbh5BnwXHHfRtPNSggfowgfcC
|
||||
AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////
|
||||
MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr
|
||||
vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE
|
||||
axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W
|
||||
K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8
|
||||
YyVRAgEBoUQDQgAEQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRWqTI/q
|
||||
BIwba6G3zcnZaArnCw+XsMsBvTtphuiDHouPWw==
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -1,14 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICJDCCAYagAwIBAgIURE3nvaUdT7yk7gTwyhUFyCE1+K8wCgYIKoZIzj0EAwIw
|
||||
JDEiMCAGA1UEAwwZR1AgUHVibGljIHA1MjEgUmVncmVzc2lvbjAeFw0yNjExMDcw
|
||||
MjA2MjZaFw0zNjExMDQwMjA2MjZaMCQxIjAgBgNVBAMMGUdQIFB1YmxpYyBwNTIx
|
||||
IFJlZ3Jlc3Npb24wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABAAu5HAWZpjZxfu6
|
||||
jQ+61F5CysJzWgkc4MIB4z8kW9w0x76vUGlWPX+yw0q5EzpeEGjWV82YDRoEfkDR
|
||||
fAjk8/B/8wDNJ7oH9pepkq3DroH0v3R34C8oQwbsw/Rx9JwOECR3u2jIgzNLtiEf
|
||||
iEBgucZ5MgDEgNJdB03qCvaqUmYXN7LwoqNTMFEwHQYDVR0OBBYEFOsuLBWpYWC7
|
||||
PHAVmEE4a4gypkYaMB8GA1UdIwQYMBaAFOsuLBWpYWC7PHAVmEE4a4gypkYaMA8G
|
||||
A1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDgYsAMIGHAkEPBtWqP2e1ZLiXH3V5
|
||||
Zp21p4uWCJiJxasdl3iuGgKbJiSUSM9m/90iLhan+j/RTkxW8Yt5KkWDTNFQac17
|
||||
7oSymAJCAROy25Xz7ScbLRbh2CquVzelxmxQtrWZmr2C6hNOG8vZat4qOigwmz/1
|
||||
ZRn2bQL5Gh0J21ohAXpzWgpLlXp1O4Bf
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,7 +0,0 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIHcAgEBBEIB61IsG6+MaMabtPWlbajOeOFQHcYyRjgenJqZdHvPt4VW9COQZGai
|
||||
NkHmp3iifcXWDegv1vY4fFmCmc9zlbbZU7qgBwYFK4EEACOhgYkDgYYABAAu5HAW
|
||||
ZpjZxfu6jQ+61F5CysJzWgkc4MIB4z8kW9w0x76vUGlWPX+yw0q5EzpeEGjWV82Y
|
||||
DRoEfkDRfAjk8/B/8wDNJ7oH9pepkq3DroH0v3R34C8oQwbsw/Rx9JwOECR3u2jI
|
||||
gzNLtiEfiEBgucZ5MgDEgNJdB03qCvaqUmYXN7Lwog==
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -1,24 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Public test certificates only; uses the existing public RSA client key.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
openssl_bin=${OPENSSL_BIN:-openssl}
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -rf "$scratch"' EXIT
|
||||
"$openssl_bin" req -x509 -newkey rsa:2048 -noenc -sha256 -days 3650 \
|
||||
-subj '/CN=PSS Chain Root' -addext 'basicConstraints=critical,CA:TRUE' \
|
||||
-keyout "$scratch/root.key" -out pss-chain-root.pem
|
||||
"$openssl_bin" req -new -newkey rsa:2048 -noenc -subj '/CN=PSS Issuing CA' \
|
||||
-keyout "$scratch/issuer.key" -out "$scratch/issuer.csr"
|
||||
printf 'basicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign\n' > "$scratch/ca.ext"
|
||||
"$openssl_bin" x509 -req -in "$scratch/issuer.csr" -CA pss-chain-root.pem \
|
||||
-CAkey "$scratch/root.key" -set_serial 2 -days 3650 -sha256 \
|
||||
-extfile "$scratch/ca.ext" -out pss-chain-issuer.pem
|
||||
"$openssl_bin" req -new -key rsa-pkcs8.pem -subj '/CN=PSS Signed Client' -out "$scratch/client.csr"
|
||||
printf 'basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\n' > "$scratch/client.ext"
|
||||
for salt_length in 20 32 48; do
|
||||
"$openssl_bin" x509 -req -in "$scratch/client.csr" -CA pss-chain-issuer.pem \
|
||||
-CAkey "$scratch/issuer.key" -set_serial "$salt_length" -days 3650 -sha256 \
|
||||
-sigopt rsa_padding_mode:pss -sigopt "rsa_pss_saltlen:$salt_length" \
|
||||
-extfile "$scratch/client.ext" -out "pss-chain-salt-$salt_length.pem"
|
||||
done
|
||||
@@ -17,19 +17,6 @@ for algorithm in rsa ec; do
|
||||
"$openssl_bin" x509 -req -in "$scratch/$algorithm.csr" -CA root.pem -CAkey "$scratch/root.key" \
|
||||
-set_serial 10 -days 3650 -sha256 -out "$algorithm-cert.pem"
|
||||
done
|
||||
# Issue #697: the local identity must allow a server-specific critical extension.
|
||||
"$openssl_bin" req -new -x509 -key rsa-pkcs8.pem -sha256 -days 3650 \
|
||||
-subj '/CN=GP Critical Extension Regression' \
|
||||
-addext '1.3.6.1.4.1.55555.1=critical,DER:05:00' -out rsa-critical-extension.pem
|
||||
# Compatibility and unsupported-input fixtures use the same public test keys.
|
||||
"$openssl_bin" ec -in ec-pkcs8.pem -conv_form compressed -out ec-compressed.pem
|
||||
"$openssl_bin" ec -in ec-pkcs8.pem -param_enc explicit -out ec-explicit.pem
|
||||
"$openssl_bin" ecparam -name secp521r1 -genkey -noout -out ec-p521.pem
|
||||
"$openssl_bin" genpkey -algorithm RSA-PSS -pkeyopt rsa_keygen_bits:2048 -out rsa-pss.pem
|
||||
for variant in ec-compressed ec-explicit ec-p521 rsa-pss; do
|
||||
"$openssl_bin" req -new -x509 -key "$variant.pem" -sha256 -days 3650 \
|
||||
-subj "/CN=GP Public $variant Regression" -out "$variant-cert.pem"
|
||||
done
|
||||
"$openssl_bin" rsa -in rsa-pkcs8.pem -traditional -out rsa-pkcs1.pem
|
||||
"$openssl_bin" ec -in ec-pkcs8.pem -out ec-sec1.pem
|
||||
for cipher in aes128 aes192 aes256 des3; do
|
||||
@@ -83,14 +70,6 @@ done
|
||||
"$openssl_bin" pkcs8 -provider default -provider legacy -topk8 -in rsa-pkcs8.pem \
|
||||
-v2 des-cbc -v2prf hmacWithSHA256 -passout pass:fixture-password -out rsa-pbes2-des.pem
|
||||
|
||||
# RC4-128 was usable with the former OpenSSL legacy provider and OpenConnect.
|
||||
# RC2-128 and two-key 3DES deliberately exercise unsupported-encryption errors.
|
||||
for scheme in RC4-128 RC2-128 2DES; do
|
||||
"$openssl_bin" pkcs12 -export -legacy -inkey rsa-pkcs8.pem -in rsa-cert.pem \
|
||||
-keypbe "PBE-SHA1-$scheme" -certpbe PBE-SHA1-3DES \
|
||||
-passout pass:fixture-password -out "legacy-$scheme.p12"
|
||||
done
|
||||
|
||||
# Incomplete identity archives exercise validation before native TLS import.
|
||||
"$openssl_bin" pkcs12 -export -nokeys -in rsa-cert.pem \
|
||||
-name fixture -passout pass:fixture-password -out certificate-only.pfx
|
||||
@@ -99,4 +78,3 @@ done
|
||||
|
||||
# Plain PKCS#12 bags let the import tests omit optional IDs and reorder bags.
|
||||
python3 "$(dirname "$0")/generate-plain-pfx.py"
|
||||
bash "$(dirname "$0")/generate-pss-chain.sh"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,19 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDEDCCAfigAwIBAgIBAjANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDDA5QU1Mg
|
||||
Q2hhaW4gUm9vdDAeFw0yNjExMDcwNTIxNTJaFw0zNjExMDQwNTIxNTJaMBkxFzAV
|
||||
BgNVBAMMDlBTUyBJc3N1aW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
|
||||
CgKCAQEAkjFaot6TCYfvnmfxSGfpqd2X+633FdjuaJLFf+G/EAccA7SVwtyGAJuT
|
||||
/+RE3q0JO9I502mPRIWxkKOH0KU1dQK92iIup2lhc4WOtaGFvk+KGu3UrIQhgK8N
|
||||
h0bEkiPcO160M3MEBo3mZGC933n/q+ean1nHcxrh3vp6t4fAUmH8B46+ww2QgUR0
|
||||
nJorVh/gAmrzRmgRfRy3FKHRh9sZLrguJqlNOe8g3x/brmFV2dd4vl1iX84+Xxs3
|
||||
9WfyrYGH0Sy3HAUv7ur5z8j9eiPTdy3UvGpDoz815WKCJNkdTvbMlDJVu0+NokLa
|
||||
7q3z0CidYwVGqHlzKl6yXPp4J/ZbVwIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/
|
||||
MA4GA1UdDwEB/wQEAwICBDAdBgNVHQ4EFgQUjMoHVKzTYMWxwGZvjWzCuv2roqYw
|
||||
HwYDVR0jBBgwFoAUK0dvk5jU2/lvSQ4u3d0VdEQ1bTwwDQYJKoZIhvcNAQELBQAD
|
||||
ggEBABr/bCjbrX3JrF8S30glfEPOwXuYsJRCWuHn4+p89x0nwEU7+DpChepRwG6n
|
||||
rhsFRUz2ADrpJyw+4DaEHquGpEGirRx9QLEV9rDXAAyHK7/k1yy25pfj/CttzjXn
|
||||
M6WEZPR5jRcNNBH+B7Lb55uvGQHiuZg7abuNz+lE8iUwXOsfsbXqAU7RoWpvb59f
|
||||
jrDh925YPvKRIMGPqZjA9l5KzPxmBxyWZlSyTwRlZPVcAJXPRusfuCVko6kXcEJ1
|
||||
U86g8VjR03EknNSxYifXjbAlFGh2NBeJ1BeS12yTe9zlyZ1hijwC0jTlzF9fzI/K
|
||||
YgwNW6V0W51+Rn2L8EyHtl0IbyU=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,19 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDEzCCAfugAwIBAgIUbtOYPmJw0zjzONdDDXnD4PWLy+8wDQYJKoZIhvcNAQEL
|
||||
BQAwGTEXMBUGA1UEAwwOUFNTIENoYWluIFJvb3QwHhcNMjYxMTA3MDUyMTUxWhcN
|
||||
MzYxMTA0MDUyMTUxWjAZMRcwFQYDVQQDDA5QU1MgQ2hhaW4gUm9vdDCCASIwDQYJ
|
||||
KoZIhvcNAQEBBQADggEPADCCAQoCggEBANnZ/+l/MSDO3IlW57rCGg8WOSOQ1Kmy
|
||||
2QoMUGCSNNrYsfmriY0BkcyX4LHyvH2FqZUE4h6IfVnY1qEaKRQYw6Rljy9unGkW
|
||||
Z7a5c6N88KbZ3GgFUkn/BpFbf1FAd7AVfXwOrbUtpw43nxLmN6nXr3iYTme0aOuH
|
||||
rNTnxBUq7WEMKyZNwtuKJoYBllqNr6Pth+KVtFNvXyQfqOetTi1upwObsZYVewnU
|
||||
Hv5+XM9ZQ9S2pC8816B9DGm+ys0+f+mn+W9f6C+ffHhjV+aUMfgBFOIB9sl1oZNO
|
||||
td+WX5yT96/b7OTwOwP/Q6eKvK+QMDEbi2K2ULMqknlUfOfeLvKPCUECAwEAAaNT
|
||||
MFEwHQYDVR0OBBYEFCtHb5OY1Nv5b0kOLt3dFXRENW08MB8GA1UdIwQYMBaAFCtH
|
||||
b5OY1Nv5b0kOLt3dFXRENW08MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
|
||||
BQADggEBALrN2Eu94nDxpbSp1AfYPVr5/9yUOMfA/NjUB3OZ4q5fyPoAiTmOFZ7C
|
||||
hIdnXfMZq6tKKUf1qO86HreiyHF4+JIewBPkR43uTRxRuuV37R9igbXDmYtvmUK0
|
||||
+8zgj4Y6IhXO7wqr6llIgK3LF9dkg7K1NhqvgWaGXB10YrjU5Ae1rVToN+9Yre8a
|
||||
4PsbaWGQR+kchcYd1WlJJO4afBf7ecGDujwBc0k/bHX8eFmhQ94ZIh/KyONsEI3C
|
||||
mmgEDeFCdWPCG+736IkrYA8SAAFqVMMQCvHDMpROUzbHFOQQIKKOUy0ErLKpwEYo
|
||||
4Xn5o6uX/eWZaLv5iOcNACugZ2JwW1g=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,21 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDgzCCAjygAwIBAgIBFDA8BgkqhkiG9w0BAQowL6APMA0GCWCGSAFlAwQCAQUA
|
||||
oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAMBkxFzAVBgNVBAMMDlBTUyBJ
|
||||
c3N1aW5nIENBMB4XDTI2MTEwNzA1MjE1MloXDTM2MTEwNDA1MjE1MlowHDEaMBgG
|
||||
A1UEAwwRUFNTIFNpZ25lZCBDbGllbnQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
|
||||
ggEKAoIBAQDd1Qd/iKhTpVWOjhfwPTqlaj9Ac6CKubFr0fZsVgR8r1OSmRv16e2t
|
||||
jhfjjhOI0cz3S4Cqt9ZPLWIMGMugt9Y1YFHpg8gTsLrnYgRHBtA2eoBhLROLsj5x
|
||||
aiUBoAYPR1vLmPyHtPuvveRepaY59AEarptx6//jf6LJQAjxTNbiU5FQsGr4ixVG
|
||||
I29zsesFE0VbVSxKYdiMN+duVX7iPQSkMODWedcBEqQo17xAdvPgjtpN1AfXoDHW
|
||||
ns/kpfOb2z9W1o3GG89XxA1s/IBivmIb6Dy+p7CzhCFxHmOd8Wlt8/U5W9wkphHm
|
||||
HWbsF79XEBqyIoUx6Vo1kNsCezCSf9aHAgMBAAGjdTBzMAwGA1UdEwEB/wQCMAAw
|
||||
DgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMCMB0GA1UdDgQWBBQ/
|
||||
cTzIdpR+vdaP5Z9fBxp5isXZMDAfBgNVHSMEGDAWgBSMygdUrNNgxbHAZm+NbMK6
|
||||
/auipjA8BgkqhkiG9w0BAQowL6APMA0GCWCGSAFlAwQCAQUAoRwwGgYJKoZIhvcN
|
||||
AQEIMA0GCWCGSAFlAwQCAQUAA4IBAQAUOI4kd5ZvRevSo5kt6xoJBYmRw2jVwcqG
|
||||
rVoq21h1L3cqhqYSb9oCyGcrkWcUfXY5uPAemF9wyScbLgwyGudX6ngVdHWwRVvN
|
||||
dBZLRLDsviRAjN60NP06vrV/JzcQfFOL2L0tjGfYCfXdYD+0WZG8R1qtb2fHPh89
|
||||
II7O3dof2eR/GOot/JX6te7vYc3faWyNTC8SclB9tJrwAz8++tf0cuStHoLWd9jV
|
||||
Gq3mhKn1ZzdJsbwTQjledIXLG6eRE6XyLHzcB6VctAt6bhVLxH8Ck/oEfGwYY2wK
|
||||
tkwyNCnl35CCBRdbKxXfUJavoq8jwETZmSVnRUfWn2HUB6FDmtGm
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,22 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDjTCCAkGgAwIBAgIBIDBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
|
||||
oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwGTEXMBUGA1UEAwwO
|
||||
UFNTIElzc3VpbmcgQ0EwHhcNMjYxMTA3MDUyMTUyWhcNMzYxMTA0MDUyMTUyWjAc
|
||||
MRowGAYDVQQDDBFQU1MgU2lnbmVkIENsaWVudDCCASIwDQYJKoZIhvcNAQEBBQAD
|
||||
ggEPADCCAQoCggEBAN3VB3+IqFOlVY6OF/A9OqVqP0BzoIq5sWvR9mxWBHyvU5KZ
|
||||
G/Xp7a2OF+OOE4jRzPdLgKq31k8tYgwYy6C31jVgUemDyBOwuudiBEcG0DZ6gGEt
|
||||
E4uyPnFqJQGgBg9HW8uY/Ie0+6+95F6lpjn0ARqum3Hr/+N/oslACPFM1uJTkVCw
|
||||
aviLFUYjb3Ox6wUTRVtVLEph2Iw3525VfuI9BKQw4NZ51wESpCjXvEB28+CO2k3U
|
||||
B9egMdaez+Sl85vbP1bWjcYbz1fEDWz8gGK+YhvoPL6nsLOEIXEeY53xaW3z9Tlb
|
||||
3CSmEeYdZuwXv1cQGrIihTHpWjWQ2wJ7MJJ/1ocCAwEAAaN1MHMwDAYDVR0TAQH/
|
||||
BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0O
|
||||
BBYEFD9xPMh2lH691o/ln18HGnmKxdkwMB8GA1UdIwQYMBaAFIzKB1Ss02DFscBm
|
||||
b41swrr9q6KmMEEGCSqGSIb3DQEBCjA0oA8wDQYJYIZIAWUDBAIBBQChHDAaBgkq
|
||||
hkiG9w0BAQgwDQYJYIZIAWUDBAIBBQCiAwIBIAOCAQEAHduUqnc8vvfsg8PrIRxD
|
||||
qOWW0wx6BdRSd23cx1V7OaT7JMU6gvWSiiFx+aOl+REPQNNxi9yTAUDL0vPewwa9
|
||||
UZSNUy0tYVXuhZ4QfoPMZNRV2d1JekoHXgWLk39JgD363TL504MEhDoeXtIAbj/d
|
||||
Ta+7aHGH6xMhwldUWMqiUkBpC4TUOsshZm92197/SRl9joTWB5G3RSREirG8LEn4
|
||||
HiTgd2AbiPXzAzA5MdIOeGWMKSF+Ey3R6Z2HzOzIrqAd3pFVPI6oHMSN6WzfHLVW
|
||||
GT8LM+eQyUXTQn7B67REH+/GsolCHBUEMjyABUtZoNIxa3KOXE7GN7SQDV93UPhT
|
||||
CQ==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,22 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDjTCCAkGgAwIBAgIBMDBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
|
||||
oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCATAwGTEXMBUGA1UEAwwO
|
||||
UFNTIElzc3VpbmcgQ0EwHhcNMjYxMTA3MDUyMTUyWhcNMzYxMTA0MDUyMTUyWjAc
|
||||
MRowGAYDVQQDDBFQU1MgU2lnbmVkIENsaWVudDCCASIwDQYJKoZIhvcNAQEBBQAD
|
||||
ggEPADCCAQoCggEBAN3VB3+IqFOlVY6OF/A9OqVqP0BzoIq5sWvR9mxWBHyvU5KZ
|
||||
G/Xp7a2OF+OOE4jRzPdLgKq31k8tYgwYy6C31jVgUemDyBOwuudiBEcG0DZ6gGEt
|
||||
E4uyPnFqJQGgBg9HW8uY/Ie0+6+95F6lpjn0ARqum3Hr/+N/oslACPFM1uJTkVCw
|
||||
aviLFUYjb3Ox6wUTRVtVLEph2Iw3525VfuI9BKQw4NZ51wESpCjXvEB28+CO2k3U
|
||||
B9egMdaez+Sl85vbP1bWjcYbz1fEDWz8gGK+YhvoPL6nsLOEIXEeY53xaW3z9Tlb
|
||||
3CSmEeYdZuwXv1cQGrIihTHpWjWQ2wJ7MJJ/1ocCAwEAAaN1MHMwDAYDVR0TAQH/
|
||||
BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0O
|
||||
BBYEFD9xPMh2lH691o/ln18HGnmKxdkwMB8GA1UdIwQYMBaAFIzKB1Ss02DFscBm
|
||||
b41swrr9q6KmMEEGCSqGSIb3DQEBCjA0oA8wDQYJYIZIAWUDBAIBBQChHDAaBgkq
|
||||
hkiG9w0BAQgwDQYJYIZIAWUDBAIBBQCiAwIBMAOCAQEAfRbXy5n1jSsOiKKGppzq
|
||||
iRhrCJf51Le9aaf5cot/l1Q8GTFdYi8Ieu4CghsmGvfJIuRyig/aFfqXxpcFldDq
|
||||
Nm4uIKRyDwygLyDau+OUaNmz1UZ2Y6FzOfyb6ujy2pEhOXr1EnQnL82MvlvbN4DT
|
||||
9Dx4FgXAydtM6P6QfALvAEVy8/wjAYVCK5Xv/vKR5fFc2Rgl3DZkopcPF2pNQFN4
|
||||
E0P7GWxE+elRG952lacqHyhL4sIMoHF6AvDFUVwWoqttIfjX1272vt2yN1ej9F94
|
||||
BWyVm+sYf0fg767lsW2yFQS/1LbldjkHmxQn3qkrPhPni1zWhC5MJ6DxFLXGxkIr
|
||||
kw==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,20 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDSzCCAjOgAwIBAgIUColgV9GBymAbAEDYl4N4hI5i+icwDQYJKoZIhvcNAQEL
|
||||
BQAwKzEpMCcGA1UEAwwgR1AgQ3JpdGljYWwgRXh0ZW5zaW9uIFJlZ3Jlc3Npb24w
|
||||
HhcNMjYxMTA3MDA0ODI3WhcNMzYxMTA0MDA0ODI3WjArMSkwJwYDVQQDDCBHUCBD
|
||||
cml0aWNhbCBFeHRlbnNpb24gUmVncmVzc2lvbjCCASIwDQYJKoZIhvcNAQEBBQAD
|
||||
ggEPADCCAQoCggEBAN3VB3+IqFOlVY6OF/A9OqVqP0BzoIq5sWvR9mxWBHyvU5KZ
|
||||
G/Xp7a2OF+OOE4jRzPdLgKq31k8tYgwYy6C31jVgUemDyBOwuudiBEcG0DZ6gGEt
|
||||
E4uyPnFqJQGgBg9HW8uY/Ie0+6+95F6lpjn0ARqum3Hr/+N/oslACPFM1uJTkVCw
|
||||
aviLFUYjb3Ox6wUTRVtVLEph2Iw3525VfuI9BKQw4NZ51wESpCjXvEB28+CO2k3U
|
||||
B9egMdaez+Sl85vbP1bWjcYbz1fEDWz8gGK+YhvoPL6nsLOEIXEeY53xaW3z9Tlb
|
||||
3CSmEeYdZuwXv1cQGrIihTHpWjWQ2wJ7MJJ/1ocCAwEAAaNnMGUwHQYDVR0OBBYE
|
||||
FD9xPMh2lH691o/ln18HGnmKxdkwMB8GA1UdIwQYMBaAFD9xPMh2lH691o/ln18H
|
||||
GnmKxdkwMA8GA1UdEwEB/wQFMAMBAf8wEgYJKwYBBAGDsgMBAQH/BAIFADANBgkq
|
||||
hkiG9w0BAQsFAAOCAQEANDajhAeLynPhIpjeh0FJf2lwTVap0yA903pGeOziuvdc
|
||||
R3eTX6DF9lXyNsfdiIR9BL+oL0fhOh8LG85dqCANIKCkKqelcI6FBUjTbZziDXxi
|
||||
Xxc68XHfNs+f8Z+LLTuBo7k8vPuOxPLxTmERi5+O2dLUINAjZrQML+uzAmK3KlfZ
|
||||
Ge6qWNE6k35+ZQGQwor+VHwmwJjKLHaPaZHAwhQWJer/dDcadkxLGGJ4DDt95awL
|
||||
ggpS/04jM5tUxlysCQqrTHxFIiiALFPy7+Md4DRLv+oinIpcRrT2SECVWCW583JI
|
||||
gWAPCoAvOOT7qMWYuba6OUidaeR7T6sgIQtZ4x9Fnw==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,22 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDjTCCAkGgAwIBAgIUZbovjhUmkSfk/CWcoqSraiFxygUwQQYJKoZIhvcNAQEK
|
||||
MDSgDzANBglghkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEF
|
||||
AKIDAgEgMCMxITAfBgNVBAMMGEdQIFB1YmxpYyBwc3MgUmVncmVzc2lvbjAeFw0y
|
||||
NjExMDcwMjA2MjZaFw0zNjExMDQwMjA2MjZaMCMxITAfBgNVBAMMGEdQIFB1Ymxp
|
||||
YyBwc3MgUmVncmVzc2lvbjCCASAwCwYJKoZIhvcNAQEKA4IBDwAwggEKAoIBAQDr
|
||||
NsIJvoquN4qj9OIcsw8Pu/jjZMUPFGXQeejNRh1oIA+Lo0aps9IgQm2iIHlrusdO
|
||||
3DbXriMvrUXEmrp10FC7JCe34oY1SahpY4/EU5acQrcANwszkN+wRxGHNmZ4jYGQ
|
||||
tRZGyQIDiejvztBAWsCjSp/VfqyfCoECe21/6cKl1qZRJSPgnXlZJrYfvJeyKMoa
|
||||
/GYyE1oFQRvNN56TRkT4Z4ys5kN3tl7S4GI13LohIzlej3pQeAiU+4+addJ71c29
|
||||
3UDfZfqu2p+qpcZ9y5k1dhVn/XAuiX4avQ40UYxtYMTo10h6oyU64GBfcJ05ljbb
|
||||
UaX4XcC0udKPcWmH/Y2/AgMBAAGjUzBRMB0GA1UdDgQWBBSG4neJk61a5OKpTJwv
|
||||
xTfMYWhzRTAfBgNVHSMEGDAWgBSG4neJk61a5OKpTJwvxTfMYWhzRTAPBgNVHRMB
|
||||
Af8EBTADAQH/MEEGCSqGSIb3DQEBCjA0oA8wDQYJYIZIAWUDBAIBBQChHDAaBgkq
|
||||
hkiG9w0BAQgwDQYJYIZIAWUDBAIBBQCiAwIBIAOCAQEArry92CksVDObs8ekbHPQ
|
||||
tz5BF8s7yI729Dy35oH/zFT/vWOtP9vMYRF83x+g5ZzNMjdBZDm2lzVLlHOjClbp
|
||||
RKxMthR+Dy8jGu2+5f+GwaOWWvIlTGJB0qssH5pKWvt5PU1f2KGuPAp4aU+1VxwA
|
||||
DJXbQn5ssQxS/L/9WsQGOzvDMuMkWKxIZ+Z1YsAvBNlhYlS8OMdfDVGl5MobomVl
|
||||
WU5kwNZlIDoBk3J9EXXa40xbUULCCq3bEEfIu5Mo6VgzyE8Y/EAPjI2q23wH2Map
|
||||
ReT5yhKyqX6BXfUGaN9jNv/t7j6h+gXEXx5WYXb5OX557csMWRCBiHjAQUoIh3FB
|
||||
7Q==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,28 +0,0 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEuwIBADALBgkqhkiG9w0BAQoEggSnMIIEowIBAAKCAQEA6zbCCb6KrjeKo/Ti
|
||||
HLMPD7v442TFDxRl0HnozUYdaCAPi6NGqbPSIEJtoiB5a7rHTtw2164jL61FxJq6
|
||||
ddBQuyQnt+KGNUmoaWOPxFOWnEK3ADcLM5DfsEcRhzZmeI2BkLUWRskCA4no787Q
|
||||
QFrAo0qf1X6snwqBAnttf+nCpdamUSUj4J15WSa2H7yXsijKGvxmMhNaBUEbzTee
|
||||
k0ZE+GeMrOZDd7Ze0uBiNdy6ISM5Xo96UHgIlPuPmnXSe9XNvd1A32X6rtqfqqXG
|
||||
fcuZNXYVZ/1wLol+Gr0ONFGMbWDE6NdIeqMlOuBgX3CdOZY221Gl+F3AtLnSj3Fp
|
||||
h/2NvwIDAQABAoIBACQNGFrU/RLXHs/4HytQmIeMAzRF2Ybw/z/1B3plpj6I4h5q
|
||||
xVBfvYjwlYwqwmGBgb3eYSYtTGWo1E+I0E5xbNuaHt+qKnGCxiYiZUKCoKF3qkPa
|
||||
q+6t5FMeOXC0z6o833XLWPbleoJfV2K2G1OEdWUxxri6zytwjoslBDNS+WC1xTj/
|
||||
3IOj0hQwwTToiLkqrcyG1ymCj9RR+3CJ30/QVSmj9Gg+1/9Cws3/mc3en2hjVhSw
|
||||
AwCEZUD2c+Uvc+DnfOtJNeJaDrwgmuZNNPUw/SEkTtsUY6SMbY5tgrkHzNhXl5Af
|
||||
aqSznvhwykxvgw/PIowgZMA1pGynicX2ajYq+KECgYEA+5OfLmT4e1tXqTgiv7Ea
|
||||
pOmPR2AaAsryZNpSf5CbmmxgVrNvLtmy5PNV7QvRtsIvmoCPHZkyHmLGPIIIMu8L
|
||||
G2yyFyZWSCVVieanRrxJrRZlssbHRRcu9r9LFNi1S7SgkMKknaiWQIbQFVMx/rZQ
|
||||
VTiPGu+sicoPefeCuvOtOKECgYEA71l8QLRApjOHShiWPzZFn9aD23txtsbcpHD+
|
||||
pzW/yB+19gnUQA4VtIfQFvlUMmeRbu2LnIXhTqXEo4Zfkgq7o5ROtyrK/FOQ/qKr
|
||||
N8C112O9vUS0ccpN31VaN66jWGPa61+a5awtEr78c153Z94Pl4iYmMFhshK79E2G
|
||||
tEX3Sl8CgYBea6Bh1EmiWr0C6Ou50Gm0nWhGHJ6Gj8775Sjzcb3E7ooV4FCJX/GR
|
||||
lnaYekgidK1TKo8MR9QUrXPDf/Y9z5P2ngwVPjFB8KkzEZuUo9RvHynaOFrP5oyc
|
||||
1V0DnPYmTMu6qSMJfR2vaCmu50OrWpe59HlZXbz/FhRK7YdmTVClIQKBgCjFuaDc
|
||||
E9c8F+PLZGzINfwQcs3ErY5ROezZQsgBI/ZXUIvlCL8QpynlqNEBEBK2CdQ3qvyy
|
||||
4bqgCmtAzK74HRa0gOQ66fEp2x1FYJ1SuqdCWmQPfB2WNMXCqGer3C+Gcxh9ZMmT
|
||||
FuqGlkKg6P5MmaNapYQADUBkaJgpTLUQ5htJAoGBAMpA9RbcSNPMe+POUxGb6pk3
|
||||
mSV4ymmotWtyr0GqNa/FgujjZ68TWwvhrJFD0kQap3flM3/82ThJCk9HsJ9osjPM
|
||||
mNEHccfgASpPVgpkvLUjtITUb7aO1cdjHK1gFknNQSy/jZyMClfhnwvXiqqgWqme
|
||||
f9Ih4LSOdrek2teuI5Mo
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -1,280 +0,0 @@
|
||||
/* Exercise the normal OpenConnect setter and GlobalProtect HTTPS path. The peer
|
||||
* verifies client TLS authentication, then returns 503: no VPN is configured. */
|
||||
#include <config.h>
|
||||
#include "openconnect-internal.h"
|
||||
#include <gnutls/gnutls.h>
|
||||
#include <gnutls/pkcs12.h>
|
||||
#include <assert.h>
|
||||
#include <limits.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <time.h>
|
||||
|
||||
#define PRIVATE_EXTENSION "1.3.6.1.4.1.55555.1"
|
||||
#define PASSWORD "fixture-password"
|
||||
|
||||
struct peer {
|
||||
int listener, tls13, verified;
|
||||
gnutls_certificate_credentials_t credentials;
|
||||
gnutls_datum_t expected;
|
||||
};
|
||||
|
||||
static void path(char *output, const char *directory, const char *name)
|
||||
{
|
||||
assert(snprintf(output, PATH_MAX, "%s/%s", directory, name) < PATH_MAX);
|
||||
}
|
||||
|
||||
static gnutls_datum_t read_file(const char *filename)
|
||||
{
|
||||
gnutls_datum_t data;
|
||||
FILE *file = fopen(filename, "rb");
|
||||
long length;
|
||||
assert(file);
|
||||
assert(!fseek(file, 0, SEEK_END));
|
||||
length = ftell(file);
|
||||
assert(length > 0 && length <= UINT_MAX);
|
||||
assert(!fseek(file, 0, SEEK_SET));
|
||||
data.size = length;
|
||||
data.data = malloc(data.size);
|
||||
assert(data.data && fread(data.data, 1, data.size, file) == data.size);
|
||||
assert(!fclose(file));
|
||||
return data;
|
||||
}
|
||||
|
||||
static gnutls_x509_crt_t read_certificate(const char *filename)
|
||||
{
|
||||
gnutls_x509_crt_t certificate;
|
||||
gnutls_datum_t data = read_file(filename);
|
||||
assert(!gnutls_x509_crt_init(&certificate));
|
||||
assert(!gnutls_x509_crt_import(certificate, &data, GNUTLS_X509_FMT_PEM));
|
||||
free(data.data);
|
||||
return certificate;
|
||||
}
|
||||
|
||||
static void progress(void *data, int level, const char *format, ...)
|
||||
{
|
||||
va_list arguments;
|
||||
if (level > PRG_DEBUG) return;
|
||||
va_start(arguments, format);
|
||||
vfprintf(stderr, format, arguments);
|
||||
va_end(arguments);
|
||||
}
|
||||
|
||||
static int reject_untrusted_server(void *data, const char *reason)
|
||||
{
|
||||
fprintf(stderr, "Unexpected server verification failure: %s\n", reason);
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
static int cancel_password_prompt(void *data, struct oc_auth_form *form)
|
||||
{
|
||||
/* A missing/wrong fixture password must fail, never block on input. */
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int verify_client(gnutls_session_t session)
|
||||
{
|
||||
struct peer *peer = gnutls_session_get_ptr(session);
|
||||
unsigned int count, status;
|
||||
const gnutls_datum_t *certificates = gnutls_certificate_get_peers(session, &count);
|
||||
assert(certificates && count > 0);
|
||||
assert(certificates[0].size == peer->expected.size);
|
||||
assert(!memcmp(certificates[0].data, peer->expected.data, peer->expected.size));
|
||||
assert(!gnutls_certificate_verify_peers2(session, &status));
|
||||
assert(!status);
|
||||
peer->verified = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void *serve(void *data)
|
||||
{
|
||||
struct peer *peer = data;
|
||||
gnutls_session_t session;
|
||||
fd_set reads;
|
||||
struct timeval wait = { .tv_sec = 8 };
|
||||
struct timeval timeout = { .tv_sec = 5 };
|
||||
char request[8192];
|
||||
static const char response[] =
|
||||
"HTTP/1.1 503 TLS fixture complete\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
int fd;
|
||||
FD_ZERO(&reads);
|
||||
FD_SET(peer->listener, &reads);
|
||||
assert(select(peer->listener + 1, &reads, NULL, NULL, &wait) == 1);
|
||||
fd = accept(peer->listener, NULL, NULL);
|
||||
assert(fd >= 0);
|
||||
assert(!setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)));
|
||||
assert(!setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)));
|
||||
assert(!gnutls_init(&session, GNUTLS_SERVER));
|
||||
assert(!gnutls_priority_set_direct(session, peer->tls13
|
||||
? "NORMAL:-VERS-ALL:+VERS-TLS1.3" : "NORMAL:-VERS-ALL:+VERS-TLS1.2", NULL));
|
||||
assert(!gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, peer->credentials));
|
||||
gnutls_certificate_server_set_request(session, GNUTLS_CERT_REQUIRE);
|
||||
gnutls_session_set_ptr(session, peer);
|
||||
gnutls_transport_set_int(session, fd);
|
||||
gnutls_handshake_set_timeout(session, 5000);
|
||||
/* A successful handshake also verifies CertificateVerify proof of possession. */
|
||||
assert(!gnutls_handshake(session));
|
||||
assert(peer->verified);
|
||||
assert(gnutls_protocol_get_version(session) == (peer->tls13 ? GNUTLS_TLS1_3 : GNUTLS_TLS1_2));
|
||||
assert(gnutls_record_recv(session, request, sizeof(request)) > 0);
|
||||
assert(gnutls_record_send(session, response, sizeof(response) - 1) == sizeof(response) - 1);
|
||||
gnutls_deinit(session);
|
||||
close(fd);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void check(const char *name, const char *server_cert, const char *server_key,
|
||||
const char *server_ca, const char *client_ca, const char *certificate,
|
||||
const char *key, const char *password, gnutls_x509_crt_t expected,
|
||||
int private_extension, int tls13)
|
||||
{
|
||||
struct peer peer = { .tls13 = tls13 };
|
||||
struct sockaddr_in address = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
|
||||
socklen_t address_length = sizeof(address);
|
||||
struct openconnect_info *client;
|
||||
pthread_t thread;
|
||||
char url[128];
|
||||
int result;
|
||||
assert(!gnutls_certificate_allocate_credentials(&peer.credentials));
|
||||
assert(!gnutls_certificate_set_x509_key_file(peer.credentials, server_cert, server_key, GNUTLS_X509_FMT_PEM));
|
||||
assert(gnutls_certificate_set_x509_trust_file(peer.credentials, client_ca, GNUTLS_X509_FMT_PEM) > 0);
|
||||
assert(gnutls_certificate_set_x509_trust(peer.credentials, &expected, 1) > 0);
|
||||
assert(!gnutls_x509_crt_export2(expected, GNUTLS_X509_FMT_DER, &peer.expected));
|
||||
if (private_extension) {
|
||||
unsigned critical = 0;
|
||||
unsigned char value[2];
|
||||
size_t length = sizeof(value);
|
||||
assert(!gnutls_x509_crt_get_extension_by_oid(expected, PRIVATE_EXTENSION, 0,
|
||||
value, &length, &critical));
|
||||
assert(critical && length == 2 && value[0] == 5 && value[1] == 0);
|
||||
/* The exact-DER pin in verify_client limits this exception to the known
|
||||
* fixture extension. Chain trust and handshake signatures stay checked. */
|
||||
gnutls_certificate_set_verify_flags(peer.credentials, GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS);
|
||||
}
|
||||
gnutls_certificate_set_verify_function(peer.credentials, verify_client);
|
||||
peer.listener = socket(AF_INET, SOCK_STREAM, 0);
|
||||
assert(peer.listener >= 0);
|
||||
assert(!bind(peer.listener, (struct sockaddr *)&address, sizeof(address)));
|
||||
assert(!getsockname(peer.listener, (struct sockaddr *)&address, &address_length));
|
||||
assert(!listen(peer.listener, 1));
|
||||
assert(!pthread_create(&thread, NULL, serve, &peer));
|
||||
client = openconnect_vpninfo_new("Client identity regression", reject_untrusted_server,
|
||||
NULL, cancel_password_prompt, progress, NULL);
|
||||
assert(client);
|
||||
snprintf(url, sizeof(url), "https://localhost:%u/", ntohs(address.sin_port));
|
||||
assert(!openconnect_parse_url(client, url));
|
||||
assert(!openconnect_set_protocol(client, "gp"));
|
||||
assert(!openconnect_set_cafile(client, server_ca));
|
||||
assert(!openconnect_set_client_cert(client, certificate, key));
|
||||
if (password) assert(!openconnect_set_key_password(client, password));
|
||||
assert(!openconnect_set_cookie(client, "user=fixture&authcookie=fixture"));
|
||||
result = openconnect_make_cstp_connection(client);
|
||||
assert(result < 0); /* The fixture ends after TLS, without GP configuration. */
|
||||
openconnect_vpninfo_free(client);
|
||||
assert(!pthread_join(thread, NULL));
|
||||
assert(peer.verified);
|
||||
close(peer.listener);
|
||||
gnutls_free(peer.expected.data);
|
||||
gnutls_certificate_free_credentials(peer.credentials);
|
||||
printf("%s TLS1.%d: exact client leaf, trusted server and mutual TLS passed\n", name, tls13 ? 3 : 2);
|
||||
}
|
||||
|
||||
static gnutls_x509_crt_t renewed_certificate(gnutls_x509_privkey_t key)
|
||||
{
|
||||
gnutls_x509_crt_t certificate;
|
||||
unsigned char serial[] = { 0x65 };
|
||||
time_t now = time(NULL);
|
||||
assert(!gnutls_x509_crt_init(&certificate));
|
||||
assert(!gnutls_x509_crt_set_version(certificate, 3));
|
||||
assert(!gnutls_x509_crt_set_dn(certificate, "CN=Public renewed identity", NULL));
|
||||
assert(!gnutls_x509_crt_set_issuer_dn(certificate, "CN=Public renewed identity", NULL));
|
||||
assert(!gnutls_x509_crt_set_serial(certificate, serial, sizeof(serial)));
|
||||
assert(!gnutls_x509_crt_set_key(certificate, key));
|
||||
assert(!gnutls_x509_crt_set_activation_time(certificate, now - 3600));
|
||||
assert(!gnutls_x509_crt_set_expiration_time(certificate, now + 86400));
|
||||
assert(!gnutls_x509_crt_set_basic_constraints(certificate, 1, -1));
|
||||
assert(!gnutls_x509_crt_sign2(certificate, certificate, key, GNUTLS_DIG_SHA256, 0));
|
||||
return certificate;
|
||||
}
|
||||
|
||||
static void renewal_archive(const char *filename, gnutls_x509_privkey_t key,
|
||||
gnutls_x509_crt_t older, gnutls_x509_crt_t renewed, gnutls_x509_crt_t root, int reverse)
|
||||
{
|
||||
gnutls_pkcs12_t archive;
|
||||
gnutls_pkcs12_bag_t certificates, keys;
|
||||
gnutls_datum_t output, id = { (unsigned char *)"renewed", 7 };
|
||||
FILE *file;
|
||||
int renewed_index = reverse ? 1 : 0;
|
||||
assert(!gnutls_pkcs12_init(&archive));
|
||||
assert(!gnutls_pkcs12_bag_init(&certificates));
|
||||
assert(gnutls_pkcs12_bag_set_crt(certificates, reverse ? older : renewed) == 0);
|
||||
assert(gnutls_pkcs12_bag_set_crt(certificates, reverse ? renewed : older) == 1);
|
||||
assert(gnutls_pkcs12_bag_set_crt(certificates, root) == 2);
|
||||
/* Keep the bag association on the renewed leaf in both permutations. The
|
||||
* baseline nevertheless selects the first certificate matching the key. */
|
||||
assert(!gnutls_pkcs12_bag_set_key_id(certificates, renewed_index, &id));
|
||||
assert(!gnutls_pkcs12_set_bag(archive, certificates));
|
||||
assert(!gnutls_pkcs12_bag_init(&keys));
|
||||
assert(gnutls_pkcs12_bag_set_privkey(keys, key, NULL, GNUTLS_PKCS_PLAIN) == 0);
|
||||
assert(!gnutls_pkcs12_bag_set_key_id(keys, 0, &id));
|
||||
assert(!gnutls_pkcs12_set_bag(archive, keys));
|
||||
assert(!gnutls_pkcs12_generate_mac2(archive, GNUTLS_MAC_SHA256, PASSWORD));
|
||||
assert(!gnutls_pkcs12_export2(archive, GNUTLS_X509_FMT_DER, &output));
|
||||
file = fopen(filename, "wb");
|
||||
assert(file && fwrite(output.data, 1, output.size, file) == output.size);
|
||||
assert(!fclose(file));
|
||||
gnutls_free(output.data);
|
||||
gnutls_pkcs12_bag_deinit(keys);
|
||||
gnutls_pkcs12_bag_deinit(certificates);
|
||||
gnutls_pkcs12_deinit(archive);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *names[] = { "critical extension", "P-521", "RSA-PSS", "RC4 PKCS12" };
|
||||
const char *certificates[] = { "rsa-critical-extension.pem", "ec-p521-cert.pem", "rsa-pss-cert.pem", "legacy-RC4-128.p12" };
|
||||
const char *keys[] = { "rsa-pkcs8.pem", "ec-p521.pem", "rsa-pss.pem", NULL };
|
||||
char certificate[PATH_MAX], key[PATH_MAX], ca[PATH_MAX], expected_file[PATH_MAX], archive[PATH_MAX];
|
||||
gnutls_x509_privkey_t renewal_key;
|
||||
gnutls_x509_crt_t older, renewed, root;
|
||||
gnutls_datum_t key_data;
|
||||
assert(argc == 6);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
alarm(30);
|
||||
assert(!openconnect_init_ssl());
|
||||
path(ca, argv[1], "root.pem");
|
||||
for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
|
||||
gnutls_x509_crt_t expected;
|
||||
path(certificate, argv[1], certificates[i]);
|
||||
if (keys[i]) path(key, argv[1], keys[i]);
|
||||
path(expected_file, argv[1], i == 3 ? "rsa-cert.pem" : certificates[i]);
|
||||
expected = read_certificate(expected_file);
|
||||
for (int tls13 = 0; tls13 <= 1; tls13++)
|
||||
check(names[i], argv[2], argv[3], argv[4], ca, certificate,
|
||||
keys[i] ? key : NULL, i == 3 ? PASSWORD : NULL, expected, i == 0, tls13);
|
||||
gnutls_x509_crt_deinit(expected);
|
||||
}
|
||||
path(key, argv[1], "rsa-pkcs8.pem");
|
||||
key_data = read_file(key);
|
||||
assert(!gnutls_x509_privkey_init(&renewal_key));
|
||||
assert(!gnutls_x509_privkey_import2(renewal_key, &key_data, GNUTLS_X509_FMT_PEM, NULL, 0));
|
||||
gnutls_memset(key_data.data, 0, key_data.size);
|
||||
free(key_data.data);
|
||||
path(expected_file, argv[1], "rsa-cert.pem");
|
||||
older = read_certificate(expected_file);
|
||||
root = read_certificate(ca);
|
||||
renewed = renewed_certificate(renewal_key);
|
||||
for (int reverse = 0; reverse <= 1; reverse++) {
|
||||
path(archive, argv[5], reverse ? "renewed-reversed.p12" : "renewed-forward.p12");
|
||||
renewal_archive(archive, renewal_key, older, renewed, root, reverse);
|
||||
for (int tls13 = 0; tls13 <= 1; tls13++)
|
||||
check(reverse ? "renewal reversed" : "renewal forward", argv[2], argv[3], argv[4],
|
||||
ca, archive, NULL, PASSWORD, reverse ? older : renewed, 0, tls13);
|
||||
}
|
||||
gnutls_x509_crt_deinit(renewed);
|
||||
gnutls_x509_crt_deinit(older);
|
||||
gnutls_x509_crt_deinit(root);
|
||||
gnutls_x509_privkey_deinit(renewal_key);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
//! Actual OpenConnect credential loading and mutual TLS, without creating a VPN tunnel.
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::process::CommandExt,
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, Command},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
struct ChildGuard(Child);
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe { libc::kill(-(self.0.id() as i32), libc::SIGKILL) };
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn run_bounded(command: &mut Command, log: &Path) {
|
||||
let output = fs::File::create(log).unwrap();
|
||||
let mut child = ChildGuard(
|
||||
command
|
||||
.process_group(0)
|
||||
.stdout(output.try_clone().unwrap())
|
||||
.stderr(output)
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(45);
|
||||
loop {
|
||||
if let Some(status) = child.0.try_wait().unwrap() {
|
||||
assert!(status.success(), "{status}: {}", fs::read_to_string(log).unwrap());
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"Client identity test timed out: {}",
|
||||
fs::read_to_string(log).unwrap()
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identities_complete_openconnect_tls12_and_tls13() {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
|
||||
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let executable = directory.path().join("client-identity");
|
||||
let flags = Command::new("pkg-config")
|
||||
.args(["--cflags", "--libs", "libxml-2.0", "gnutls"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(flags.status.success(), "{}", String::from_utf8_lossy(&flags.stderr));
|
||||
run_bounded(
|
||||
Command::new(build.join("libtool"))
|
||||
.args(["--mode=link", "cc", "-pthread"])
|
||||
.arg(manifest.join("tests/client_identity.c"))
|
||||
.arg("-I")
|
||||
.arg(&build)
|
||||
.arg("-I")
|
||||
.arg(&source)
|
||||
.arg("-I")
|
||||
.arg(source.join("json"))
|
||||
.arg(build.join("libopenconnect.la"))
|
||||
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
|
||||
.arg("-o")
|
||||
.arg(&executable),
|
||||
&directory.path().join("compile.log"),
|
||||
);
|
||||
let server = manifest.join("deps/openconnect/tests/certs");
|
||||
run_bounded(
|
||||
Command::new(build.join("libtool"))
|
||||
.arg("--mode=execute")
|
||||
.arg(executable)
|
||||
.arg(manifest.join("../gpapi/tests/files/client-identity"))
|
||||
.arg(server.join("server-cert.pem"))
|
||||
.arg(server.join("server-key.pem"))
|
||||
.arg(server.join("ca.pem"))
|
||||
.arg(directory.path()),
|
||||
&directory.path().join("runtime.log"),
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ Install build and runtime dependencies:
|
||||
|
||||
```sh
|
||||
sudo pkg install git rust libiconv gettext-tools autoconf automake libtool patch \
|
||||
gmake pkgconf libxml2 gnutls p11-kit nettle gmp liblz4 gnome-keyring \
|
||||
gmake pkgconf libxml2 gnutls p11-kit nettle gmp gnome-keyring \
|
||||
libayatana-appindicator polkit webkit2-gtk_41 xdg-utils
|
||||
```
|
||||
|
||||
|
||||
Generated
+3
-3
@@ -63,11 +63,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1794408178,
|
||||
"narHash": "sha256-OUDRQTMmN/6cQ/ebDsazUmLj84RxSLaHznKv5As9E1k=",
|
||||
"lastModified": 1792506237,
|
||||
"narHash": "sha256-Q/8KLB6jNfpaUN1HAedE/u/Et9feE/zYSsutBLKrCFk=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "9397dcb09c9598a33509fbc0cce699bd4e6c84d5",
|
||||
"rev": "5adc50831c259f87faeb09ddf930d43597197473",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -29,8 +29,8 @@
|
||||
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
|
||||
pname = "globalprotect-openconnect";
|
||||
version = cargoToml.workspace.package.version;
|
||||
releaseTag = "v3.4.0";
|
||||
releaseVersion = "3.4.0";
|
||||
releaseTag = "v3.2.0";
|
||||
releaseVersion = "3.2.0";
|
||||
|
||||
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
|
||||
|
||||
@@ -55,8 +55,8 @@
|
||||
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
|
||||
|
||||
gpguiHashes = {
|
||||
x86_64 = "sha256-2qZQICnK5fa18suhnqeYnDI1z+SGqXJa1ZXI2NhfQP0=";
|
||||
aarch64 = "sha256-iOM3+Qte/6C4Gs/e9jVvx5DtBFq7DG2PNDCsGwPMeY0=";
|
||||
x86_64 = "sha256-Y0MbRebzQCPjvXUyWF8grBxGPuvDhIlnvEoEkFl5WMI=";
|
||||
aarch64 = "sha256-TnQPKllHSRfl/ir6PYZE6dVb8XUtayg7CRZUkWE4jsw=";
|
||||
};
|
||||
|
||||
gpguiArchive = pkgs.fetchurl {
|
||||
@@ -70,8 +70,8 @@
|
||||
};
|
||||
|
||||
binaryHashes = {
|
||||
x86_64 = "sha256-hBnfMAS3qEby9Dyc3ysH8tdGQwarXqo9xtY1gbN8gJI=";
|
||||
aarch64 = "sha256-lW1yQQD1G633tdBGBhVEAEQvMtnntK3mMU9M69x9ID0=";
|
||||
x86_64 = "sha256-3SvFEL9C8uB+ekp/PygBw0k8vZwdbnBWnvBcfGN8e1A=";
|
||||
aarch64 = "sha256-3lVKM1lnYQsgAboBCRuzEOFY/uB8+lf+yrxIRJJZtV4=";
|
||||
};
|
||||
|
||||
binaryArchive = pkgs.fetchurl {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
pkgbase = globalprotect-openconnect-git
|
||||
pkgdesc = A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method.
|
||||
pkgver = 3.3.1.r623.g4085368
|
||||
pkgrel = 1
|
||||
pkgver = 2.5.1.r1.g24f9bbb
|
||||
pkgrel = 2
|
||||
url = https://github.com/yuezk/GlobalProtect-openconnect
|
||||
install = gp.install
|
||||
arch = x86_64
|
||||
@@ -30,7 +30,6 @@ pkgbase = globalprotect-openconnect-git
|
||||
depends = gnutls
|
||||
depends = libp11-kit
|
||||
depends = nettle
|
||||
depends = libhogweed.so
|
||||
depends = gmp
|
||||
depends = shared-mime-info
|
||||
depends = desktop-file-utils
|
||||
@@ -43,7 +42,6 @@ pkgbase = globalprotect-openconnect-git
|
||||
provides = gpgui
|
||||
conflicts = globalprotect-openconnect
|
||||
options = !strip
|
||||
options = !lto
|
||||
source = globalprotect-openconnect::git+https://github.com/yuezk/GlobalProtect-openconnect.git#branch=main
|
||||
sha256sums = SKIP
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
_pkgname_prefix=globalprotect-openconnect
|
||||
pkgname="${_pkgname_prefix}-git"
|
||||
pkgver=3.3.1.r623.g4085368
|
||||
pkgrel=1
|
||||
pkgver=2.5.1.r1.g24f9bbb
|
||||
pkgrel=2
|
||||
pkgdesc="A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method."
|
||||
arch=(x86_64 aarch64)
|
||||
url="https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
@@ -22,8 +22,7 @@ source=("${_pkgname_prefix}::git+https://github.com/yuezk/GlobalProtect-openconn
|
||||
|
||||
sha256sums=("SKIP")
|
||||
|
||||
# GCC LTO objects from native dependencies cannot be linked by Rust's LLD.
|
||||
options=('!strip' '!lto')
|
||||
options=('!strip')
|
||||
|
||||
pkgver() {
|
||||
cd "${_pkgname_prefix}"
|
||||
|
||||
@@ -175,7 +175,7 @@ release_snapshot() {
|
||||
|
||||
# The appcast publisher removes expired macOS snapshots after the new feed
|
||||
# is live. Removing them here would temporarily break the current feed.
|
||||
if [[ "$asset" == GPConnect_*_arm64.* || "$asset" == GPConnect_*_windows-x64-setup.exe* || "$asset" == GPConnect_*_windows-arm64-setup.exe* ]]; then
|
||||
if [[ "$asset" == GPConnect_*_arm64.* ]]; then
|
||||
continue
|
||||
fi
|
||||
if ! delete_release_asset "$asset"; then
|
||||
|
||||
@@ -36,13 +36,13 @@ PY
|
||||
|
||||
branch="chore/promote-$tag"
|
||||
git switch -c "$branch" origin/main
|
||||
git merge --ff --no-edit "$release_sha"
|
||||
git merge --no-commit --no-ff "$release_sha"
|
||||
cp "$artifact_dir/flake.nix" "$artifact_dir/flake.lock" .
|
||||
python3 "$script_dir/validate-release-version.py" --version "${tag#v}"
|
||||
# Check against Cargo too: overriding the expectation above is only for artifacts.
|
||||
python3 "$script_dir/validate-release-version.py"
|
||||
git add flake.nix flake.lock
|
||||
if ! git diff --cached --quiet; then
|
||||
git commit -m "release: validate Nix packages for $tag"
|
||||
if ! git diff --cached --quiet || [[ -f "$(git rev-parse --git-path MERGE_HEAD)" ]]; then
|
||||
git commit -m "release: promote $tag sources and Nix packages together"
|
||||
fi
|
||||
echo "Prepared $branch. Open one PR against main and use a regular merge to preserve $tag in main's history."
|
||||
echo "Prepared $branch. Review the candidate, push normally, and open one PR against main."
|
||||
@@ -1,46 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Retain other platform/channel feeds before replacing a static Worker deployment."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
FEEDS = ("appcast.xml", "latest.json", "windows/latest.json", "windows/stable/appcast.xml", "windows/snapshot/appcast.xml")
|
||||
|
||||
|
||||
def preserve(base_url: str, directory: Path, exclude: list[str]) -> None:
|
||||
if urlparse(base_url).scheme != "https":
|
||||
raise ValueError("feed host must use HTTPS")
|
||||
for relative in FEEDS:
|
||||
if relative in exclude:
|
||||
continue
|
||||
try:
|
||||
request = Request(base_url.rstrip("/") + "/" + relative,
|
||||
headers={"User-Agent": "GPConnectReleasePublisher/1.0"})
|
||||
with urlopen(request, timeout=30) as response:
|
||||
data = response.read(1024 * 1024 + 1)
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
continue
|
||||
raise
|
||||
if len(data) > 1024 * 1024:
|
||||
raise ValueError(f"published feed is too large: {relative}")
|
||||
if relative.endswith(".json"):
|
||||
json.loads(data)
|
||||
else:
|
||||
ET.fromstring(data)
|
||||
target = directory / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--directory", type=Path, required=True)
|
||||
parser.add_argument("--exclude", action="append", default=[], choices=FEEDS)
|
||||
args = parser.parse_args()
|
||||
preserve(args.base_url, args.directory, args.exclude)
|
||||
@@ -8,18 +8,6 @@ import sys
|
||||
|
||||
|
||||
def report_compile(output):
|
||||
output = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', output)
|
||||
stages = re.findall(r'^GP_WINDOWS_BUILD_STAGE=(core|gui|bundle|installer)\r?$', output, re.MULTILINE)
|
||||
if stages:
|
||||
print(f'::error::Windows build stage: {stages[-1]}.')
|
||||
locations = re.findall(r'(?:-->\s+|panicked at )([^\r\n]+?):([0-9]+):([0-9]+)', output)
|
||||
for path, line, column in sorted(set(locations)):
|
||||
path = path.replace('\\', '/')
|
||||
for prefix in ('/source/gpgui/', '/source/gp/'):
|
||||
if prefix in path:
|
||||
path = path.split(prefix, 1)[1]
|
||||
fingerprint = hashlib.sha256(path.encode()).hexdigest()
|
||||
print(f'::error::Rust source location fingerprint: {fingerprint} {line}:{column}')
|
||||
codes = sorted(set(re.findall(r'error\[E[0-9]{4}\]', output)))
|
||||
if codes:
|
||||
print(f'::error::Rust diagnostic codes: {" ".join(codes)}.')
|
||||
@@ -29,10 +17,6 @@ def report_compile(output):
|
||||
'compiler or linker killed by SIGKILL'),
|
||||
(r'undefined reference to|undefined symbol:', 'unresolved linker symbols'),
|
||||
('proc macro panicked', 'procedural macro failed'),
|
||||
(r'Review runtime license notices for|Required runtime notice is missing',
|
||||
'runtime library notices require review'),
|
||||
('Unresolved Windows runtime dependency:', 'Windows runtime dependency is missing'),
|
||||
(r'out of memory|paging file is too small|os error 1455', 'memory exhausted'),
|
||||
]
|
||||
for pattern, description in categories:
|
||||
if re.search(pattern, output):
|
||||
|
||||
@@ -1,45 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Retain one source and version identity per build run, including retries."""
|
||||
"""Retain one source pair per build run so retries cannot move branch refs."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def record(path, gp, gpgui, output, build_version):
|
||||
def record(path, gp, gpgui, output):
|
||||
if path.exists():
|
||||
identity = json.loads(path.read_text())
|
||||
sources = json.loads(path.read_text())
|
||||
else:
|
||||
identity = {
|
||||
sources = {
|
||||
name: subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"],
|
||||
text=True, stderr=subprocess.DEVNULL).strip()
|
||||
for name, root in (("gp_sha", gp), ("gpgui_sha", gpgui))
|
||||
}
|
||||
cargo_version = runpy.run_path(str(Path(__file__).with_name("validate-release-version.py")))["cargo_version"]
|
||||
version = cargo_version(gp)
|
||||
if cargo_version(gpgui) != version:
|
||||
raise ValueError("public and desktop product versions differ")
|
||||
identity.update(version=version, build_version=build_version)
|
||||
if set(identity) != {"gp_sha", "gpgui_sha", "version", "build_version"} or any(
|
||||
if set(sources) != {"gp_sha", "gpgui_sha"} or any(
|
||||
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{40}", value)
|
||||
for name, value in identity.items() if name.endswith("_sha")
|
||||
for value in sources.values()
|
||||
):
|
||||
raise ValueError("invalid retained build source refs")
|
||||
if not isinstance(identity["version"], str) or not re.fullmatch(r"\d+\.\d+\.\d+", identity["version"]):
|
||||
raise ValueError("invalid retained product version")
|
||||
if not isinstance(identity["build_version"], str) or not re.fullmatch(
|
||||
r"(0|[1-9]\d*)\.(0|[1-9]\d*)", identity["build_version"]
|
||||
):
|
||||
raise ValueError("invalid retained build version")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(identity, indent=2) + "\n")
|
||||
path.write_text(json.dumps(sources, indent=2) + "\n")
|
||||
with output.open("a") as stream:
|
||||
for name, value in identity.items():
|
||||
stream.write(f"{name}={value}\n")
|
||||
for name, sha in sources.items():
|
||||
stream.write(f"{name}={sha}\n")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -47,10 +35,9 @@ def main():
|
||||
parser.add_argument("path", type=Path)
|
||||
parser.add_argument("--gp", type=Path, required=True)
|
||||
parser.add_argument("--gpgui", type=Path, required=True)
|
||||
parser.add_argument("--build-version", required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
record(args.path, args.gp, args.gpgui, Path(os.environ["GITHUB_OUTPUT"]), args.build_version)
|
||||
record(args.path, args.gp, args.gpgui, Path(os.environ["GITHUB_OUTPUT"]))
|
||||
except (OSError, ValueError, subprocess.CalledProcessError):
|
||||
parser.exit(1, "Could not retain the selected build source refs.\n")
|
||||
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
# Exercise a candidate installer only on an empty CI machine.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$Installer,
|
||||
[Parameter(Mandatory=$true)][ValidateSet('x64','arm64')][string]$Architecture,
|
||||
[Parameter(Mandatory=$true)][AllowEmptyString()][string]$Build
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
$destination = Join-Path $env:ProgramFiles 'GP Connect'
|
||||
if ((Test-Path $destination) -or (Get-Service GPConnect -ErrorAction SilentlyContinue)) {
|
||||
throw 'Run this installer test on a clean Windows test machine.'
|
||||
}
|
||||
$process = Start-Process $Installer -ArgumentList '/S' -PassThru -Wait
|
||||
if ($process.ExitCode -ne 0) {
|
||||
# This test requires an empty CI installation; this log contains only installer operations.
|
||||
$log = Join-Path $env:ProgramData 'GP Connect\installer.log'
|
||||
if (Test-Path $log) { Get-Content $log -Tail 80 | Write-Host }
|
||||
throw "The installer failed with exit code $($process.ExitCode)."
|
||||
}
|
||||
$info = Get-Content (Join-Path $destination 'build-info.json') -Raw | ConvertFrom-Json
|
||||
if ($info.architecture -ne $Architecture -or [string]$info.build_version -ne $Build) { throw 'The installed package identity does not match.' }
|
||||
$service = Get-CimInstance Win32_Service -Filter "Name='GPConnect'"
|
||||
if ($service.State -ne 'Running' -or $service.StartMode -ne 'Auto' -or $service.StartName -ne 'LocalSystem') {
|
||||
throw 'The service did not start automatically as LocalSystem.'
|
||||
}
|
||||
foreach ($name in @('gpgui.exe', 'gpauth.exe')) {
|
||||
$process = Start-Process (Join-Path $destination $name) -ArgumentList '--version' -PassThru -Wait
|
||||
if ($process.ExitCode -ne 0) { throw "The installed $name cannot start." }
|
||||
}
|
||||
$state = Join-Path $env:LOCALAPPDATA 'GP Connect\config\protected-state'
|
||||
New-Item -ItemType Directory -Force $state | Out-Null
|
||||
$marker = Join-Path $state 'ci-install-retention'
|
||||
[IO.File]::WriteAllText($marker, 'retain user settings')
|
||||
$process = Start-Process (Join-Path $destination 'uninstall.exe') -ArgumentList '/S' -PassThru -Wait
|
||||
if ($process.ExitCode -ne 0) { throw 'The uninstaller failed.' }
|
||||
if ((Get-Service GPConnect -ErrorAction SilentlyContinue) -or (Test-Path $destination) -or (Test-Path ($destination + '.previous'))) {
|
||||
throw 'The uninstaller left service registration or runtime files.'
|
||||
}
|
||||
$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk'
|
||||
if ((Test-Path $shortcut) -or (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect')) {
|
||||
throw 'The uninstaller left its shortcut or registration.'
|
||||
}
|
||||
if ([IO.File]::ReadAllText($marker) -ne 'retain user settings') { throw 'The uninstaller changed user state.' }
|
||||
Remove-Item $marker
|
||||
Write-Host "Installed $Architecture runtime and service, launched both applications, and uninstalled successfully."
|
||||
@@ -274,23 +274,6 @@ class PrivateTestStageTests(unittest.TestCase):
|
||||
self.assertIn(expected, result.stdout)
|
||||
self.assertNotRegex(result.stdout, r'(?m)^Rust tests: started')
|
||||
|
||||
def test_compile_diagnostics_hash_source_locations_and_allowlist_windows_stage(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
log = Path(temporary) / 'private.log'
|
||||
log.write_text('GP_WINDOWS_BUILD_STAGE=gui\n'
|
||||
'error[E0433]: PRIVATE_ERROR_MESSAGE\n'
|
||||
' --> D:/a/repo/source/gpgui/crates/private.rs:42:9\n'
|
||||
'PRIVATE_SOURCE_AND_CREDENTIALS\n')
|
||||
result = subprocess.run([sys.executable, str(ROOT / 'scripts/private-ci-diagnostics.py'),
|
||||
'compile', str(log)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
digest = hashlib.sha256(b'crates/private.rs').hexdigest()
|
||||
self.assertEqual(result.stdout,
|
||||
'::error::Windows build stage: gui.\n'
|
||||
f'::error::Rust source location fingerprint: {digest} 42:9\n'
|
||||
'::error::Rust diagnostic codes: error[E0433].\n')
|
||||
self.assertEqual(result.stderr, '')
|
||||
|
||||
def test_test_diagnostics_hash_names_without_exposing_private_details(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
log = Path(temporary) / 'private.log'
|
||||
|
||||
@@ -90,43 +90,24 @@ class ReleaseVersionTests(unittest.TestCase):
|
||||
versions.validate(root, package=package)
|
||||
|
||||
|
||||
class BuildIdentityTests(unittest.TestCase):
|
||||
class SourceSelectionTests(unittest.TestCase):
|
||||
def test_retry_uses_original_sources_after_both_branches_advance(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
paths = [root / 'gp', root / 'gpgui']
|
||||
for repo in paths:
|
||||
initialize(repo)
|
||||
write_version(repo)
|
||||
(repo / 'source').write_text('first')
|
||||
commit(repo, 'first')
|
||||
path, output = root / 'sources.json', root / 'output'
|
||||
sources.record(path, *paths, output, '42.1')
|
||||
sources.record(path, *paths, output)
|
||||
original = json.loads(path.read_text())
|
||||
for repo in paths:
|
||||
write_version(repo, '3.2.0')
|
||||
(repo / 'source').write_text('second')
|
||||
commit(repo, 'second')
|
||||
sources.record(path, *paths, output, '42.2')
|
||||
sources.record(path, *paths, output)
|
||||
self.assertEqual(json.loads(path.read_text()), original)
|
||||
self.assertEqual(output.read_text().count(f"gp_sha={original['gp_sha']}"), 2)
|
||||
self.assertEqual(original['version'], '3.1.0')
|
||||
self.assertEqual(original['build_version'], '42.1')
|
||||
sources.record(path, root / 'missing-gp', root / 'missing-gui', output, '42.3')
|
||||
self.assertEqual(json.loads(path.read_text()), original)
|
||||
|
||||
def test_mismatched_product_versions_are_not_retained(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
paths = [root / 'gp', root / 'gpgui']
|
||||
for repo, version in zip(paths, ['3.1.0', '3.2.0']):
|
||||
initialize(repo)
|
||||
write_version(repo, version)
|
||||
commit(repo, 'source')
|
||||
path = root / 'sources.json'
|
||||
with self.assertRaisesRegex(ValueError, 'versions differ'):
|
||||
sources.record(path, *paths, root / 'output', '42.1')
|
||||
self.assertFalse(path.exists())
|
||||
|
||||
def test_corrupt_retained_sources_do_not_resolve_again(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
@@ -134,11 +115,11 @@ class BuildIdentityTests(unittest.TestCase):
|
||||
path = root / 'sources.json'
|
||||
path.write_text('{"gp_sha":"main","gpgui_sha":"main"}')
|
||||
with self.assertRaises(ValueError):
|
||||
sources.record(path, root, root, root / 'output', '42.1')
|
||||
sources.record(path, root, root, root / 'output')
|
||||
|
||||
|
||||
class PromotionTests(unittest.TestCase):
|
||||
def test_promotion_keeps_tag_history_and_adds_flake_commit(self):
|
||||
def test_sources_and_flake_are_committed_together_preserving_main_work(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
repo, origin, artifact = root / 'repo', root / 'origin.git', root / 'artifact'
|
||||
@@ -168,8 +149,7 @@ class PromotionTests(unittest.TestCase):
|
||||
self.assertEqual(git(repo, 'show', f'{old}:Cargo.toml'), '[workspace.package]\nversion = "3.1.0"')
|
||||
self.assertTrue((repo / 'infrastructure').exists())
|
||||
self.assertTrue((repo / 'feature').exists())
|
||||
self.assertEqual(git(repo, 'rev-list', '--parents', '-1', 'HEAD^').split()[1:], [main, release])
|
||||
self.assertEqual(git(repo, 'diff', '--name-only', 'HEAD^', 'HEAD'), 'flake.nix')
|
||||
self.assertEqual(git(repo, 'rev-list', '--parents', '-1', 'HEAD').split()[1:], [main, release])
|
||||
self.assertEqual(git(repo, 'status', '--porcelain'), '')
|
||||
|
||||
|
||||
@@ -215,65 +195,6 @@ class SnapshotBranchTests(unittest.TestCase):
|
||||
self.assertEqual(git(origin, 'branch', '--list', 'main'), '')
|
||||
|
||||
|
||||
class PublicationWorkflowTests(unittest.TestCase):
|
||||
def job(self, name):
|
||||
source = (ROOT / '.github/workflows/build.yaml').read_text()
|
||||
return re.search(r'(?ms)^ ' + name + r':\n.*?(?=^ [\w-]+:|\Z)', source).group(0)
|
||||
|
||||
def decisions(self, name, cases):
|
||||
expression = re.search(r'\$\{\{ (.*?) \}\}', self.job(name), re.DOTALL).group(1)
|
||||
expression = re.sub(r'needs\.([\w-]+)\.result', r'needs["\1"].result', expression)
|
||||
script = """
|
||||
const cases = JSON.parse(process.argv[1]);
|
||||
const allows = new Function('needs', 'inputs', 'github', 'cancelled',
|
||||
'return (' + process.argv[2] + ')');
|
||||
console.log(JSON.stringify(cases.map(c => allows(c.needs, c.inputs, c.github, () => c.cancelled))));
|
||||
"""
|
||||
return json.loads(subprocess.check_output(
|
||||
['node', '-e', script, json.dumps(cases), expression], text=True))
|
||||
|
||||
def test_macos_assets_require_both_jobs_and_a_live_run(self):
|
||||
job = self.job('publish-macos-assets')
|
||||
self.assertIn('needs: [build-macos, gh-release]', job)
|
||||
self.assertIn('uses: ./.github/workflows/publish-macos-assets.yaml', job)
|
||||
cases, expected = [], []
|
||||
for macos in ['success', 'failure', 'skipped', 'cancelled']:
|
||||
for release in ['success', 'failure', 'skipped', 'cancelled']:
|
||||
for cancelled in [False, True]:
|
||||
cases.append({'needs': {'build-macos': {'result': macos},
|
||||
'gh-release': {'result': release}},
|
||||
'inputs': {}, 'github': {}, 'cancelled': cancelled})
|
||||
expected.append(not cancelled and macos == release == 'success')
|
||||
self.assertEqual(self.decisions('publish-macos-assets', cases), expected)
|
||||
|
||||
def test_snapshot_feeds_follow_selection_and_publication_results(self):
|
||||
cases, expected_windows, expected_macos = [], [], []
|
||||
for macos in [False, True]:
|
||||
for windows in [False, True]:
|
||||
for override in [{}, {'channel': 'stable'}, {'build_only': True},
|
||||
{'event': 'push'}, {'cancelled': True}, {'release': 'failure'},
|
||||
{'macos_publish': 'failure'}, {'windows_feed': 'failure'}]:
|
||||
inputs = dict(channel='snapshot', build_only=False,
|
||||
build_macos=macos, build_windows=windows)
|
||||
inputs.update({key: value for key, value in override.items() if key in inputs})
|
||||
release = override.get('release', 'success')
|
||||
macos_publish = override.get('macos_publish', 'success') if macos else 'skipped'
|
||||
windows_feed = override.get('windows_feed', 'success') if windows else 'skipped'
|
||||
cancelled = override.get('cancelled', False)
|
||||
event = override.get('event', 'workflow_dispatch')
|
||||
cases.append({'needs': {'gh-release': {'result': release},
|
||||
'publish-macos-assets': {'result': macos_publish},
|
||||
'publish-windows-snapshot-feed': {'result': windows_feed}},
|
||||
'inputs': inputs, 'github': {'event_name': event}, 'cancelled': cancelled})
|
||||
ready = (not cancelled and event == 'workflow_dispatch' and
|
||||
inputs['channel'] == 'snapshot' and not inputs['build_only'] and
|
||||
release == 'success' and (not macos or macos_publish == 'success'))
|
||||
expected_windows.append(ready and windows)
|
||||
expected_macos.append(ready and macos and (not windows or windows_feed == 'success'))
|
||||
self.assertEqual(self.decisions('publish-windows-snapshot-feed', cases), expected_windows)
|
||||
self.assertEqual(self.decisions('publish-macos-unix-snapshot-feeds', cases), expected_macos)
|
||||
|
||||
|
||||
class DockerMatrixTests(unittest.TestCase):
|
||||
def test_workflow_matrix_follows_all_architecture_choices(self):
|
||||
source = (ROOT / '.github/workflows/release.yaml').read_text()
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
import argparse
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from urllib.error import HTTPError
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def load(name, filename):
|
||||
spec = importlib.util.spec_from_file_location(name, Path(__file__).parents[1] / filename)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
feed = load("windows_update_feed", "windows-update-feed.py")
|
||||
preserver = load("preserve_update_feeds", "preserve-update-feeds.py")
|
||||
|
||||
|
||||
class WindowsFeedTests(unittest.TestCase):
|
||||
def args(self, root, channel="stable", version="3.4.0", build=None, architecture="x64"):
|
||||
name = feed.installer_name(version, channel, build, architecture)
|
||||
installer = root / name
|
||||
installer.write_bytes(f"test installer {architecture}".encode())
|
||||
signature = root / f"installer-{architecture}.sig"
|
||||
signature.write_text(base64.b64encode(bytes([1 if architecture == "arm64" else 0]) * 64).decode())
|
||||
highlights = root / "highlights.txt"
|
||||
highlights.write_text("Update & improve <Windows>.\n")
|
||||
tag = f"v{version}" if channel == "stable" else "snapshot"
|
||||
return argparse.Namespace(payload=[feed.Payload(architecture, installer,
|
||||
f"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{tag}/{name}", signature)],
|
||||
repository="yuezk/GlobalProtect-openconnect", channel=channel,
|
||||
version=version, build=build, released_at="2026-11-14",
|
||||
highlights_file=highlights, input=None, output=root / "windows", allow_localhost=False)
|
||||
|
||||
def test_catalog_and_appcast_keep_the_same_version_and_payload(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
feed.generate(args)
|
||||
catalog = json.loads((args.output / "latest.json").read_text())
|
||||
self.assertEqual(catalog["stable"]["platforms"], ["windows"])
|
||||
item = ET.parse(args.output / "stable/appcast.xml").find("channel/item")
|
||||
self.assertEqual(item.findtext("description"), "Update & improve <Windows>.")
|
||||
enclosure = item.find("enclosure")
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), catalog["stable"]["version"])
|
||||
self.assertEqual(int(enclosure.get("length")), args.payload[0].installer.stat().st_size)
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}os"), "windows-x64")
|
||||
|
||||
def test_native_architectures_share_one_release_with_separate_signed_enclosures(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
arm = self.args(Path(directory), architecture="arm64")
|
||||
args.payload += arm.payload
|
||||
feed.generate(args)
|
||||
items = ET.parse(args.output / "stable/appcast.xml").findall("channel/item")
|
||||
self.assertEqual(len(items), 2)
|
||||
for item, payload in zip(items, args.payload):
|
||||
enclosure = item.find("enclosure")
|
||||
self.assertEqual(enclosure.get("url"), payload.installer_url)
|
||||
self.assertEqual(int(enclosure.get("length")), payload.installer.stat().st_size)
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}edSignature"), payload.signature_file.read_text())
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}os"), f"windows-{payload.architecture}")
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.4.0")
|
||||
minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.19041"
|
||||
self.assertEqual(item.findtext(f"{{{feed.SPARKLE}}}minimumSystemVersion"), minimum)
|
||||
self.assertEqual(json.loads((args.output / "latest.json").read_text())["stable"]["platforms"], ["windows"])
|
||||
|
||||
def test_mismatched_or_duplicate_architecture_does_not_write_a_feed(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
args.payload[0].architecture = "arm64"
|
||||
with self.assertRaisesRegex(ValueError, "filename"):
|
||||
feed.generate(args)
|
||||
self.assertFalse(args.output.exists())
|
||||
args.payload[0].architecture = "x64"
|
||||
args.payload *= 2
|
||||
with self.assertRaisesRegex(ValueError, "one installer per"):
|
||||
feed.generate(args)
|
||||
self.assertFalse(args.output.exists())
|
||||
|
||||
def test_snapshot_promotion_retains_stable_and_rejects_downgrade(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
feed.generate(args)
|
||||
args.input = args.output / "latest.json"
|
||||
args.channel, args.build = "snapshot", "2026.1114.2"
|
||||
args.payload[0].installer = args.payload[0].installer.rename(args.payload[0].installer.parent / feed.installer_name(args.version, args.channel, args.build))
|
||||
args.payload[0].installer_url = f"https://github.com/{args.repository}/releases/download/snapshot/{args.payload[0].installer.name}"
|
||||
feed.generate(args)
|
||||
catalog = json.loads(args.input.read_text())
|
||||
self.assertEqual(catalog["stable"]["version"], "3.4.0")
|
||||
self.assertEqual(catalog["snapshot"]["build"], "2026.1114.2")
|
||||
enclosure = ET.parse(args.output / "snapshot/appcast.xml").find("channel/item/enclosure")
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.4.0-snapshot.2026.1114.2")
|
||||
args.build = "2026.1114.1"
|
||||
args.payload[0].installer = args.payload[0].installer.rename(args.payload[0].installer.parent / feed.installer_name(args.version, args.channel, args.build))
|
||||
args.payload[0].installer_url = f"https://github.com/{args.repository}/releases/download/snapshot/{args.payload[0].installer.name}"
|
||||
with self.assertRaisesRegex(ValueError, "older"):
|
||||
feed.generate(args)
|
||||
|
||||
def test_snapshot_filename_cannot_advertise_another_build(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory), "snapshot", build="2026.1114.1")
|
||||
args.build = "2026.1114.2"
|
||||
with self.assertRaisesRegex(ValueError, "filename does not match"):
|
||||
feed.generate(args)
|
||||
|
||||
def test_newer_stable_updates_both_native_feeds_and_retains_snapshot_history(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
snapshot = self.args(root, "snapshot", build="2026.1114.2")
|
||||
feed.generate(snapshot)
|
||||
stable = self.args(root, version="3.5.0")
|
||||
stable.input = stable.output / "latest.json"
|
||||
feed.generate(stable)
|
||||
catalog = json.loads(stable.input.read_text())
|
||||
self.assertEqual(catalog["snapshot"]["baseVersion"], "3.4.0")
|
||||
self.assertEqual(catalog["snapshot"]["build"], "2026.1114.2")
|
||||
for channel in ("stable", "snapshot"):
|
||||
enclosure = ET.parse(stable.output / channel / "appcast.xml").find("channel/item/enclosure")
|
||||
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.5.0")
|
||||
self.assertEqual(enclosure.get("url"), stable.payload[0].installer_url)
|
||||
|
||||
def test_stable_without_snapshot_initializes_both_native_feeds(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
feed.generate(args)
|
||||
self.assertEqual((args.output / "stable/appcast.xml").read_bytes(),
|
||||
(args.output / "snapshot/appcast.xml").read_bytes())
|
||||
self.assertIsNone(json.loads((args.output / "latest.json").read_text())["snapshot"])
|
||||
|
||||
def test_stable_does_not_replace_same_or_newer_base_snapshot_feed(self):
|
||||
for snapshot_version in ("3.4.0", "3.5.0"):
|
||||
with self.subTest(snapshot_version=snapshot_version), tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
snapshot = self.args(root, "snapshot", version=snapshot_version, build="2026.1114.2")
|
||||
feed.generate(snapshot)
|
||||
before = (snapshot.output / "snapshot/appcast.xml").read_bytes()
|
||||
stable = self.args(root)
|
||||
stable.input = stable.output / "latest.json"
|
||||
feed.generate(stable)
|
||||
self.assertEqual((stable.output / "snapshot/appcast.xml").read_bytes(), before)
|
||||
|
||||
def test_snapshot_older_than_stable_is_rejected_without_changing_published_files(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
stable = self.args(root, version="3.5.0")
|
||||
feed.generate(stable)
|
||||
published = {relative: (stable.output / relative).read_bytes()
|
||||
for relative in ("latest.json", "stable/appcast.xml", "snapshot/appcast.xml")}
|
||||
snapshot = self.args(root, "snapshot", version="3.4.0", build="2026.1114.3")
|
||||
snapshot.input = stable.output / "latest.json"
|
||||
with self.assertRaisesRegex(ValueError, "snapshot base version is older"):
|
||||
feed.generate(snapshot)
|
||||
for relative, content in published.items():
|
||||
self.assertEqual((stable.output / relative).read_bytes(), content)
|
||||
|
||||
def test_private_loopback_download_requires_explicit_opt_in(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
args.payload[0].installer_url = "http://127.0.0.1:18770/setup.exe"
|
||||
with self.assertRaisesRegex(ValueError, "matching GitHub"):
|
||||
feed.generate(args)
|
||||
args.allow_localhost = True
|
||||
feed.generate(args)
|
||||
|
||||
def test_missing_or_malformed_signature_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
args = self.args(Path(directory))
|
||||
args.payload[0].signature_file.write_text("not a signature")
|
||||
with self.assertRaises(ValueError):
|
||||
feed.generate(args)
|
||||
|
||||
def test_preservation_keeps_other_feeds_and_does_not_hide_server_errors(self):
|
||||
class Response:
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *unused): pass
|
||||
def read(self, length): return b'{"schemaVersion": 1}'
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
with patch.object(preserver, "urlopen", return_value=Response()) as request:
|
||||
preserver.preserve("https://updates.gpgui.com", root,
|
||||
["appcast.xml", "latest.json", "windows/stable/appcast.xml", "windows/snapshot/appcast.xml"])
|
||||
self.assertTrue((root / "windows/latest.json").exists())
|
||||
self.assertEqual(request.call_count, 1)
|
||||
outgoing = request.call_args.args[0]
|
||||
self.assertEqual(outgoing.full_url, "https://updates.gpgui.com/windows/latest.json")
|
||||
self.assertEqual(outgoing.get_header("User-agent"), "GPConnectReleasePublisher/1.0")
|
||||
with patch.object(preserver, "urlopen", side_effect=HTTPError("url", 500, "failure", {}, None)):
|
||||
with self.assertRaises(HTTPError):
|
||||
preserver.preserve("https://updates.gpgui.com", root, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -10,7 +10,7 @@ import unicodedata
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ALLOWED_PLATFORMS = {"linux", "freebsd", "openbsd", "windows"}
|
||||
ALLOWED_PLATFORMS = {"linux", "freebsd", "openbsd"}
|
||||
SEMVER = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
|
||||
BUILD = re.compile(r"^(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)){0,2}$")
|
||||
EXPECTED_TOP_LEVEL_KEYS = {"schemaVersion", "stable", "snapshot"}
|
||||
@@ -192,7 +192,7 @@ def main() -> None:
|
||||
generate_parser.add_argument("--channel", choices=("stable", "snapshot"), required=True)
|
||||
generate_parser.add_argument("--version", required=True)
|
||||
generate_parser.add_argument("--platform", action="append", choices=sorted(ALLOWED_PLATFORMS),
|
||||
help="Published target; repeat for multiple targets (default: Unix targets)")
|
||||
help="Published Unix target; repeat for multiple targets (default: all)")
|
||||
generate_parser.add_argument("--build")
|
||||
generate_parser.add_argument("--released-at", required=True)
|
||||
generate_parser.add_argument("--highlights-file", required=True, type=Path)
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build one Windows catalog and appcast from verified native installers."""
|
||||
import argparse
|
||||
import base64
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle"
|
||||
ET.register_namespace("sparkle", SPARKLE)
|
||||
spec = importlib.util.spec_from_file_location("update_manifest", Path(__file__).with_name("validate-update-manifest.py"))
|
||||
manifest = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(manifest)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Payload:
|
||||
architecture: str
|
||||
installer: Path
|
||||
installer_url: str
|
||||
signature_file: Path
|
||||
|
||||
|
||||
def release_version(version: str, channel: str, build: str | None) -> str:
|
||||
if channel == "snapshot":
|
||||
return f"{version}-snapshot.{build}"
|
||||
return version
|
||||
|
||||
|
||||
def installer_name(version: str, channel: str, build: str | None, architecture: str = "x64") -> str:
|
||||
return f"GPConnect_{release_version(version, channel, build)}_windows-{architecture}-setup.exe"
|
||||
|
||||
|
||||
def validate_payload(payload: Payload, args: argparse.Namespace) -> tuple[str, int]:
|
||||
if payload.architecture not in {"x64", "arm64"}:
|
||||
raise ValueError("unsupported Windows architecture")
|
||||
expected_name = installer_name(args.version, args.channel, args.build, payload.architecture)
|
||||
if not args.allow_localhost and payload.installer.name != expected_name:
|
||||
raise ValueError("installer filename does not match the version, channel, build and architecture")
|
||||
parsed = urlparse(payload.installer_url)
|
||||
tag = f"v{args.version}" if args.channel == "stable" else "snapshot"
|
||||
expected = f"https://github.com/{args.repository}/releases/download/{tag}/"
|
||||
local = args.allow_localhost and parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
|
||||
if not local and not payload.installer_url.startswith(expected):
|
||||
raise ValueError("installer URL must identify the matching GitHub release asset")
|
||||
if parsed.query or parsed.fragment or not parsed.path.endswith(".exe"):
|
||||
raise ValueError("installer URL must name an EXE without query or fragment")
|
||||
if not local and parsed.path.rsplit("/", 1)[-1] != expected_name:
|
||||
raise ValueError("installer download filename does not match the version, channel, build and architecture")
|
||||
signature = payload.signature_file.read_text(encoding="ascii").strip()
|
||||
if len(base64.b64decode(signature, validate=True)) != 64:
|
||||
raise ValueError("EdDSA signature must contain 64 bytes")
|
||||
length = payload.installer.stat().st_size
|
||||
if length == 0:
|
||||
raise ValueError("installer is empty")
|
||||
return signature, length
|
||||
|
||||
|
||||
def generate(args: argparse.Namespace) -> None:
|
||||
manifest.version_tuple(args.version)
|
||||
if args.channel == "snapshot":
|
||||
if args.build is None:
|
||||
raise ValueError("snapshot releases require --build")
|
||||
manifest.build_tuple(args.build)
|
||||
elif args.build is not None:
|
||||
raise ValueError("stable releases must not specify --build")
|
||||
if not args.payload or len({payload.architecture for payload in args.payload}) != len(args.payload):
|
||||
raise ValueError("provide one installer per Windows architecture")
|
||||
prepared = [(payload, *validate_payload(payload, args)) for payload in args.payload]
|
||||
if args.channel == "snapshot" and args.input is not None:
|
||||
previous = manifest.validate_manifest(json.loads(args.input.read_text(encoding="utf-8")), args.repository)
|
||||
stable = previous["stable"]
|
||||
if stable is not None and manifest.version_tuple(args.version) < manifest.version_tuple(stable["version"]):
|
||||
raise ValueError("snapshot base version is older than the published stable release")
|
||||
output = args.output
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
catalog = output / "latest.json"
|
||||
manifest.generate(argparse.Namespace(
|
||||
repository=args.repository, channel=args.channel, version=args.version,
|
||||
platform=["windows"], build=args.build, released_at=args.released_at,
|
||||
highlights_file=args.highlights_file, input=args.input, output=catalog,
|
||||
))
|
||||
data = json.loads(catalog.read_text(encoding="utf-8"))
|
||||
if any(release and release["platforms"] != ["windows"] for release in [data["stable"], data["snapshot"]]):
|
||||
raise ValueError("Windows catalog may contain only the Windows target")
|
||||
release = data[args.channel]
|
||||
display_version = release_version(args.version, args.channel, args.build)
|
||||
rss = ET.Element("rss", {"version": "2.0"})
|
||||
channel = ET.SubElement(rss, "channel")
|
||||
ET.SubElement(channel, "title").text = "GP Connect for Windows"
|
||||
for payload, signature, length in prepared:
|
||||
item = ET.SubElement(channel, "item")
|
||||
ET.SubElement(item, "title").text = f"GP Connect {display_version}"
|
||||
ET.SubElement(item, "description").text = "\n".join(release["highlights"])
|
||||
minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.19041"
|
||||
ET.SubElement(item, f"{{{SPARKLE}}}minimumSystemVersion").text = minimum
|
||||
ET.SubElement(item, "enclosure", {
|
||||
"url": payload.installer_url, "length": str(length), "type": "application/octet-stream",
|
||||
f"{{{SPARKLE}}}version": display_version,
|
||||
f"{{{SPARKLE}}}shortVersionString": display_version,
|
||||
f"{{{SPARKLE}}}os": f"windows-{payload.architecture}", f"{{{SPARKLE}}}edSignature": signature,
|
||||
})
|
||||
ET.indent(rss)
|
||||
channels = [args.channel]
|
||||
snapshot = data["snapshot"]
|
||||
if args.channel == "stable" and (
|
||||
snapshot is None or manifest.version_tuple(args.version) > manifest.version_tuple(snapshot["baseVersion"])
|
||||
):
|
||||
# A newer stable release also updates snapshot installations.
|
||||
channels.append("snapshot")
|
||||
for target_channel in channels:
|
||||
channel_directory = output / target_channel
|
||||
channel_directory.mkdir(exist_ok=True)
|
||||
ET.ElementTree(rss).write(channel_directory / "appcast.xml", encoding="utf-8", xml_declaration=True)
|
||||
for payload, _, _ in prepared:
|
||||
with payload.installer.open("rb") as installer:
|
||||
digest = hashlib.file_digest(installer, "sha256").hexdigest()
|
||||
(output / (payload.installer.name + ".sha256")).write_text(f"{digest} {payload.installer.name}\n", encoding="ascii")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--payload", nargs=4, action="append", required=True,
|
||||
metavar=("ARCH", "INSTALLER", "URL", "SIGNATURE_FILE"))
|
||||
parser.add_argument("--repository", default="yuezk/GlobalProtect-openconnect")
|
||||
parser.add_argument("--channel", choices=("stable", "snapshot"), required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--build")
|
||||
parser.add_argument("--released-at", required=True)
|
||||
parser.add_argument("--highlights-file", type=Path, required=True)
|
||||
parser.add_argument("--input", type=Path)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--allow-localhost", action="store_true", help="Permit an isolated loopback test download")
|
||||
args = parser.parse_args()
|
||||
args.payload = [Payload(architecture, Path(installer), url, Path(signature))
|
||||
for architecture, installer, url, signature in args.payload]
|
||||
try:
|
||||
generate(args)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user