Compare commits

..
Author SHA1 Message Date
Kevin Yue baa77a774b chore: prepare GP Connect 3.3.1 release 2026-11-08 21:49:14 +08:00
Kevin Yue 92857fc1ba fix: add gateway login diagnostics and scope platform dependencies 2026-11-08 21:36:31 +08:00
Kevin Yue 5ff3760bc0 fix: select PKCS12 issuers by certificate signature
Handle CA rollover and self-issued intermediates by checking issuer signatures. Preserve RSA-PSS signature parameters during GnuTLS verification and keep the original archive for OpenConnect.

Add mutual-TLS regression coverage for certificate bag order and RSA-PSS salt lengths. Verified 53 targeted tests plus gpapi, desktop-core, and iOS compile checks.
2026-11-07 13:27:42 +08:00
Kevin Yue c476dfefb0 fix: restore client certificate compatibility after OpenSSL removal
Use GnuTLS for desktop client key matching and signing without applying server certificate policy to local identities. Restore RC4 PKCS12 import and renewed certificate selection, and provide actionable unsupported identity errors.

Add HTTP and OpenConnect mutual TLS regressions. Record the unresolved TLS 1.2 ECDSA hash limitation and reject P-521 and RSA-PSS keys explicitly.
2026-11-07 11:23:19 +08:00
Ihar Hrachyshka e03a758acb test: use root for HIP user lookup (#696) 2026-11-06 09:08:48 +08:00
Kevin Yue 16e08c09af Merge pull request #695 from yuezk/fix/aur-srcinfo
fix: build AUR native dependencies without makepkg LTO
2026-11-06 01:28:07 +08:00
Kevin Yue a949b175d4 fix: disable makepkg LTO for mixed Rust and C archives 2026-11-06 01:19:54 +08:00
Kevin Yue 1202ca6c81 fix: synchronize AUR dependency metadata 2026-11-06 01:10:29 +08:00
Kevin Yue 0408bcb67f Merge pull request #694 from yuezk/chore/promote-v3.3.0
chore: promote 3.3.0 sources and Nix packages
2026-11-06 01:08:13 +08:00
Kevin Yue a9474d4059 docs: include complete 3.3.0 release notes 2026-11-06 00:49:58 +08:00
Kevin Yue 5380a5f3c3 release: promote v3.3.0 sources and Nix packages together 2026-11-06 00:49:57 +08:00
Kevin Yue 82c9ba2dcd docs: include Okta FastPass fix in 3.3.0 release notes 2026-11-05 23:33:02 +08:00
Kevin Yue fd08cdbe66 feat: release GP Connect 3.3.0 with Native Shell support 2026-11-05 23:05:14 +08:00
Kevin Yue d12d677208 Merge pull request #693 from yuezk/ci/prepare-3.3.0-release
ci: prepare Native Shell release infrastructure
2026-11-05 23:01:42 +08:00
Kevin Yue d15ebdfe3a ci: prepare Native Shell builds and publishers for 3.3.0 2026-11-05 22:59:59 +08:00
62 changed files with 3426 additions and 605 deletions

No files matched your search

+3
View File
@@ -16,3 +16,6 @@ gen
# Nix files # Nix files
result result
# Packages & test assets
*.ipa
Generated
+15 -23
View File
@@ -292,7 +292,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]] [[package]]
name = "auth" name = "auth"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"block2", "block2",
@@ -547,7 +547,7 @@ dependencies = [
[[package]] [[package]]
name = "browser-launcher" name = "browser-launcher"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"log", "log",
@@ -911,7 +911,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"tempfile", "tempfile",
] ]
@@ -2115,7 +2115,7 @@ dependencies = [
[[package]] [[package]]
name = "gpapi" name = "gpapi"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.23.1", "base64 0.23.1",
@@ -2124,6 +2124,7 @@ dependencies = [
"chrono", "chrono",
"clap", "clap",
"clap-verbosity-flag", "clap-verbosity-flag",
"cms",
"common", "common",
"directories", "directories",
"dns-lookup", "dns-lookup",
@@ -2142,6 +2143,7 @@ dependencies = [
"oslog", "oslog",
"p12-keystore", "p12-keystore",
"pem", "pem",
"pkcs12",
"pkcs8", "pkcs8",
"pkg-config", "pkg-config",
"proptest", "proptest",
@@ -2149,7 +2151,7 @@ dependencies = [
"reqwest", "reqwest",
"rustls", "rustls",
"rustls-pemfile", "rustls-pemfile",
"sec1", "rustls-platform-verifier",
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
@@ -2174,7 +2176,7 @@ dependencies = [
[[package]] [[package]]
name = "gpauth" name = "gpauth"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"auth", "auth",
@@ -2193,7 +2195,7 @@ dependencies = [
[[package]] [[package]]
name = "gpclient" name = "gpclient"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -2224,7 +2226,7 @@ dependencies = [
[[package]] [[package]]
name = "gpgui-helper" name = "gpgui-helper"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -2245,7 +2247,7 @@ dependencies = [
[[package]] [[package]]
name = "gphip" name = "gphip"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"askama", "askama",
@@ -2262,7 +2264,7 @@ dependencies = [
[[package]] [[package]]
name = "gpservice" name = "gpservice"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -2297,7 +2299,7 @@ dependencies = [
[[package]] [[package]]
name = "gptunnel" name = "gptunnel"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"gpapi", "gpapi",
"log", "log",
@@ -2309,7 +2311,7 @@ dependencies = [
[[package]] [[package]]
name = "gpvpnc" name = "gpvpnc"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"log", "log",
] ]
@@ -3823,7 +3825,7 @@ dependencies = [
[[package]] [[package]]
name = "openconnect" name = "openconnect"
version = "3.2.0" version = "3.3.1"
dependencies = [ dependencies = [
"autotools", "autotools",
"cc", "cc",
@@ -4880,16 +4882,6 @@ dependencies = [
"sha2 0.11.1", "sha2 0.11.1",
] ]
[[package]]
name = "sec1"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"
dependencies = [
"der",
"zeroize",
]
[[package]] [[package]]
name = "security-framework" name = "security-framework"
version = "3.7.0" version = "3.7.0"
+1 -2
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package] [workspace.package]
rust-version = "1.91" rust-version = "1.91"
version = "3.2.0" version = "3.3.1"
authors = ["Kevin Yue <[email protected]>"] authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect" homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024" edition = "2024"
@@ -24,7 +24,6 @@ base64 = { version = "0.23", default-features = false, features = ["std"] }
chrono = "0.4" chrono = "0.4"
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3" clap-verbosity-flag = "3"
ctrlc = "3.4"
directories = "6.0" directories = "6.0"
dns-lookup = "4.0.2" dns-lookup = "4.0.2"
env_logger = "0.11" env_logger = "0.11"
+97 -397
View File
@@ -1,6 +1,8 @@
# GlobalProtect-openconnect # GlobalProtect-openconnect
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. 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.
<p align="center"> <p align="center">
<picture> <picture>
@@ -22,147 +24,89 @@ A GlobalProtect VPN client built on OpenConnect with support for SSO authenticat
- [macOS](#macos) - [macOS](#macos)
- [Debian / Ubuntu](#debian--ubuntu) - [Debian / Ubuntu](#debian--ubuntu)
- [Arch Linux / Manjaro](#arch-linux--manjaro) - [Arch Linux / Manjaro](#arch-linux--manjaro)
- [Fedora 38+ / Rawhide](#fedora-38--rawhide) - [Fedora / RHEL](#fedora--rhel)
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed) - [openSUSE](#opensuse)
- [Other RPM-based Distributions](#other-rpm-based-distributions)
- [Alpine Linux](#alpine-linux) - [Alpine Linux](#alpine-linux)
- [FreeBSD](#freebsd) - [FreeBSD](#freebsd)
- [OpenBSD](#openbsd) - [OpenBSD](#openbsd)
- [Gentoo](#gentoo) - [Gentoo](#gentoo)
- [NixOS](#nixos) - [NixOS](#nixos)
- [Official Docker Image](#official-docker-image) - [Docker](#docker)
- [Other Distributions](#other-distributions) - [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source) - [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions) - [Troubleshooting](#troubleshooting)
- [NetworkManager Integration](#networkmanager-integration) - [NetworkManager Integration](#networkmanager-integration)
- [Licensing](#licensing) - [Licensing](#licensing)
## Features ## Features
- **Desktop Platform Support** – macOS, Linux, FreeBSD, and OpenBSD - **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD
- **Dual Interface** – Available as both CLI and GUI applications - **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**)
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication - **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface
- **Browser Integration** – Authenticate using your default browser or any specified browser - **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode
- **Multi-Portal Support** – Connect to multiple portals and gateways - **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login
- **Direct Gateway Connection** – Bypass portal selection when needed - **Automated HIP Reports** – Built-in HIP report generation or custom scripts
- **Auto-Connect** – Automatically connect on system startup - **Multi-Portal & Direct Gateway** – Manage multiple saved portals or connect directly to a gateway
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME) - **Desktop Integration** – Theme-aware system tray icon, auto-connect on launch, and reconnect on wake
## Usage ## Usage
### Command-Line Interface ### Command-Line Interface
The CLI is free and open source. Use it to authenticate, connect to portals or gateways, and generate HIP reports from the terminal. The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation:
#### Basic Commands
```bash ```bash
Usage: gpclient [OPTIONS] <COMMAND> # Connect to a portal server
sudo gpclient connect <portal>
Commands: # Connect using browser authentication (SSO / SAML)
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)
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
```
> **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 sudo gpclient connect <portal> --browser
# 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
``` ```
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. Run `gpclient --help` or `gpclient <command> --help` to view all available commands and options.
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 ### Graphical User Interface
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: - **macOS**: Open **GP Connect** from Applications.
- **Linux / BSD**: Launch GP Connect from your application menu or run:
```bash ```bash
gpclient launch-gui gpclient launch-gui
``` ```
> [!TIP] > [!TIP]
> **On Linux, try Native Shell for lower memory usage.** Switch to it in **Settings → General → Interface**. > **On Linux, try Native Shell for lower memory usage.** Switch between Native Shell and Tauri 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 ## 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 ### macOS
GP Connect requires Apple silicon and macOS 13 or later. The macOS app includes both the desktop application and the free `gpclient` CLI. The CLI does not require a GUI license. Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI.
#### Option 1: Install with Homebrew #### Option 1: Homebrew (Recommended)
```bash ```bash
brew install --cask yuezk/gp-connect/gp-connect brew install --cask yuezk/gp-connect/gp-connect
``` ```
Open GP Connect from Applications, or connect from the terminal: #### Option 2: DMG Installer
```bash Download the `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page and drag GP Connect into Applications.
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 ### Debian / Ubuntu
#### Option 1: Install from PPA (Recommended) #### Option 1: PPA (Recommended)
```bash ```bash
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
@@ -170,392 +114,152 @@ sudo apt-get update
sudo apt-get install globalprotect-openconnect sudo apt-get install globalprotect-openconnect
``` ```
> [!Note] #### Option 2: DEB Package
>
> **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
> ```
#### Option 2: Install from DEB Package Download the latest `.deb` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash ```bash
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb sudo apt install ./globalprotect-openconnect_*.deb
``` ```
### Arch Linux / Manjaro ### Arch Linux / Manjaro
#### Option 1: Install from AUR
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 ```bash
# Official Extra repository
sudo pacman -S globalprotect-openconnect
# AUR (git main)
yay -S globalprotect-openconnect-git yay -S globalprotect-openconnect-git
``` ```
#### Option 2: Install from the Official Extra Repository ### Fedora / RHEL
The package is also available in the official Arch Linux Extra repository. Enable the COPR 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 ```bash
sudo dnf copr enable yuezk/globalprotect-openconnect sudo dnf copr enable yuezk/globalprotect-openconnect
sudo dnf install globalprotect-openconnect sudo dnf install globalprotect-openconnect
``` ```
### openSUSE Leap 15.6+ / Tumbleweed ### openSUSE
#### 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 [OBS instructions](https://software.opensuse.org/download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution.
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 ### Alpine Linux
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install: Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash ```bash
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
``` ```
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`. *(Requires `community` repository enabled for WebKitGTK and AppIndicator dependencies).*
### FreeBSD ### FreeBSD
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install: Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash ```bash
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg 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 ### OpenBSD
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install: Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash ```bash
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz 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 ### Gentoo
Available via the `guru` and `lamdness` overlays: Available via the `guru` repository:
```bash ```bash
sudo eselect repository enable guru sudo eselect repository enable guru
sudo emerge --sync guru sudo emerge --sync guru
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect sudo emerge --ask net-vpn/GlobalProtect-openconnect
``` ```
### NixOS ### NixOS
This repository includes a flake for NixOS integration. Add the flake to your `flake.nix`:
#### 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 ```nix
{ {
inputs = { inputs.globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
# ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
};
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;
outputs = { self, nixpkgs, globalprotect-openconnect, ... }: {
nixosConfigurations.<hostname> = nixpkgs.lib.nixosSystem {
modules = [ modules = [
./configuration.nix
globalprotect-openconnect.nixosModules.default globalprotect-openconnect.nixosModules.default
{ {
programs.globalprotect-openconnect.enable = true; programs.globalprotect-openconnect.enable = true;
environment.systemPackages = [
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
];
} }
]; ];
}; };
}; }
} }
``` ```
Apply: Apply changes:
```bash ```bash
sudo nixos-rebuild switch sudo nixos-rebuild switch
loginctl terminate-user "$USER"
``` ```
After logging back in to GNOME, enable AppIndicator support if needed: ### Docker
```bash Run the CLI client in an official Alpine container:
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 ```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \ docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \ yuezk/globalprotect-openconnect:latest \
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 connect <portal> --browser manual
``` ```
On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine: *(Add `--network host` on Linux if VPN routes should apply to the host network).*
```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 ### Other Distributions
#### Manual Installation Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
1. **Install dependencies:** ```bash
- WebKitGTK 4.1 (for example, `libwebkit2gtk-4.1-0` on Debian/Ubuntu) tar -xJf globalprotect-openconnect_*.bin.tar.xz
- `libsecret` cd globalprotect-openconnect_*
- `libayatana-appindicator` or `libappindicator-gtk3` sudo make install
- 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 ## Building from Source
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). ### Prerequisites (Linux)
### Method 1: Using DevContainer - [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
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. *(For FreeBSD and OpenBSD instructions, see [Building from Source on FreeBSD and OpenBSD](docs/bsd-source-build.md)).*
#### Prerequisites ### Build Steps
- [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 ```bash
./target/release/gpclient --help git clone --recursive https://github.com/yuezk/GlobalProtect-openconnect.git
cd GlobalProtect-openconnect
make build
sudo make install
``` ```
### Build Options **Build Options:**
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper - `INCLUDE_GUI=1` – Download and install the matching desktop application bundle.
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external browser or manual authentication - `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication (uses external browser or manual mode).
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation - `BUILD_GUI_HELPER=0` – Skip building the helper UI.
- `OFFLINE=1` – Build in offline mode using vendored dependencies
## Frequently Asked Questions ## Troubleshooting
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. - **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.
### 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 ## NetworkManager Integration
@@ -564,14 +268,10 @@ On a headless server, use `--browser manual` and complete authentication from an
## Licensing ## Licensing
### Trial and Pricing - **CLI (`gpclient`)**: Free and open source (GPL-3.0).
- **GUI (GP Connect)**: Commercial desktop application with a free trial.
The **CLI version** is completely free and open source. ### Open Source Components
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 | | Component | Type | License |
|-----------|------|---------| |-----------|------|---------|
+59
View File
@@ -511,3 +511,62 @@ printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
); );
} }
} }
#[tokio::test]
async fn unsupported_and_malformed_identities_fail_before_password_prompt_or_network_connection() {
use gpapi::utils::request::RequestIdentityError;
let directory = tempfile::tempdir().unwrap();
let malformed = directory.path().join("invalid.p12");
std::fs::write(&malformed, b"not a certificate archive").unwrap();
let fixtures =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/gpapi/tests/files/client-identity");
for (certificate, key, expected) in [
(
fixtures.join("rsa-pss-cert.pem"),
Some(fixtures.join("rsa-pss.pem")),
"algorithm",
),
(fixtures.join("legacy-RC2-128.p12"), None, "encryption"),
(malformed, None, "malformed"),
] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let server = format!("https://{}", listener.local_addr().unwrap());
let mut argv = vec![
"test".to_owned(),
server,
"--as-gateway".to_owned(),
"--certificate".to_owned(),
certificate.to_string_lossy().into_owned(),
];
if let Some(key) = key {
argv.extend(["--sslkey".to_owned(), key.to_string_lossy().into_owned()]);
}
let args = TestArgs::parse_from(argv).connect;
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
ignore_tls_errors: false,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
let error = tokio::time::timeout(Duration::from_secs(2), handler.handle_attempt())
.await
.expect("identity failure must not wait for a password or server")
.unwrap_err();
match (expected, error.downcast_ref::<RequestIdentityError>()) {
("algorithm", Some(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"))) => {}
("encryption", Some(RequestIdentityError::UnsupportedEncryption)) => {}
("malformed", Some(RequestIdentityError::InvalidPkcs12(_) | RequestIdentityError::InvalidCertificate)) => {}
_ => panic!("{expected}: unexpected failure {error:#}"),
}
assert!(
tokio::time::timeout(Duration::from_millis(20), listener.accept())
.await
.is_err(),
"{expected}: local identity failure must precede network access"
);
}
}
+2 -3
View File
@@ -785,9 +785,8 @@ mod tests {
#[test] #[test]
fn explicit_hip_user_resolves_to_the_selected_account() { fn explicit_hip_user_resolves_to_the_selected_account() {
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap(); // Build sandboxes may use a UID without an entry in the user database.
let name = current.name().to_string_lossy().into_owned(); assert_eq!(get_uid(&Some("root".to_string())).unwrap(), Some(0));
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
} }
#[test] #[test]
+8 -2
View File
@@ -186,6 +186,8 @@ impl<'a> ConnectHandler<'a> {
match identity_error { match identity_error {
RequestIdentityError::UnsupportedEncryption RequestIdentityError::UnsupportedEncryption
| RequestIdentityError::UnsupportedKeyFormat | RequestIdentityError::UnsupportedKeyFormat
| RequestIdentityError::UnsupportedKeyAlgorithm(_)
| RequestIdentityError::KeyMismatch
| RequestIdentityError::InvalidKey | RequestIdentityError::InvalidKey
| RequestIdentityError::InvalidCertificate | RequestIdentityError::InvalidCertificate
| RequestIdentityError::IncompletePkcs12 | RequestIdentityError::IncompletePkcs12
@@ -206,8 +208,12 @@ impl<'a> ConnectHandler<'a> {
return Ok(()); return Ok(());
} }
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => { RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
let message = format!("Enter the {} passphrase:", cert_type); let message = if *cert_type == "PKCS#12" {
let password = Password::new(&message) "Enter the certificate file password:"
} else {
"Enter the private key password:"
};
let password = Password::new(message)
.without_confirmation() .without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked) .with_display_mode(PasswordDisplayMode::Masked)
.prompt()?; .prompt()?;
+45
View File
@@ -1,5 +1,50 @@
# Changelog # Changelog
## 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 ## 3.2.0
### Added ### Added
+12 -5
View File
@@ -8,7 +8,6 @@ license = "MIT"
[dependencies] [dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true } nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
common = { path = "../common" } common = { path = "../common" }
directories = { workspace = true, optional = true }
anyhow.workspace = true anyhow.workspace = true
base64.workspace = true base64.workspace = true
dns-lookup = { workspace = true, optional = true } dns-lookup = { workspace = true, optional = true }
@@ -16,8 +15,10 @@ log.workspace = true
reqwest.workspace = true reqwest.workspace = true
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2" rustls-pemfile = "2"
rustls-platform-verifier = "0.7"
p12-keystore = "0.4.1" p12-keystore = "0.4.1"
sec1 = { version = "0.8.1", default-features = false, features = ["der"] } pkcs12 = { version = "=0.2.0-pre.0", default-features = false }
cms = { version = "=0.3.0-pre.1", default-features = false }
pem.workspace = true pem.workspace = true
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] } pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
x509-cert = { version = "0.3", default-features = false } x509-cert = { version = "0.3", default-features = false }
@@ -43,7 +44,6 @@ chrono.workspace = true
humantime.workspace = true humantime.workspace = true
netdev = { workspace = true, optional = true } netdev = { workspace = true, optional = true }
socket2 = { version = "0.6", features = ["all"], optional = true } socket2 = { version = "0.6", features = ["all"], optional = true }
os_info = { version = "3", default-features = false, optional = true }
snow.workspace = true snow.workspace = true
zeroize = { workspace = true, features = ["serde"] } zeroize = { workspace = true, features = ["serde"] }
getrandom = "0.4" getrandom = "0.4"
@@ -64,8 +64,15 @@ oslog = { version = "0.2", default-features = false, optional = true }
gtk = { version = "0.18", optional = true } gtk = { version = "0.18", optional = true }
[target.'cfg(target_os="linux")'.dependencies] [target.'cfg(target_os="linux")'.dependencies]
directories = { workspace = true, optional = true }
libloading = { version = "0.9", optional = true } libloading = { version = "0.9", optional = true }
[target.'cfg(target_os="macos")'.dependencies]
os_info = { version = "3", default-features = false, optional = true }
[target.'cfg(target_os="windows")'.dependencies]
os_info = { version = "3", default-features = false }
[build-dependencies] [build-dependencies]
cc = "1" cc = "1"
pkg-config = "0.3" pkg-config = "0.3"
@@ -78,8 +85,8 @@ tokio = { workspace = true, features = ["test-util"] }
[features] [features]
default = ["desktop"] default = ["desktop"]
desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:os_info", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"] desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"]
tauri = ["desktop", "dep:tauri", "dep:gtk"] tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"] clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
webview-auth = [] webview-auth = []
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"] logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
+99 -10
View File
@@ -22,11 +22,23 @@ pub enum ServerTlsErrorKind {
} }
impl ServerTlsError { impl ServerTlsError {
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> { pub(crate) fn from_request(
Some(Self { server: &url::Url,
error: &(dyn Error + 'static),
has_client_identity: bool,
) -> Option<anyhow::Error> {
let kind = classify_with_identity(error, has_client_identity)?;
let error = anyhow::Error::new(Self {
server: server.origin().ascii_serialization(), server: server.origin().ascii_serialization(),
kind: classify(error)?, kind,
}) });
if has_client_identity && kind == ServerTlsErrorKind::ClientCertificateRequired {
Some(error.context(
"The VPN server could not use the configured client certificate. Check it with your VPN administrator",
))
} else {
Some(error)
}
} }
} }
@@ -60,6 +72,10 @@ impl ServerTlsErrorKind {
} }
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> { pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
classify_with_identity(error, false)
}
fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bool) -> Option<ServerTlsErrorKind> {
let mut source = Some(error); let mut source = Some(error);
while let Some(error) = source { while let Some(error) = source {
if let Some(tls) = error.downcast_ref::<ServerTlsError>() { if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
@@ -71,6 +87,14 @@ pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKi
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => { rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
ServerTlsErrorKind::ClientCertificateRequired ServerTlsErrorKind::ClientCertificateRequired
} }
rustls::Error::AlertReceived(
rustls::AlertDescription::BadCertificate
| rustls::AlertDescription::UnsupportedCertificate
| rustls::AlertDescription::CertificateRevoked
| rustls::AlertDescription::CertificateExpired
| rustls::AlertDescription::CertificateUnknown
| rustls::AlertDescription::UnknownCA,
) if has_client_identity => ServerTlsErrorKind::ClientCertificateRequired,
_ => ServerTlsErrorKind::Other, _ => ServerTlsErrorKind::Other,
}); });
} }
@@ -123,6 +147,39 @@ mod tests {
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None); assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
} }
#[test]
fn configured_identity_peer_errors_have_actionable_copy_without_becoming_server_trust_failures() {
let server = url::Url::parse("https://vpn.example.com/private/login").unwrap();
for alert in [
rustls::AlertDescription::CertificateRequired,
rustls::AlertDescription::BadCertificate,
rustls::AlertDescription::UnknownCA,
] {
let error = rustls::Error::AlertReceived(alert);
let configured = ServerTlsError::from_request(&server, &error, true).unwrap();
assert_eq!(
ServerTlsErrorKind::from_error(&configured),
Some(ServerTlsErrorKind::ClientCertificateRequired)
);
let message = configured.to_string();
assert!(
message.contains("configured client certificate") && message.contains("VPN administrator"),
"{message}"
);
assert!(
!message.contains("password") && !message.contains("passphrase"),
"{message}"
);
assert!(!message.contains("/private/login"));
}
let trust_error = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer);
let classified = ServerTlsError::from_request(&server, &trust_error, true).unwrap();
assert_eq!(
ServerTlsErrorKind::from_error(&classified),
Some(ServerTlsErrorKind::Certificate)
);
}
fn server(tls: bool) -> (String, thread::JoinHandle<()>) { fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
server_with_client_auth(tls, SslVerifyMode::NONE) server_with_client_auth(tls, SslVerifyMode::NONE)
} }
@@ -226,8 +283,8 @@ mod tests {
.await .await
.unwrap_err(); .unwrap_err();
worker.join().unwrap(); worker.join().unwrap();
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap(); let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error, false).unwrap();
assert_eq!(tls.kind, ServerTlsErrorKind::Other); assert_eq!(ServerTlsErrorKind::from_error(&tls), Some(ServerTlsErrorKind::Other));
} }
#[tokio::test] #[tokio::test]
@@ -314,6 +371,38 @@ mod tests {
} }
} }
#[tokio::test]
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
utils::request::ClientIdentity,
};
let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/client-identity");
let identity = ClientIdentity::load(
fixtures.join("rsa-critical-extension.pem").to_str().unwrap(),
Some(fixtures.join("rsa-pkcs8.pem").to_str().unwrap()),
None,
)
.unwrap();
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()))
.client_identity(Some(identity))
.ignore_tls_errors(true)
.build();
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
let error = prelogin(&address, &params, PreloginOptions::default())
.await
.unwrap_err();
worker.join().unwrap();
assert_eq!(
ServerTlsErrorKind::from_error(&error),
Some(ServerTlsErrorKind::ClientCertificateRequired)
);
assert!(error.to_string().contains("configured client certificate"), "{error:#}");
assert!(!error.to_string().contains("passphrase"));
}
#[tokio::test] #[tokio::test]
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() { async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
use crate::{ use crate::{
@@ -411,10 +500,10 @@ mod tests {
.await .await
.unwrap_err(); .unwrap_err();
assert_eq!( assert_eq!(
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error) ServerTlsErrorKind::from_error(
.unwrap() &ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error, false).unwrap()
.kind, ),
ServerTlsErrorKind::Certificate Some(ServerTlsErrorKind::Certificate)
); );
} }
+102 -7
View File
@@ -18,7 +18,7 @@ use crate::{
gp_params::GpParams, gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput}, params::gateway_login::{self, GatewayLoginInput},
session::GatewayAuthentication, session::GatewayAuthentication,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, redact::redact_uri, remove_url_scheme, xml::ElementExt},
}; };
pub enum GatewayLogin { pub enum GatewayLogin {
@@ -181,14 +181,14 @@ async fn receive_gateway_login(
log_gateway_login_context(context, client_ip, gp_params); log_gateway_login_context(context, client_ip, gp_params);
let res = client let res = client
.post(login_url) .post(&login_url)
.form(&request_params.body) .form(&request_params.body)
.send() .send()
.await .await
.map_err(|e| { .map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match crate::error::ServerTlsError::from_request(origin, &e) { match crate::error::ServerTlsError::from_request(origin, &e, gp_params.has_client_identity()) {
Some(tls) => anyhow::anyhow!(tls), Some(tls) => tls,
None => anyhow::anyhow!(PortalError::NetworkError(e)), None => anyhow::anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
@@ -200,14 +200,30 @@ async fn receive_gateway_login(
.map(<[u8]>::to_vec); .map(<[u8]>::to_vec);
let endpoint = res.remote_addr(); let endpoint = res.remote_addr();
let url = res.url().clone(); let url = res.url().clone();
let http_version = res.version();
let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned();
let res = parse_gp_response(res).await.map_err(|err| { let res = parse_gp_response(res).await.map_err(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) { // Redirect paths and query strings can contain authentication tokens. Log
return anyhow::anyhow!(tls); // only the redacted origin and whether the response is from the login path.
warn!(
"Gateway login response failed: status={}, reason={}, http={:?}, origin={}, port={:?}, redirected={}, login_endpoint={}, content_type={:?}, client_certificate={}, ignore_tls_errors={}",
err.status,
err.reason,
http_version,
redact_uri(&url.origin().ascii_serialization()),
url.port_or_known_default(),
url.as_str() != login_url,
url.path() == "/ssl-vpn/login.esp",
content_type,
gp_params.has_client_identity(),
gp_params.ignore_tls_errors(),
);
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) {
return tls;
} }
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
return anyhow::anyhow!(crate::error::AuthenticationRejected); return anyhow::anyhow!(crate::error::AuthenticationRejected);
} }
warn!("Gateway login response failed: {}", err.reason);
anyhow::anyhow!("Gateway login error: {}", err.reason) anyhow::anyhow!("Gateway login error: {}", err.reason)
})?; })?;
@@ -429,6 +445,85 @@ mod tests {
.build() .build()
} }
#[tokio::test]
async fn failed_login_logs_http_context_without_credentials_or_redirect_tokens() {
use std::cell::RefCell;
thread_local! {
static MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
struct Logger;
impl log::Log for Logger {
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
true
}
fn log(&self, record: &log::Record<'_>) {
let message = record.args().to_string();
if message.starts_with("Gateway login response failed:") {
MESSAGES.with_borrow_mut(|messages| messages.push(message));
}
}
fn flush(&self) {}
}
log::set_logger(&Logger).unwrap();
log::set_max_level(log::LevelFilter::Warn);
for (status, reason, redirected) in [
(403, None, false),
(502, None, true),
(401, Some("access denied"), false),
] {
let body = "<html>response-body-secret</html>";
let mut responses = Vec::new();
if redirected {
responses.push(
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /path-secret?token=query-secret\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
);
}
let reason_header = reason
.map(|reason| format!("x-private-pan-globalprotect: {reason}\r\n"))
.unwrap_or_default();
responses.push(format!(
"HTTP/1.1 {status} Error\r\nContent-Type: text/html\r\nSet-Cookie: cookie-secret\r\n{reason_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
));
let (_, origin, server) = crate::session::transport::tests::login_gateway(responses).await;
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("username-secret", "password-secret").into();
let error = client
.login(&credential, None, &CancellationToken::new())
.await
.err()
.unwrap();
server.await.unwrap();
assert_eq!(
error.to_string(),
format!("Gateway login error: {}", reason.unwrap_or("<none>"))
);
let messages = MESSAGES.with_borrow_mut(std::mem::take);
assert_eq!(messages.len(), 1);
let message = &messages[0];
for expected in [
format!("status={status}"),
format!("reason={}", reason.unwrap_or("<none>")),
format!("port={:?}", origin.port()),
format!("redirected={redirected}"),
format!("login_endpoint={}", !redirected),
"http=HTTP/1.1".into(),
"content_type=Some(\"text/html\")".into(),
"client_certificate=false".into(),
"ignore_tls_errors=false".into(),
] {
assert!(message.contains(&expected), "missing {expected}: {message}");
}
assert!(!message.contains("secret"), "sensitive data in diagnostic: {message}");
assert!(!message.contains("127.0.0.1"), "unredacted origin: {message}");
}
}
#[tokio::test] #[tokio::test]
async fn gateway_login_cancels_stalled_headers_and_body() { async fn gateway_login_cancels_stalled_headers_and_body() {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
+13 -13
View File
@@ -6,7 +6,7 @@ use zeroize::Zeroize;
use crate::{ use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile}, os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::{ClientIdentity, create_identity}, utils::request::ClientIdentity,
}; };
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)] #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
@@ -160,21 +160,21 @@ impl GpParams {
self.prepared_identity.as_ref() self.prepared_identity.as_ref()
} }
pub(crate) fn has_client_identity(&self) -> bool {
self.prepared_identity.is_some() || self.certificate.is_some()
}
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> { pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
let mut builder = crate::utils::request::client_builder() let builder = if let Some(identity) = &self.prepared_identity {
.tls_info(true) identity.client_builder(self.ignore_tls_errors)?
.danger_accept_invalid_certs(self.ignore_tls_errors)
.user_agent(self.user_agent());
if let Some(identity) = &self.prepared_identity {
builder = builder.identity(identity.request_identity());
} else if let Some(cert) = self.certificate.as_deref() { } else if let Some(cert) = self.certificate.as_deref() {
info!("Using client certificate authentication..."); info!("Using client certificate authentication...");
builder = builder.identity(create_identity( ClientIdentity::load(cert, self.sslkey.as_deref(), self.key_password.as_deref())?
cert, .client_builder(self.ignore_tls_errors)?
self.sslkey.as_deref(), } else {
self.key_password.as_deref(), crate::utils::request::client_builder().danger_accept_invalid_certs(self.ignore_tls_errors)
)?); };
} let builder = builder.tls_info(true).user_agent(self.user_agent());
Ok(builder) Ok(builder)
} }
} }
+8 -8
View File
@@ -201,15 +201,15 @@ pub async fn retrieve_config(
result = async { result = async {
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| { let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match ServerTlsError::from_request(&server_url, &e) { match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
Some(tls) => anyhow::anyhow!(tls), Some(tls) => tls,
None => anyhow::anyhow!(PortalError::NetworkError(e)), None => anyhow::anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
parse_gp_response(res).await.or_else(|err| { parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
return Err(anyhow::anyhow!(tls)); return Err(tls);
} }
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected)); return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
@@ -274,15 +274,15 @@ async fn retrieve_csc_config(
let res = client.post(&url).form(&params).send().await.map_err(|e| { let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match ServerTlsError::from_request(&server_url, &e) { match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
Some(tls) => anyhow::anyhow!(tls), Some(tls) => tls,
None => anyhow::anyhow!(PortalError::NetworkError(e)), None => anyhow::anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
parse_gp_response(res).await.or_else(|err| { parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
return Err(anyhow::anyhow!(tls)); return Err(tls);
} }
if err.status == StatusCode::NOT_FOUND { if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string())); bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
+4 -4
View File
@@ -152,15 +152,15 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
let res = request.send().await.map_err(|e| { let res = request.send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
match crate::error::ServerTlsError::from_request(&server_url, &e) { match crate::error::ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) {
Some(error) => anyhow!(error), Some(error) => error,
None => anyhow!(PortalError::NetworkError(e)), None => anyhow!(PortalError::NetworkError(e)),
} }
})?; })?;
let res_xml = parse_gp_response(res).await.or_else(|err| { let res_xml = parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) { if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) {
return Err(anyhow!(tls)); return Err(tls);
} }
if err.status == StatusCode::NOT_FOUND { if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string())) bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
+1
View File
@@ -72,6 +72,7 @@ impl SwitchListener {
self.directory.path().join("control") self.directory.path().join("control")
} }
#[cfg(target_os = "linux")]
pub async fn ready(&self) -> anyhow::Result<()> { pub async fn ready(&self) -> anyhow::Result<()> {
let (mut socket, _) = self.listener.accept().await?; let (mut socket, _) = self.listener.accept().await?;
anyhow::ensure!( anyhow::ensure!(
@@ -0,0 +1,133 @@
//! Client identity capabilities, separate from peer certificate policy.
use pkcs8::{
ObjectIdentifier, PrivateKeyInfoRef,
der::{
Decode, Reader, Tag, TagNumber, Tagged,
asn1::{AnyRef, BitStringRef, ContextSpecific, OctetStringRef},
},
};
use rustls::pki_types::PrivateKeyDer;
use crate::utils::request::RequestIdentityError;
#[cfg(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
))]
#[path = "native_key.rs"]
mod implementation;
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
#[path = "portable_key.rs"]
mod implementation;
pub(in crate::utils) use implementation::ClientKey;
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
const EC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
const ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
const ED448: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.113");
const P521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
const DSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10040.4.1");
fn validate_algorithm(oid: ObjectIdentifier) -> Result<(), RequestIdentityError> {
match oid {
RSA | EC | ED25519 => Ok(()),
RSA_PSS => Err(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS")),
ED448 => Err(RequestIdentityError::UnsupportedKeyAlgorithm("Ed448")),
DSA => Err(RequestIdentityError::UnsupportedKeyAlgorithm("DSA")),
_ => Err(RequestIdentityError::UnsupportedKeyAlgorithm(
"an unknown key algorithm",
)),
}
}
fn validate_ec_parameters(parameters: Option<AnyRef<'_>>) -> Result<(), RequestIdentityError> {
if let Some(parameters) = parameters {
if parameters.tag() == Tag::ObjectIdentifier {
let curve = parameters
.decode_as::<ObjectIdentifier>()
.map_err(|_| RequestIdentityError::InvalidKey)?;
if curve == P521 {
return Err(RequestIdentityError::UnsupportedKeyAlgorithm("P-521"));
}
return Ok(());
}
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(
"EC with explicit parameters",
));
}
Ok(())
}
fn validate_ec_point(point: &[u8]) -> Result<(), RequestIdentityError> {
if matches!(point.first(), Some(2 | 3)) {
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(
"EC with compressed public keys",
));
}
Ok(())
}
fn validate_sec1(bytes: &[u8]) -> anyhow::Result<()> {
let (parameters, point) = AnyRef::from_der(bytes)
.and_then(|sequence| {
sequence.sequence(|reader| {
let version: u8 = reader.decode()?;
if version != 1 {
return Err(reader.error(Tag::Integer.value_error()));
}
let _: &OctetStringRef = reader.decode()?;
let parameters = ContextSpecific::<AnyRef<'_>>::decode_explicit(reader, TagNumber(0))?.map(|field| field.value);
let point =
ContextSpecific::<BitStringRef<'_>>::decode_explicit(reader, TagNumber(1))?.map(|field| field.value);
Ok((parameters, point))
})
})
.map_err(|_| RequestIdentityError::InvalidKey)?;
validate_ec_parameters(parameters)?;
if let Some(point) = point {
validate_ec_point(point.as_bytes().ok_or(RequestIdentityError::InvalidKey)?)?;
}
Ok(())
}
pub(super) fn validate_private_key(key: &PrivateKeyDer<'_>) -> anyhow::Result<()> {
match key {
PrivateKeyDer::Pkcs8(key) => {
let info = PrivateKeyInfoRef::from_der(key.secret_pkcs8_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
validate_algorithm(info.algorithm.oid)?;
if info.algorithm.oid == EC {
validate_ec_parameters(info.algorithm.parameters)?;
validate_sec1(info.private_key.as_bytes())?;
}
}
PrivateKeyDer::Sec1(key) => validate_sec1(key.secret_sec1_der())?,
PrivateKeyDer::Pkcs1(_) => {}
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
}
Ok(())
}
pub(in crate::utils) fn validate_certificate(bytes: &[u8]) -> anyhow::Result<()> {
let certificate = x509_cert::Certificate::from_der(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)?;
let public_key = certificate.tbs_certificate().subject_public_key_info();
validate_algorithm(public_key.algorithm.oid)?;
if public_key.algorithm.oid == EC {
validate_ec_parameters(public_key.algorithm.parameters.as_ref().map(|value| value.into()))?;
validate_ec_point(
public_key
.subject_public_key
.as_bytes()
.ok_or(RequestIdentityError::InvalidCertificate)?,
)?;
}
Ok(())
}
+269
View File
@@ -44,3 +44,272 @@ void gp_key_free(unsigned char *data, size_t length) {
gnutls_free(data); gnutls_free(data);
} }
} }
#include <gnutls/abstract.h>
#include <stdlib.h>
#include <string.h>
/* Check only the signature, not whether this local certificate is trusted,
* current, or has extensions understood by the client. */
int gp_certificate_verify_signature(
const unsigned char *certificate, size_t certificate_length,
const unsigned char *issuer_key, size_t issuer_key_length,
const unsigned char *message, size_t message_length,
const unsigned char *signature, size_t signature_length) {
gnutls_x509_crt_t child = NULL;
gnutls_pubkey_t public_key = NULL;
int result, algorithm;
if (certificate_length > UINT_MAX || issuer_key_length > UINT_MAX ||
message_length > UINT_MAX || signature_length > UINT_MAX) return -1;
result = gnutls_global_init();
if (result < 0) return -1;
gnutls_datum_t child_data = {(unsigned char *)certificate, (unsigned int)certificate_length};
gnutls_datum_t key_data = {(unsigned char *)issuer_key, (unsigned int)issuer_key_length};
gnutls_datum_t data = {(unsigned char *)message, (unsigned int)message_length};
gnutls_datum_t sig = {(unsigned char *)signature, (unsigned int)signature_length};
result = gnutls_x509_crt_init(&child);
if (result >= 0) result = gnutls_x509_crt_import(child, &child_data, GNUTLS_X509_FMT_DER);
if (result >= 0) result = gnutls_pubkey_init(&public_key);
if (result >= 0) result = gnutls_pubkey_import(public_key, &key_data, GNUTLS_X509_FMT_DER);
if (result >= 0) {
algorithm = gnutls_x509_crt_get_signature_algorithm(child);
if (algorithm < 0) result = algorithm;
else result = gnutls_pubkey_verify_data2(public_key, algorithm,
GNUTLS_VERIFY_ALLOW_BROKEN | GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1, &data, &sig) >= 0;
}
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
if (child != NULL) gnutls_x509_crt_deinit(child);
gnutls_global_deinit();
return result < 0 ? -1 : result;
}
/* Stable private kinds, independent of the native enum values. */
struct gp_client_key {
gnutls_privkey_t signer;
gnutls_pubkey_t public_key;
};
void gp_client_key_delete(struct gp_client_key *key) {
if (key == NULL) return;
if (key->public_key != NULL) gnutls_pubkey_deinit(key->public_key);
if (key->signer != NULL) gnutls_privkey_deinit(key->signer);
free(key);
gnutls_global_deinit();
}
int gp_client_key_new(const unsigned char *data, size_t length, int *kind,
struct gp_client_key **output) {
gnutls_x509_privkey_t input = NULL;
struct gp_client_key *key = NULL;
int result, algorithm;
*output = NULL;
*kind = 9;
if (length > UINT_MAX || gnutls_global_init() < 0) return 1;
key = calloc(1, sizeof(*key));
if (key == NULL) { gnutls_global_deinit(); return 1; }
result = gnutls_x509_privkey_init(&input);
if (result >= 0) {
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
result = gnutls_x509_privkey_import2(input, &bytes, GNUTLS_X509_FMT_DER, NULL, 0);
}
if (result < 0) goto invalid;
algorithm = gnutls_x509_privkey_get_pk_algorithm(input);
if (algorithm == GNUTLS_PK_RSA_PSS) { *kind = 5; goto unsupported; }
if (algorithm == GNUTLS_PK_DSA) { *kind = 7; goto unsupported; }
if (algorithm == GNUTLS_PK_EDDSA_ED448) { *kind = 8; goto unsupported; }
result = gnutls_privkey_init(&key->signer);
if (result < 0) goto invalid;
result = gnutls_privkey_import_x509(key->signer, input, GNUTLS_PRIVKEY_IMPORT_COPY);
if (result < 0) goto invalid;
result = gnutls_pubkey_init(&key->public_key);
if (result < 0) goto invalid;
result = gnutls_pubkey_import_privkey(key->public_key, key->signer, 0, 0);
if (result < 0) goto invalid;
if (algorithm == GNUTLS_PK_RSA) *kind = 0;
else if (algorithm == GNUTLS_PK_EDDSA_ED25519) *kind = 4;
else if (algorithm == GNUTLS_PK_ECDSA) {
gnutls_ecc_curve_t curve;
gnutls_datum_t x = {NULL, 0}, y = {NULL, 0};
result = gnutls_pubkey_export_ecc_raw(key->public_key, &curve, &x, &y);
gnutls_free(x.data);
gnutls_free(y.data);
if (result < 0) goto invalid;
if (curve == GNUTLS_ECC_CURVE_SECP256R1) *kind = 1;
else if (curve == GNUTLS_ECC_CURVE_SECP384R1) *kind = 2;
else if (curve == GNUTLS_ECC_CURVE_SECP521R1) { *kind = 3; goto unsupported; }
else { *kind = 6; goto unsupported; }
} else goto unsupported;
gnutls_x509_privkey_deinit(input);
*output = key;
return 0;
unsupported:
if (input != NULL) gnutls_x509_privkey_deinit(input);
gp_client_key_delete(key);
return 2;
invalid:
if (input != NULL) gnutls_x509_privkey_deinit(input);
gp_client_key_delete(key);
return 1;
}
int gp_client_key_public(struct gp_client_key *key, unsigned char **output, size_t *length) {
gnutls_datum_t bytes = {NULL, 0};
int result = gnutls_pubkey_export2(key->public_key, GNUTLS_X509_FMT_DER, &bytes);
*output = bytes.data;
*length = bytes.size;
return result;
}
int gp_client_key_matches(struct gp_client_key *key, const unsigned char *data, size_t length) {
gnutls_x509_crt_t certificate = NULL;
gnutls_pubkey_t public_key = NULL;
unsigned char key_id[32], cert_id[32];
size_t key_id_length = sizeof(key_id), cert_id_length = sizeof(cert_id);
int result;
if (length > UINT_MAX) return -1;
result = gnutls_x509_crt_init(&certificate);
if (result >= 0) {
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
result = gnutls_x509_crt_import(certificate, &bytes, GNUTLS_X509_FMT_DER);
}
if (result >= 0) result = gnutls_pubkey_init(&public_key);
if (result >= 0) result = gnutls_pubkey_import_x509(public_key, certificate, 0);
if (result >= 0) result = gnutls_pubkey_get_key_id(key->public_key, GNUTLS_KEYID_USE_SHA256, key_id, &key_id_length);
if (result >= 0) result = gnutls_pubkey_get_key_id(public_key, GNUTLS_KEYID_USE_SHA256, cert_id, &cert_id_length);
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
if (certificate != NULL) gnutls_x509_crt_deinit(certificate);
if (result < 0) return result;
return key_id_length == cert_id_length && !memcmp(key_id, cert_id, key_id_length);
}
int gp_client_key_sign(struct gp_client_key *key, unsigned short scheme,
const unsigned char *message, size_t length,
unsigned char **output, size_t *output_length) {
gnutls_sign_algorithm_t algorithm;
unsigned int flags = 0;
*output = NULL;
*output_length = 0;
if (length > UINT_MAX) return -1;
switch (scheme) {
case 0x0804: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA256; break;
case 0x0805: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA384; break;
case 0x0806: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA512; break;
case 0x0401: algorithm = GNUTLS_SIGN_RSA_SHA256; break;
case 0x0501: algorithm = GNUTLS_SIGN_RSA_SHA384; break;
case 0x0601: algorithm = GNUTLS_SIGN_RSA_SHA512; break;
case 0x0403: algorithm = GNUTLS_SIGN_ECDSA_SECP256R1_SHA256; break;
case 0x0503: algorithm = GNUTLS_SIGN_ECDSA_SECP384R1_SHA384; break;
case 0x0807: algorithm = GNUTLS_SIGN_EDDSA_ED25519; break;
default: return -1;
}
if (scheme >= 0x0804 && scheme <= 0x0806)
flags = GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH;
gnutls_datum_t bytes = {(unsigned char *)message, (unsigned int)length};
gnutls_datum_t signature = {NULL, 0};
int result = gnutls_privkey_sign_data2(key->signer, algorithm, flags, &bytes, &signature);
*output = signature.data;
*output_length = signature.size;
return result;
}
#include <gnutls/pkcs12.h>
#include <stdint.h>
/* Invoked only after Rust has identified the supported RC4 archive scheme.
* Integrity and identity-count checks precede the native leaf selection. */
int gp_pkcs12_identity(const unsigned char *input, size_t length, const char *password,
unsigned char **certificate, size_t *certificate_length,
unsigned char **private_key, size_t *private_key_length) {
gnutls_pkcs12_t archive = NULL;
gnutls_x509_privkey_t key = NULL;
gnutls_x509_crt_t *chain = NULL, *extra = NULL;
unsigned int chain_length = 0, extra_length = 0;
gnutls_datum_t exported_key = {NULL, 0};
unsigned int key_count = 0, cert_count = 0;
int result, status = 5;
*certificate = NULL;
*certificate_length = 0;
*private_key = NULL;
*private_key_length = 0;
if (length > UINT_MAX || gnutls_global_init() < 0) return 5;
result = gnutls_pkcs12_init(&archive);
if (result >= 0) {
gnutls_datum_t bytes = {(unsigned char *)input, (unsigned int)length};
result = gnutls_pkcs12_import(archive, &bytes, GNUTLS_X509_FMT_DER, 0);
}
if (result < 0) goto out;
result = gnutls_pkcs12_verify_mac(archive, password);
if (result == GNUTLS_E_MAC_VERIFY_FAILED) { status = 1; goto out; }
if (result < 0 && result != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) goto out;
for (int index = 0; ; index++) {
gnutls_pkcs12_bag_t bag;
result = gnutls_pkcs12_bag_init(&bag);
if (result < 0) goto out;
result = gnutls_pkcs12_get_bag(archive, index, bag);
if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
gnutls_pkcs12_bag_deinit(bag);
break;
}
if (result >= 0 && gnutls_pkcs12_bag_get_type(bag, 0) == GNUTLS_BAG_ENCRYPTED)
result = gnutls_pkcs12_bag_decrypt(bag, password);
if (result < 0) {
gnutls_pkcs12_bag_deinit(bag);
if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1;
else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4;
goto out;
}
int count = gnutls_pkcs12_bag_get_count(bag);
if (count < 0) { gnutls_pkcs12_bag_deinit(bag); goto out; }
for (int item = 0; item < count; item++) {
int type = gnutls_pkcs12_bag_get_type(bag, item);
if (type == GNUTLS_BAG_PKCS8_KEY || type == GNUTLS_BAG_PKCS8_ENCRYPTED_KEY) key_count++;
if (type == GNUTLS_BAG_CERTIFICATE) cert_count++;
}
gnutls_pkcs12_bag_deinit(bag);
}
if (key_count == 0 || cert_count == 0) { status = 2; goto out; }
if (key_count != 1) { status = 3; goto out; }
result = gnutls_pkcs12_simple_parse(archive, password, &key, &chain, &chain_length,
&extra, &extra_length, NULL, GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED);
if (result < 0) {
if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1;
else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4;
else if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) status = 6;
goto out;
}
if (key == NULL || chain_length == 0) { status = 2; goto out; }
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER, NULL, GNUTLS_PKCS_PLAIN, &exported_key);
if (result < 0) goto out;
for (unsigned int index = 0; index < chain_length; index++) {
gnutls_datum_t part = {NULL, 0};
result = gnutls_x509_crt_export2(chain[index], GNUTLS_X509_FMT_PEM, &part);
if (result < 0) goto out;
if (part.size > SIZE_MAX - *certificate_length) { gnutls_free(part.data); goto out; }
unsigned char *buffer = gnutls_realloc(*certificate, *certificate_length + part.size);
if (buffer == NULL) { gnutls_free(part.data); goto out; }
memcpy(buffer + *certificate_length, part.data, part.size);
*certificate = buffer;
*certificate_length += part.size;
gnutls_free(part.data);
}
*private_key = exported_key.data;
*private_key_length = exported_key.size;
exported_key.data = NULL;
exported_key.size = 0;
status = 0;
out:
if (status != 0) {
gp_key_free(*certificate, *certificate_length);
*certificate = NULL;
*certificate_length = 0;
}
gp_key_free(exported_key.data, exported_key.size);
if (key != NULL) gnutls_x509_privkey_deinit(key);
for (unsigned int index = 0; index < chain_length; index++) gnutls_x509_crt_deinit(chain[index]);
for (unsigned int index = 0; index < extra_length; index++) gnutls_x509_crt_deinit(extra[index]);
gnutls_free(chain);
gnutls_free(extra);
if (archive != NULL) gnutls_pkcs12_deinit(archive);
gnutls_global_deinit();
return status;
}
@@ -1,11 +1,22 @@
use std::ffi::{c_char, c_int}; use std::ffi::{c_char, c_int};
use pkcs8::SecretDocument; use pkcs8::SecretDocument;
use pkcs8::der::{Encode, asn1::ObjectIdentifier};
use zeroize::Zeroizing; use zeroize::Zeroizing;
use crate::utils::request::RequestIdentityError; use crate::utils::request::RequestIdentityError;
unsafe extern "C" { unsafe extern "C" {
fn gp_certificate_verify_signature(
certificate: *const u8,
certificate_length: usize,
issuer_key: *const u8,
issuer_key_length: usize,
message: *const u8,
message_length: usize,
signature: *const u8,
signature_length: usize,
) -> c_int;
fn gp_key_import( fn gp_key_import(
input: *const u8, input: *const u8,
length: usize, length: usize,
@@ -14,9 +25,58 @@ unsafe extern "C" {
output: *mut *mut u8, output: *mut *mut u8,
output_length: *mut usize, output_length: *mut usize,
) -> c_int; ) -> c_int;
fn gp_pkcs12_identity(
input: *const u8,
length: usize,
password: *const c_char,
certificate: *mut *mut u8,
certificate_length: *mut usize,
key: *mut *mut u8,
key_length: *mut usize,
) -> c_int;
fn gp_key_free(data: *mut u8, length: usize); fn gp_key_free(data: *mut u8, length: usize);
} }
pub(super) fn verify_certificate_signature(
certificate: &x509_cert::Certificate,
issuer: &x509_cert::Certificate,
message: &[u8],
signature: &[u8],
) -> anyhow::Result<bool> {
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
let mut issuer_key = issuer.tbs_certificate().subject_public_key_info().clone();
if certificate.signature_algorithm().oid == RSA_PSS {
if !matches!(issuer_key.algorithm.oid, RSA | RSA_PSS) {
return Ok(false);
}
// GnuTLS's generic verifier takes PSS parameters from the imported key.
// Give this verification operation the certificate's full AlgorithmIdentifier,
// including salt length, rather than the default implied by its signature enum.
// This temporary SPKI never changes the certificates sent to the server.
issuer_key.algorithm = certificate.signature_algorithm().clone();
}
let issuer_key = issuer_key.to_der()?;
let certificate = certificate.to_der()?;
let result = unsafe {
gp_certificate_verify_signature(
certificate.as_ptr(),
certificate.len(),
issuer_key.as_ptr(),
issuer_key.len(),
message.as_ptr(),
message.len(),
signature.as_ptr(),
signature.len(),
)
};
match result {
0 => Ok(false),
1 => Ok(true),
_ => Err(RequestIdentityError::InvalidCertificate.into()),
}
}
struct ExportedKey { struct ExportedKey {
data: *mut u8, data: *mut u8,
length: usize, length: usize,
@@ -64,3 +124,55 @@ pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str
_ => Err(RequestIdentityError::InvalidKey.into()), _ => Err(RequestIdentityError::InvalidKey.into()),
} }
} }
pub(in crate::utils) fn archive(
bytes: &[u8],
passphrase: Option<&str>,
) -> anyhow::Result<(Zeroizing<Vec<u8>>, SecretDocument)> {
let mut password = Zeroizing::new(passphrase.unwrap_or_default().as_bytes().to_vec());
anyhow::ensure!(
!password.contains(&0),
"PKCS#12 passphrases containing NUL are not supported"
);
password.push(0);
let mut certificate = ExportedKey {
data: std::ptr::null_mut(),
length: 0,
};
let mut key = ExportedKey {
data: std::ptr::null_mut(),
length: 0,
};
let result = unsafe {
gp_pkcs12_identity(
bytes.as_ptr(),
bytes.len(),
password.as_ptr().cast(),
&mut certificate.data,
&mut certificate.length,
&mut key.data,
&mut key.length,
)
};
match result {
0 => {
anyhow::ensure!(
!certificate.data.is_null() && certificate.length > 0,
"Invalid certificate file"
);
anyhow::ensure!(!key.data.is_null() && key.length > 0, "Invalid private key");
let certificate =
Zeroizing::new(unsafe { std::slice::from_raw_parts(certificate.data, certificate.length) }.to_vec());
let key = SecretDocument::try_from(unsafe { std::slice::from_raw_parts(key.data, key.length) })
.map_err(|_| RequestIdentityError::InvalidKey)?;
Ok((certificate, key))
}
1 if passphrase.is_none() => Err(RequestIdentityError::NoPassphrase("PKCS#12").into()),
1 => Err(RequestIdentityError::InvalidPkcs12(p12_keystore::error::Error::InvalidData).into()),
2 => Err(RequestIdentityError::IncompletePkcs12.into()),
3 => Err(RequestIdentityError::AmbiguousPkcs12.into()),
4 => Err(RequestIdentityError::UnsupportedEncryption.into()),
6 => Err(RequestIdentityError::KeyMismatch.into()),
_ => Err(RequestIdentityError::InvalidCertificate.into()),
}
}
@@ -0,0 +1,18 @@
use pkcs8::der::{Decode, Encode};
use crate::utils::request::RequestIdentityError;
/// Identify the signing issuer, without applying trust, expiry or extension policy
/// to a local identity. The VPN server remains responsible for those checks.
pub(super) fn is_issuer(certificate: &[u8], issuer: &[u8]) -> anyhow::Result<bool> {
let child = x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
let parent = x509_cert::Certificate::from_der(issuer).map_err(|_| RequestIdentityError::InvalidCertificate)?;
if child.tbs_certificate().issuer() != parent.tbs_certificate().subject() {
return Ok(false);
}
let signature = child
.signature()
.as_bytes()
.ok_or(RequestIdentityError::InvalidCertificate)?;
super::platform_import::verify_certificate_signature(&child, &parent, &child.tbs_certificate().to_der()?, signature)
}
+9 -4
View File
@@ -1,4 +1,9 @@
mod client_key;
mod issuer;
pub(super) use client_key::{ClientKey, validate_certificate};
pub(super) mod pkcs12; pub(super) mod pkcs12;
mod pkcs12_format;
#[cfg(any( #[cfg(any(
target_os = "macos", target_os = "macos",
@@ -7,14 +12,14 @@ pub(super) mod pkcs12;
target_os = "openbsd" target_os = "openbsd"
))] ))]
#[path = "gnutls.rs"] #[path = "gnutls.rs"]
mod legacy_key; mod platform_import;
#[cfg(not(any( #[cfg(not(any(
target_os = "macos", target_os = "macos",
target_os = "linux", target_os = "linux",
target_os = "freebsd", target_os = "freebsd",
target_os = "openbsd" target_os = "openbsd"
)))] )))]
#[path = "unsupported.rs"] #[path = "portable_import.rs"]
mod legacy_key; mod platform_import;
pub(super) use legacy_key::decrypt as decrypt_key; pub(super) use platform_import::{archive, decrypt as decrypt_key};
@@ -0,0 +1,307 @@
use std::{
ffi::{c_int, c_void},
fmt,
ptr::NonNull,
sync::{Arc, Mutex},
};
use crate::utils::request::RequestIdentityError;
use rustls::{
SignatureAlgorithm, SignatureScheme,
pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer},
sign::{Signer, SigningKey},
};
unsafe extern "C" {
fn gp_client_key_new(data: *const u8, length: usize, kind: *mut c_int, output: *mut *mut c_void) -> c_int;
fn gp_client_key_delete(key: *mut c_void);
fn gp_client_key_public(key: *mut c_void, output: *mut *mut u8, length: *mut usize) -> c_int;
fn gp_client_key_matches(key: *mut c_void, cert: *const u8, length: usize) -> c_int;
fn gp_client_key_sign(
key: *mut c_void,
scheme: u16,
message: *const u8,
length: usize,
output: *mut *mut u8,
output_length: *mut usize,
) -> c_int;
fn gp_key_free(data: *mut u8, length: usize);
}
struct NativeKey(NonNull<c_void>);
// The handle is not thread-affine. All access and final release occur under its
// Rust owner; shared operations use the mutex in ClientKey.
unsafe impl Send for NativeKey {}
impl Drop for NativeKey {
fn drop(&mut self) {
unsafe { gp_client_key_delete(self.0.as_ptr()) };
}
}
struct NativeBytes {
data: *mut u8,
length: usize,
}
impl Drop for NativeBytes {
fn drop(&mut self) {
unsafe { gp_key_free(self.data, self.length) };
}
}
impl NativeBytes {
fn new() -> Self {
Self {
data: std::ptr::null_mut(),
length: 0,
}
}
fn copy(&self) -> anyhow::Result<Vec<u8>> {
anyhow::ensure!(
!self.data.is_null() && self.length > 0,
"Client certificate operation failed"
);
Ok(unsafe { std::slice::from_raw_parts(self.data, self.length) }.to_vec())
}
}
#[derive(Clone)]
pub(in crate::utils) struct ClientKey {
key: Arc<Mutex<NativeKey>>,
kind: c_int,
public_key: Vec<u8>,
}
impl fmt::Debug for ClientKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientKey")
.field("algorithm", &self.algorithm())
.finish_non_exhaustive()
}
}
impl ClientKey {
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
super::validate_private_key(key)?;
let bytes = key.secret_der();
let mut kind = 0;
let mut pointer = std::ptr::null_mut();
let result = unsafe { gp_client_key_new(bytes.as_ptr(), bytes.len(), &mut kind, &mut pointer) };
if result == 2 {
let algorithm = match kind {
3 => "P-521",
5 => "RSA-PSS",
6 => "an unsupported elliptic curve",
7 => "DSA",
8 => "Ed448",
_ => "an unknown key algorithm",
};
return Err(RequestIdentityError::UnsupportedKeyAlgorithm(algorithm).into());
}
if result != 0 {
return Err(RequestIdentityError::InvalidKey.into());
}
let key = NativeKey(NonNull::new(pointer).ok_or(RequestIdentityError::InvalidKey)?);
let mut exported = NativeBytes::new();
let result = unsafe { gp_client_key_public(key.0.as_ptr(), &mut exported.data, &mut exported.length) };
anyhow::ensure!(result == 0, "Could not read the client certificate's public key");
Ok(Self {
key: Arc::new(Mutex::new(key)),
kind,
public_key: exported.copy()?,
})
}
pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result<bool> {
let key = self
.key
.lock()
.map_err(|_| anyhow::anyhow!("The client certificate is unavailable"))?;
match unsafe { gp_client_key_matches(key.0.as_ptr(), certificate.as_ptr(), certificate.len()) } {
1 => Ok(true),
0 => Ok(false),
_ => Err(RequestIdentityError::InvalidCertificate.into()),
}
}
fn schemes(&self) -> &'static [SignatureScheme] {
use SignatureScheme::*;
match self.kind {
0 => &[
RSA_PSS_SHA512,
RSA_PSS_SHA384,
RSA_PSS_SHA256,
RSA_PKCS1_SHA512,
RSA_PKCS1_SHA384,
RSA_PKCS1_SHA256,
],
// Rustls does not expose the negotiated TLS version here. Keep TLS 1.3
// curve/hash requirements; TLS 1.2 cross-curve hash offers remain unsupported.
1 => &[ECDSA_NISTP256_SHA256],
2 => &[ECDSA_NISTP384_SHA384],
4 => &[ED25519],
_ => &[],
}
}
}
impl SigningKey for ClientKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
self
.schemes()
.iter()
.copied()
.find(|scheme| offered.contains(scheme))
.map(|scheme| {
Box::new(ClientSigner {
key: self.clone(),
scheme,
}) as Box<dyn Signer>
})
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
Some(SubjectPublicKeyInfoDer::from(self.public_key.as_slice()))
}
fn algorithm(&self) -> SignatureAlgorithm {
match self.kind {
0 => SignatureAlgorithm::RSA,
4 => SignatureAlgorithm::ED25519,
_ => SignatureAlgorithm::ECDSA,
}
}
}
#[derive(Debug)]
struct ClientSigner {
key: ClientKey,
scheme: SignatureScheme,
}
impl Signer for ClientSigner {
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, rustls::Error> {
let error = || rustls::Error::General("Could not sign with the client certificate".into());
let key = self.key.key.lock().map_err(|_| error())?;
let mut output = NativeBytes::new();
let result = unsafe {
gp_client_key_sign(
key.0.as_ptr(),
self.scheme.into(),
message.as_ptr(),
message.len(),
&mut output.data,
&mut output.length,
)
};
if result != 0 {
return Err(error());
}
output.copy().map_err(|_| error())
}
fn scheme(&self) -> SignatureScheme {
self.scheme
}
}
#[cfg(test)]
mod tests {
use super::*;
use openssl::{
hash::MessageDigest,
pkey::PKey,
rsa::Padding,
sign::{RsaPssSaltlen, Verifier},
};
fn fixture(name: &str) -> Vec<u8> {
std::fs::read(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/files/client-identity")
.join(name),
)
.unwrap()
}
fn native_key(bytes: &[u8]) -> ClientKey {
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
.unwrap()
.unwrap();
ClientKey::load(&key).unwrap()
}
#[test]
fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() {
let bytes = fixture("rsa-pkcs8.pem");
let key = native_key(&bytes);
let oracle = PKey::private_key_from_pem(&bytes).unwrap();
let message = b"client authentication regression";
for (scheme, digest, pss) in [
(SignatureScheme::RSA_PSS_SHA256, MessageDigest::sha256(), true),
(SignatureScheme::RSA_PSS_SHA384, MessageDigest::sha384(), true),
(SignatureScheme::RSA_PSS_SHA512, MessageDigest::sha512(), true),
(SignatureScheme::RSA_PKCS1_SHA256, MessageDigest::sha256(), false),
(SignatureScheme::RSA_PKCS1_SHA384, MessageDigest::sha384(), false),
(SignatureScheme::RSA_PKCS1_SHA512, MessageDigest::sha512(), false),
] {
let signer = key.choose_scheme(&[scheme]).unwrap();
assert_eq!(signer.scheme(), scheme);
let signature = signer.sign(message).unwrap();
let mut verifier = Verifier::new(digest, &oracle).unwrap();
if pss {
verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap();
verifier.set_rsa_mgf1_md(digest).unwrap();
}
assert!(verifier.verify_oneshot(&signature, message).unwrap(), "{scheme:?}");
}
assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none());
}
#[test]
fn p256_signatures_verify_with_an_independent_backend() {
let bytes = fixture("ec-pkcs8.pem");
let key = native_key(&bytes);
let oracle = PKey::private_key_from_pem(&bytes).unwrap();
let signer = key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).unwrap();
let message = b"native client key signature";
let signature = signer.sign(message).unwrap();
let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap();
assert!(verifier.verify_oneshot(&signature, message).unwrap());
assert!(key.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256]).is_none());
}
#[test]
fn unsupported_key_types_fail_at_import() {
for (name, algorithm) in [("ec-p521.pem", "P-521"), ("rsa-pss.pem", "RSA-PSS")] {
let bytes = fixture(name);
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
.unwrap()
.unwrap();
let error = ClientKey::load(&private_key).unwrap_err();
assert!(matches!(error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::UnsupportedKeyAlgorithm(actual)) if *actual == algorithm));
}
}
#[test]
fn a_key_remains_usable_when_shared_clients_sign_concurrently() {
let key = native_key(&fixture("rsa-pkcs8.pem"));
let mut workers = Vec::new();
for _ in 0..4 {
let key = key.clone();
workers.push(std::thread::spawn(move || {
key
.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
.unwrap()
.sign(b"shared identity")
.unwrap()
}));
}
let oracle = PKey::private_key_from_pem(&fixture("rsa-pkcs8.pem")).unwrap();
for worker in workers {
let signature = worker.join().unwrap();
let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap();
verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap();
verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap();
assert!(verifier.verify_oneshot(&signature, b"shared identity").unwrap());
}
}
}
+47 -33
View File
@@ -1,22 +1,37 @@
use p12_keystore::Pkcs12Archive; use p12_keystore::Pkcs12Archive;
use rustls::{ use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
sign::CertifiedKey, use super::{
ClientKey,
pkcs12_format::{self, ArchiveBackend},
}; };
use crate::utils::{client_tls, request::RequestIdentityError};
use crate::utils::request::{RequestIdentityError, pem_request_identity}; pub(in crate::utils) fn certified_key(
bytes: &[u8],
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> { passphrase: Option<&str>,
) -> anyhow::Result<std::sync::Arc<rustls::sign::CertifiedKey>> {
anyhow::ensure!( anyhow::ensure!(
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)), passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
"PKCS#12 passphrases containing NUL are not supported" "PKCS#12 passphrases containing NUL are not supported"
); );
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| { if pkcs12_format::backend(bytes)? == ArchiveBackend::NativeRc4 {
if passphrase.is_none() { let (certificate, key) = super::archive(bytes, passphrase)?;
RequestIdentityError::NoPassphrase("PKCS#12") let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
} else { return client_tls::pem_certified_key(&certificate, key.as_bytes());
RequestIdentityError::InvalidPkcs12(error)
} }
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| match error {
p12_keystore::error::Error::UnsupportedEncryptionScheme | p12_keystore::error::Error::UnsupportedMacAlgorithm => {
RequestIdentityError::UnsupportedEncryption
}
p12_keystore::error::Error::MacError(_)
| p12_keystore::error::Error::UnpadError
| p12_keystore::error::Error::Pkcs5Error(_)
if passphrase.is_none() =>
{
RequestIdentityError::NoPassphrase("PKCS#12")
}
error => RequestIdentityError::InvalidPkcs12(error),
})?; })?;
if archive.keys.is_empty() || archive.certs.is_empty() { if archive.keys.is_empty() || archive.certs.is_empty() {
return Err(RequestIdentityError::IncompletePkcs12.into()); return Err(RequestIdentityError::IncompletePkcs12.into());
@@ -25,7 +40,8 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh
return Err(RequestIdentityError::AmbiguousPkcs12.into()); return Err(RequestIdentityError::AmbiguousPkcs12.into());
} }
let key = &archive.keys[0].key; let key = &archive.keys[0].key;
let provider = rustls::crypto::ring::default_provider(); let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
let signing_key = ClientKey::load(&private_key)?;
let mut certs = Vec::new(); let mut certs = Vec::new();
for bag in &archive.certs { for bag in &archive.certs {
if !certs if !certs
@@ -35,38 +51,36 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh
certs.push(&bag.cert); certs.push(&bag.cert);
} }
} }
let matches: Vec<_> = certs let mut matches = Vec::new();
.iter() for (index, cert) in certs.iter().enumerate() {
.enumerate() if signing_key.matches_certificate(cert.as_der())? {
.filter_map(|(index, cert)| { matches.push(index);
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec())); }
CertifiedKey::from_der( }
vec![CertificateDer::from(cert.as_der().to_vec())], let leaf = match matches.first() {
private_key, Some(leaf) => *leaf,
&provider, None => return Err(RequestIdentityError::KeyMismatch.into()),
)
.is_ok()
.then_some(index)
})
.collect();
let leaf = match matches.as_slice() {
[leaf] => *leaf,
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
}; };
let mut current = certs.remove(leaf); let mut current = certs.remove(leaf);
let mut chain = Vec::new(); let mut chain = Vec::new();
loop { loop {
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes()); chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
if current.subject() == current.issuer() { if super::issuer::is_issuer(current.as_der(), current.as_der())? {
break; break;
} }
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else { let mut parent = None;
for (index, candidate) in certs.iter().enumerate() {
if super::issuer::is_issuer(current.as_der(), candidate.as_der())? {
parent = Some(index);
break;
}
}
let Some(parent) = parent else {
break; break;
}; };
current = certs.remove(parent); current = certs.remove(parent);
} }
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?; let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?; let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
pem_request_identity(&chain, key.as_bytes()) client_tls::pem_certified_key(&chain, key.as_bytes())
} }
@@ -0,0 +1,137 @@
//! Select an archive importer from decoded encryption metadata, before passwords.
use cms::encrypted_data::EncryptedData;
use pkcs8::{
ObjectIdentifier,
der::{
Decode, Encode,
asn1::{ContextSpecific, OctetString},
},
};
use pkcs12::{
AuthenticatedSafe,
pbe_params::{EncryptedPrivateKeyInfo, Pkcs12PbeParams},
pfx::Pfx,
safe_bag::SafeContents,
};
use crate::utils::request::RequestIdentityError;
const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6");
const ENCRYPTED_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2");
const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13");
const RC4_128: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.1");
const DES3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3");
const RC2_40: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.6");
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ArchiveBackend {
Rust,
NativeRc4,
}
fn invalid(_: pkcs8::der::Error) -> RequestIdentityError {
RequestIdentityError::InvalidCertificate
}
/// Inspect only visible metadata. Encrypted safe contents remain opaque until
/// the selected importer verifies the MAC and decrypts them.
pub(super) fn backend(bytes: &[u8]) -> Result<ArchiveBackend, RequestIdentityError> {
let pfx = Pfx::from_der(bytes).map_err(invalid)?;
if pfx.auth_safe.content_type != DATA {
return Err(RequestIdentityError::UnsupportedEncryption);
}
let contents = pfx.auth_safe.content.decode_as::<OctetString>().map_err(invalid)?;
let safes = AuthenticatedSafe::from_der(contents.as_bytes()).map_err(invalid)?;
let mut selected = ArchiveBackend::Rust;
for safe in safes {
if safe.content_type == ENCRYPTED_DATA {
let encrypted = safe.content.decode_as::<EncryptedData>().map_err(invalid)?;
let algorithm = encrypted.enc_content_info.content_enc_alg;
inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?;
} else if safe.content_type == DATA {
let contents = safe.content.decode_as::<OctetString>().map_err(invalid)?;
let bags = SafeContents::from_der(contents.as_bytes()).map_err(invalid)?;
for bag in bags {
if bag.bag_id == ENCRYPTED_KEY {
let encrypted = ContextSpecific::<EncryptedPrivateKeyInfo>::from_der(&bag.bag_value).map_err(invalid)?;
let algorithm = encrypted.value.encryption_algorithm;
inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?;
}
}
} else {
return Err(RequestIdentityError::UnsupportedEncryption);
}
}
Ok(selected)
}
fn inspect_algorithm(
oid: ObjectIdentifier,
parameters: Option<&pkcs8::der::Any>,
selected: &mut ArchiveBackend,
) -> Result<(), RequestIdentityError> {
let parameters = parameters
.ok_or(RequestIdentityError::InvalidCertificate)?
.to_der()
.map_err(invalid)?;
if oid == PBES2 {
pkcs8::pkcs5::pbes2::Parameters::from_der(&parameters).map_err(|error| match error.kind() {
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
_ => RequestIdentityError::InvalidCertificate,
})?;
} else if matches!(oid, RC4_128 | DES3 | RC2_40) {
Pkcs12PbeParams::from_der(&parameters).map_err(invalid)?;
if oid == RC4_128 {
*selected = ArchiveBackend::NativeRc4;
}
} else {
return Err(RequestIdentityError::UnsupportedEncryption);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn published_archive_formats_choose_their_importer_from_metadata() {
for name in [
"modern.p12",
"legacy-rc2.p12",
"empty-password.p12",
"unicode-password.p12",
"no-bag-ids.p12",
] {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/files/client-identity")
.join(name);
assert_eq!(
backend(&std::fs::read(path).unwrap()).unwrap(),
ArchiveBackend::Rust,
"{name}"
);
}
assert_eq!(
backend(include_bytes!(
"../../../tests/files/client-identity/legacy-RC4-128.p12"
))
.unwrap(),
ArchiveBackend::NativeRc4
);
}
#[test]
fn unsupported_archive_encryption_is_terminal_before_password_handling() {
for bytes in [
include_bytes!("../../../tests/files/client-identity/legacy-RC2-128.p12").as_slice(),
include_bytes!("../../../tests/files/client-identity/legacy-2DES.p12").as_slice(),
] {
assert!(matches!(
backend(bytes),
Err(RequestIdentityError::UnsupportedEncryption)
));
}
}
}
@@ -0,0 +1,46 @@
//! Portable certificate verification; native legacy import is unavailable here.
use crate::utils::request::RequestIdentityError;
use pkcs8::der::{Decode, Encode, asn1::AnyRef};
pub(in crate::utils) fn decrypt(
_bytes: &[u8],
_pem: bool,
_passphrase: Option<&str>,
) -> anyhow::Result<pkcs8::SecretDocument> {
Err(RequestIdentityError::UnsupportedEncryption.into())
}
pub(in crate::utils) fn archive(
_bytes: &[u8],
_passphrase: Option<&str>,
) -> anyhow::Result<(zeroize::Zeroizing<Vec<u8>>, pkcs8::SecretDocument)> {
Err(RequestIdentityError::UnsupportedEncryption.into())
}
pub(super) fn verify_certificate_signature(
child: &x509_cert::Certificate,
parent: &x509_cert::Certificate,
message: &[u8],
signature: &[u8],
) -> anyhow::Result<bool> {
let public_key = parent.tbs_certificate().subject_public_key_info();
let key_algorithm = public_key.algorithm.to_der()?;
let signature_algorithm = child.signature_algorithm().to_der()?;
let key_algorithm = AnyRef::from_der(&key_algorithm)?.value();
let signature_algorithm = AnyRef::from_der(&signature_algorithm)?.value();
let key = public_key
.subject_public_key
.as_bytes()
.ok_or(RequestIdentityError::InvalidCertificate)?;
Ok(
rustls::crypto::ring::default_provider()
.signature_verification_algorithms
.all
.iter()
.any(|algorithm| {
algorithm.public_key_alg_id().as_ref() == key_algorithm
&& algorithm.signature_alg_id().as_ref() == signature_algorithm
&& algorithm.verify_signature(key, message, signature).is_ok()
}),
)
}
@@ -0,0 +1,41 @@
use crate::utils::request::RequestIdentityError;
use pkcs8::der::{Decode, Encode};
use rustls::{
SignatureAlgorithm, SignatureScheme,
pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer},
sign::{Signer, SigningKey},
};
use std::sync::Arc;
#[derive(Debug)]
pub(in crate::utils) struct ClientKey {
key: Arc<dyn SigningKey>,
}
impl ClientKey {
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
super::validate_private_key(key)?;
let key = rustls::crypto::ring::default_provider()
.key_provider
.load_private_key(key.clone_key())
.map_err(|_| RequestIdentityError::InvalidKey)?;
Ok(Self { key })
}
pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result<bool> {
let certificate =
x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
let key = self.key.public_key().ok_or(RequestIdentityError::InvalidKey)?;
Ok(certificate.tbs_certificate().subject_public_key_info().to_der()? == key.as_ref())
}
}
impl SigningKey for ClientKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
self.key.choose_scheme(offered)
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
self.key.public_key()
}
fn algorithm(&self) -> SignatureAlgorithm {
self.key.algorithm()
}
}
@@ -1,7 +0,0 @@
pub(in crate::utils) fn decrypt(
_bytes: &[u8],
_pem: bool,
_passphrase: Option<&str>,
) -> anyhow::Result<pkcs8::SecretDocument> {
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
}
+99
View File
@@ -0,0 +1,99 @@
//! Local identity matching is separate from the peer's certificate validation.
use std::{io::Cursor, sync::Arc};
use pkcs8::der::Decode;
use rustls::{
ClientConfig, DigitallySignedStruct, SignatureScheme,
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
pki_types::{CertificateDer, ServerName, UnixTime},
sign::{CertifiedKey, SingleCertAndKey},
};
use rustls_platform_verifier::BuilderVerifierExt;
use super::{
certificate::{ClientKey, validate_certificate},
request::RequestIdentityError,
};
pub(super) fn pem_certified_key(certificate: &[u8], key: &[u8]) -> anyhow::Result<Arc<CertifiedKey>> {
let certificates = rustls_pemfile::certs(&mut Cursor::new(certificate))
.collect::<Result<Vec<_>, _>>()
.map_err(|_| RequestIdentityError::InvalidCertificate)?;
let private_key = rustls_pemfile::private_key(&mut Cursor::new(key))
.map_err(|_| RequestIdentityError::InvalidKey)?
.ok_or(RequestIdentityError::NoKey)?;
let signing_key = Arc::new(ClientKey::load(&private_key)?);
let leaf = certificates.first().ok_or(RequestIdentityError::InvalidCertificate)?;
validate_certificate(leaf)?;
if !signing_key.matches_certificate(leaf)? {
return Err(RequestIdentityError::KeyMismatch.into());
}
for certificate in certificates.iter().skip(1) {
x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
}
// The local key has been matched without applying peer certificate policy.
Ok(Arc::new(CertifiedKey::new(certificates, signing_key)))
}
pub(super) fn identity_client_builder(
identity: Arc<CertifiedKey>,
ignore_server_certificate_errors: bool,
) -> anyhow::Result<reqwest::ClientBuilder> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let config = ClientConfig::builder_with_provider(provider.clone()).with_safe_default_protocol_versions()?;
let config = if ignore_server_certificate_errors {
config
.dangerous()
.with_custom_certificate_verifier(Arc::new(IgnoreServerCertificateErrors {
schemes: provider.signature_verification_algorithms.supported_schemes(),
}))
} else {
// Match Reqwest's default system trust store, including private enterprise CAs.
config.with_platform_verifier()?
};
let mut config = config.with_client_cert_resolver(Arc::new(SingleCertAndKey::from(identity)));
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(super::request::client_builder().tls_backend_preconfigured(config))
}
/// Equivalent to Reqwest's danger_accept_invalid_certs(true), used only when
/// the user explicitly enables the existing ignore-certificate-errors setting.
#[derive(Debug)]
struct IgnoreServerCertificateErrors {
schemes: Vec<SignatureScheme>,
}
impl ServerCertVerifier for IgnoreServerCertificateErrors {
fn verify_server_cert(
&self,
_: &CertificateDer<'_>,
_: &[CertificateDer<'_>],
_: &ServerName<'_>,
_: &[u8],
_: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_: &[u8],
_: &CertificateDer<'_>,
_: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_: &[u8],
_: &CertificateDer<'_>,
_: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.schemes.clone()
}
}
+2 -1
View File
@@ -90,7 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
} }
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?, "ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
"EC PRIVATE KEY" => { "EC PRIVATE KEY" => {
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?; // The signing provider validates both named and explicitly encoded curves.
SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?;
return Ok(block.encoded()); return Ok(block.encoded());
} }
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()), _ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
+1
View File
@@ -3,6 +3,7 @@ pub mod xml;
pub mod base64; pub mod base64;
mod certificate; mod certificate;
pub mod checksum; pub mod checksum;
mod client_tls;
pub mod crypto; pub mod crypto;
#[cfg(feature = "desktop")] #[cfg(feature = "desktop")]
pub mod endpoint; pub mod endpoint;
+57 -57
View File
@@ -1,34 +1,40 @@
use std::{fmt, fs, io::Write, path::Path, sync::Arc}; use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::{Context, ensure}; use anyhow::{Context, ensure};
use reqwest::Identity; use rustls::sign::CertifiedKey;
use zeroize::Zeroizing; use zeroize::Zeroizing;
use super::{certificate::pkcs12, identity_encoding}; use super::{certificate::pkcs12, client_tls, identity_encoding};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError { pub enum RequestIdentityError {
#[error("Failed to find the private key")] #[error("No private key was found. Choose the matching key file")]
NoKey, NoKey,
#[error("No passphrase provided")] #[error("This certificate or key is password-protected. Enter its password")]
NoPassphrase(&'static str), NoPassphrase(&'static str),
#[error("Failed to decrypt private key")] #[error("Could not unlock the certificate or key. Check the password and file")]
DecryptError(&'static str), DecryptError(&'static str),
#[error( #[error("This certificate or key uses unsupported encryption. Re-export it with AES encryption")]
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
UnsupportedEncryption, UnsupportedEncryption,
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")] #[error("This private key format is not supported. Choose a PEM key or a PKCS#12 certificate file")]
UnsupportedKeyFormat, UnsupportedKeyFormat,
#[error("Invalid private key")] #[error(
"This client certificate uses an unsupported key type ({0}). Ask your VPN administrator for an RSA or P-256 certificate"
)]
UnsupportedKeyAlgorithm(&'static str),
#[error("The private key does not match this certificate. Choose the matching key file")]
KeyMismatch,
#[error("The private key file is invalid. Choose a different key file")]
InvalidKey, InvalidKey,
#[error("Invalid certificate or certificate chain")] #[error("The certificate file is invalid. Choose a different certificate file")]
InvalidCertificate, InvalidCertificate,
#[error("The PKCS#12 file must contain both a client certificate and its private key")] #[error("The PKCS#12 file must contain both a client certificate and its private key")]
IncompletePkcs12, IncompletePkcs12,
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")] #[error("Could not open the PKCS#12 file. Check the password or choose another file")]
InvalidPkcs12(#[source] p12_keystore::error::Error), InvalidPkcs12(#[source] p12_keystore::error::Error),
#[error("The PKCS#12 file must contain one matching client identity")] #[error(
"The certificate file contains more than one matching identity. Choose a file with one client certificate and key"
)]
AmbiguousPkcs12, AmbiguousPkcs12,
} }
@@ -38,7 +44,7 @@ pub enum RequestIdentityError {
#[derive(Clone)] #[derive(Clone)]
pub struct ClientIdentity { pub struct ClientIdentity {
material: Arc<IdentityMaterial>, material: Arc<IdentityMaterial>,
identity: Identity, certified_key: Arc<CertifiedKey>,
} }
struct IdentityMaterial { struct IdentityMaterial {
@@ -68,14 +74,14 @@ impl ClientIdentity {
}; };
let key = identity_encoding::private_key(&key_bytes, passphrase)?; let key = identity_encoding::private_key(&key_bytes, passphrase)?;
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?; let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
let identity = pem_request_identity(&certificate, &key)?; let certified_key = client_tls::pem_certified_key(&certificate, &key)?;
Ok(Self { Ok(Self {
material: Arc::new(IdentityMaterial { material: Arc::new(IdentityMaterial {
certificate, certificate,
key: Some(key), key: Some(key),
passphrase: None, passphrase: None,
}), }),
identity, certified_key,
}) })
} }
@@ -86,12 +92,12 @@ impl ClientIdentity {
key: Option<Zeroizing<Vec<u8>>>, key: Option<Zeroizing<Vec<u8>>>,
passphrase: Option<&str>, passphrase: Option<&str>,
) -> anyhow::Result<Self> { ) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key { let (certified_key, passphrase) = match &key {
Some(key) => (pem_request_identity(&certificate, key)?, None), Some(key) => (client_tls::pem_certified_key(&certificate, key)?, None),
None => { None => {
let identity = pkcs12::identity(&certificate, passphrase)?; let certified_key = pkcs12::certified_key(&certificate, passphrase)?;
( (
identity, certified_key,
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())), Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
) )
} }
@@ -102,7 +108,7 @@ impl ClientIdentity {
key, key,
passphrase, passphrase,
}), }),
identity, certified_key,
}) })
} }
@@ -115,8 +121,8 @@ impl ClientIdentity {
pub fn key_password(&self) -> Option<&str> { pub fn key_password(&self) -> Option<&str> {
self.material.passphrase.as_ref().map(|value| value.as_str()) self.material.passphrase.as_ref().map(|value| value.as_str())
} }
pub(crate) fn request_identity(&self) -> Identity { pub(crate) fn client_builder(&self, ignore_tls_errors: bool) -> anyhow::Result<reqwest::ClientBuilder> {
self.identity.clone() client_tls::identity_client_builder(self.certified_key.clone(), ignore_tls_errors)
} }
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> { pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
@@ -149,29 +155,6 @@ impl ClientIdentityFiles {
} }
} }
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
let error_context =
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
let mut combined = Zeroizing::new(certificate.to_vec());
combined.push(b'\n');
combined.extend_from_slice(key);
let identity = Identity::from_pem(&combined).context(error_context)?;
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
.collect::<Result<Vec<_>, _>>()
.context(error_context)?;
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
.context(error_context)?
.context(error_context)?;
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
.context(error_context)?;
client_builder()
.no_proxy()
.identity(identity.clone())
.build()
.context(error_context)?;
Ok(identity)
}
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> { fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new( Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?, fs::read(path).context("Failed to read client identity")?,
@@ -208,12 +191,6 @@ pub fn client_builder() -> reqwest::ClientBuilder {
reqwest::Client::builder().tls_backend_rustls() reqwest::Client::builder().tls_backend_rustls()
} }
/// General request clients may load an identity directly. Session owners call
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -222,6 +199,29 @@ mod tests {
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem"); const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem");
const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem"); const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem");
#[test]
fn unsupported_identity_errors_explain_the_action_without_blaming_passwords_or_key_matching() {
for error in [
RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"),
RequestIdentityError::UnsupportedEncryption,
RequestIdentityError::UnsupportedKeyFormat,
] {
let message = error.to_string();
assert!(
message.contains("unsupported") || message.contains("not supported"),
"{message}"
);
assert!(
message.contains("Ask ") || message.contains("Re-export ") || message.contains("Choose "),
"{message}"
);
assert!(
!message.contains("password") && !message.contains("does not match"),
"{message}"
);
}
}
#[test] #[test]
fn pem_without_key_reports_missing_key_even_with_passphrase() { fn pem_without_key_reports_missing_key_even_with_passphrase() {
let mut source = tempfile::NamedTempFile::new().unwrap(); let mut source = tempfile::NamedTempFile::new().unwrap();
@@ -247,21 +247,21 @@ mod tests {
} }
#[test] #[test]
fn create_identity_preserves_password_errors_and_builds_a_request_client() { fn identity_loading_preserves_password_errors_and_builds_a_request_client() {
let mut source = tempfile::NamedTempFile::new().unwrap(); let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(CERTIFICATE).unwrap(); source.write_all(CERTIFICATE).unwrap();
source.write_all(ENCRYPTED_KEY).unwrap(); source.write_all(ENCRYPTED_KEY).unwrap();
for (password, missing) in [(None, true), (Some("wrong"), false)] { for (password, missing) in [(None, true), (Some("wrong"), false)] {
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err(); let error = ClientIdentity::load(source.path().to_str().unwrap(), None, password).unwrap_err();
match error.downcast_ref::<RequestIdentityError>() { match error.downcast_ref::<RequestIdentityError>() {
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing), Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing), Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
other => panic!("Unexpected identity error: {other:?}"), other => panic!("Unexpected identity error: {other:?}"),
} }
} }
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap(); let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
drop(source); drop(source);
client_builder().identity(identity).build().unwrap(); identity.client_builder(false).unwrap().build().unwrap();
} }
#[test] #[test]
@@ -283,7 +283,7 @@ mod tests {
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files); drop(files);
assert!(!Path::new(&path).exists()); assert!(!Path::new(&path).exists());
client_builder().identity(identity.request_identity()).build().unwrap(); identity.client_builder(false).unwrap().build().unwrap();
} }
} }
@@ -0,0 +1,150 @@
//! Supported desktop identities and actionable failures for unsupported inputs.
#![cfg(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
))]
use gpapi::utils::request::{ClientIdentity, RequestIdentityError};
use openssl::{
asn1::Asn1Time,
bn::BigNum,
hash::MessageDigest,
pkey::PKey,
stack::Stack,
x509::{X509, X509NameBuilder},
};
use std::{fs, path::PathBuf};
use zeroize::Zeroizing;
fn fixture(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/files/client-identity")
.join(name)
}
fn assert_unsupported_key(certificate: &str, key: &str) {
let error = ClientIdentity::load(
fixture(certificate).to_str().unwrap(),
Some(fixture(key).to_str().unwrap()),
None,
)
.unwrap_err();
assert!(
matches!(
error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::UnsupportedKeyAlgorithm(_))
),
"{error:#}"
);
let message = error.to_string();
assert!(message.contains("unsupported"), "{message}");
assert!(message.contains("VPN administrator"), "{message}");
assert!(
!message.contains("password") && !message.contains("does not match"),
"{message}"
);
}
#[test]
fn compressed_ec_certificate_reports_an_unsupported_encoding() {
assert_unsupported_key("ec-compressed-cert.pem", "ec-pkcs8.pem");
}
#[test]
fn compressed_ec_private_key_reports_an_unsupported_encoding() {
assert_unsupported_key("ec-compressed-cert.pem", "ec-compressed.pem");
}
#[test]
fn explicit_ec_parameters_report_an_unsupported_encoding() {
assert_unsupported_key("ec-explicit-cert.pem", "ec-explicit.pem");
}
#[test]
fn p521_key_reports_the_known_tls_capability_limit() {
assert_unsupported_key("ec-p521-cert.pem", "ec-p521.pem");
}
#[test]
fn rsa_pss_key_reports_the_known_tls_capability_limit() {
assert_unsupported_key("rsa-pss-cert.pem", "rsa-pss.pem");
}
fn legacy_archive(name: &str) {
let path = fixture(name);
let bytes = fs::read(&path).unwrap();
let identity = ClientIdentity::load(path.to_str().unwrap(), None, Some("fixture-password"))
.unwrap_or_else(|error| panic!("{name}: {error:#}"));
assert_eq!(identity.certificate_data(), bytes);
assert!(ClientIdentity::load(path.to_str().unwrap(), None, Some("incorrect")).is_err());
}
fn unsupported_archive(name: &str) {
let path = fixture(name);
let bytes = fs::read(&path).unwrap();
for password in [None, Some("fixture-password"), Some("incorrect"), Some("")] {
for error in [
ClientIdentity::load(path.to_str().unwrap(), None, password).unwrap_err(),
ClientIdentity::from_data(Zeroizing::new(bytes.clone()), None, password).unwrap_err(),
] {
assert!(
matches!(
error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::UnsupportedEncryption)
),
"{name}: {error:#}"
);
assert!(error.to_string().contains("AES"), "{error}");
}
}
}
#[test]
fn legacy_rc2_128_pkcs12_explains_the_unsupported_encryption() {
unsupported_archive("legacy-RC2-128.p12");
}
#[test]
fn legacy_rc4_128_pkcs12_is_usable() {
legacy_archive("legacy-RC4-128.p12");
}
#[test]
fn legacy_two_key_3des_pkcs12_explains_the_unsupported_encryption() {
unsupported_archive("legacy-2DES.p12");
}
#[test]
fn renewed_pkcs12_with_one_key_is_accepted_without_artificial_ambiguity() {
let key = PKey::private_key_from_pem(&fs::read(fixture("rsa-pkcs8.pem")).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "Public renewed identity").unwrap();
let name = name.build();
let mut certs = Vec::new();
for serial in [10, 11] {
let mut builder = X509::builder().unwrap();
builder.set_version(2).unwrap();
builder.set_subject_name(&name).unwrap();
builder.set_issuer_name(&name).unwrap();
builder.set_pubkey(&key).unwrap();
builder
.set_serial_number(&BigNum::from_u32(serial).unwrap().to_asn1_integer().unwrap())
.unwrap();
builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
builder.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
builder.sign(&key, MessageDigest::sha256()).unwrap();
certs.push(builder.build());
}
let mut extra = Stack::new().unwrap();
extra.push(certs[0].clone()).unwrap();
let mut builder = openssl::pkcs12::Pkcs12::builder();
builder.name("renewed").pkey(&key).cert(&certs[1]).ca(extra);
let archive = builder.build2("fixture-password").unwrap().to_der().unwrap();
// Independent oracle for this bag order. Native bag-order permutation tests
// establish selection; localKeyId alone does not override native ordering.
let parsed = openssl::pkcs12::Pkcs12::from_der(&archive)
.unwrap()
.parse2("fixture-password")
.unwrap();
assert_eq!(parsed.cert.unwrap().to_der().unwrap(), certs[1].to_der().unwrap());
ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap();
}
@@ -0,0 +1,238 @@
//! 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,
&current_key,
Some((&root, &root_key)),
3,
true,
self_issued,
);
let client_key = key();
let leaf = certificate(
"Client",
&client_key,
Some((&current, &current_key)),
4,
false,
self_issued,
);
for old_first in [true, false] {
let mut ca = Stack::new().unwrap();
let intermediates = if old_first { [&old, &current] } else { [&current, &old] };
for cert in intermediates {
ca.push(cert.clone()).unwrap();
}
ca.push(root.clone()).unwrap();
authenticate(&root, &current, &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(&params).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;
}
}
}
@@ -0,0 +1,419 @@
//! 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(&params(identity.clone(), false)).unwrap();
reqwest::Client::try_from(&params(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(&params).unwrap();
params.prepare_client_identity().unwrap();
drop(directory);
reqwest::Client::try_from(&params).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(&params(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(&params(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}"
);
}
}
}
}
@@ -0,0 +1,156 @@
//! 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(&params).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");
}
+13 -16
View File
@@ -114,11 +114,10 @@ fn malformed_rsa_pkcs1_is_rejected_before_connection() {
None, None,
) )
.unwrap_err(); .unwrap_err();
assert!( assert!(matches!(
error error.downcast_ref::<RequestIdentityError>(),
.to_string() Some(RequestIdentityError::InvalidKey)
.contains("Check that the private key matches the certificate") ));
);
} }
fn check_archive(name: &str, password: &str) { fn check_archive(name: &str, password: &str) {
@@ -604,17 +603,15 @@ fn mismatched_certificate_key_is_rejected_before_request_client_creation() {
let certificate = fs::read(fixture("root.pem")).unwrap(); let certificate = fs::read(fixture("root.pem")).unwrap();
let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap(); let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
let error = load("root.pem", "rsa-pkcs8.pem", None).unwrap_err(); let error = load("root.pem", "rsa-pkcs8.pem", None).unwrap_err();
assert!( assert!(matches!(
error error.downcast_ref::<RequestIdentityError>(),
.to_string() Some(RequestIdentityError::KeyMismatch)
.contains("Check that the private key matches the certificate") ));
);
let error = ClientIdentity::from_data(certificate.into(), Some(key.into()), None).unwrap_err(); let error = ClientIdentity::from_data(certificate.into(), Some(key.into()), None).unwrap_err();
assert!( assert!(matches!(
error error.downcast_ref::<RequestIdentityError>(),
.to_string() Some(RequestIdentityError::KeyMismatch)
.contains("Check that the private key matches the certificate") ));
);
} }
#[test] #[test]
@@ -640,7 +637,7 @@ fn pkcs12_rejects_mismatched_and_multiple_identities() {
let error = ClientIdentity::load(fixture(name).to_str().unwrap(), None, None).unwrap_err(); let error = ClientIdentity::load(fixture(name).to_str().unwrap(), None, None).unwrap_err();
match error.downcast_ref::<RequestIdentityError>() { match error.downcast_ref::<RequestIdentityError>() {
Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous), Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous),
Some(RequestIdentityError::InvalidCertificate) => assert!(!ambiguous), Some(RequestIdentityError::KeyMismatch) => assert!(!ambiguous),
other => panic!("{name}: unexpected archive error: {other:?}"), other => panic!("{name}: unexpected archive error: {other:?}"),
} }
} }
@@ -19,6 +19,7 @@ optional fixture-generation script, not identity import.
| Files | Contents | | Files | Contents |
| --- | --- | | --- | --- |
| `root.pem`, `rsa-cert.pem`, `ec-cert.pem` | Test root and issued RSA-2048 / P-256 client certificates, SHA256 signatures | | `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-pkcs8.pem`, `ec-pkcs8.pem` | Plain PKCS#8 keys; expected normalized output |
| `rsa-pkcs1.pem`, `ec-sec1.pem` | Same keys in traditional containers | | `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` | | `{rsa,ec}-traditional-{aes128,aes192,aes256,des3}.pem` | Traditional encrypted PEM with AES-CBC or 3DES-CBC; password `fixture-password` |
@@ -34,13 +35,20 @@ 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 | | `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` | | `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 | | `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, `tests/client_identity.rs` covers all supported key families, password failures,
archive integrity, certificate/key matching, retained snapshots, private-file archive integrity, certificate/key matching, retained snapshots, private-file
permissions and cleanup. `tests/identity_encoding.rs` covers PEM/DER, RSA PKCS#1, permissions and cleanup. `tests/identity_encoding.rs` covers PEM/DER, RSA PKCS#1,
EC SEC1, traditional encrypted PEM, first-key selection, malformed encryption EC SEC1, traditional encrypted PEM, first-key selection, malformed encryption
headers and archive extension capitalization. Rustls validates RSA and EC keys headers and archive extension capitalization. Desktop GnuTLS validates and signs client keys; portable builds keep the Rust
on all supported targets; desktop legacy encrypted-key imports use GnuTLS. implementation. Legacy encrypted-key imports use the private GnuTLS shim.
Legacy PKCS#12 SHA1/3DES keys use a consistent limit of 127 UTF-16 code units 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. (256 bytes including the terminator), matching older supported GnuTLS releases.
Longer passwords report a clear error without exposing the password. Longer passwords report a clear error without exposing the password.
@@ -53,6 +61,41 @@ MAC. Decrypted output is compared with independent plaintext fixture keys.
Unit tests in `utils/request.rs` cover missing keys, large local files and request Unit tests in `utils/request.rs` cover missing keys, large local files and request
client construction. 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 The unencrypted, MAC-less `no-bag-ids.p12`, `mismatched.p12`, and
`multiple-identities.p12` contain only the same public test keys/certificates. `multiple-identities.p12` contain only the same public test keys/certificates.
They exercise PKCS#12 bags without optional attributes, reversed certificate They exercise PKCS#12 bags without optional attributes, reversed certific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MCwGByqG
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-----
@@ -0,0 +1,10 @@
-----BEGIN EC PRIVATE KEY-----
MIIBaAIBAQQgwiAZclkH//xmntM5q9LIH7sus8oUbh5BnwXHHfRtPNSggfowgfcC
AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////
MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr
vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE
axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W
K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8
YyVRAgEBoUQDQgAEQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRWqTI/q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WPX+yw0q5EzpeEGjWV82Y
DRoEfkDRfAjk8/B/8wDNJ7oH9pepkq3DroH0v3R34C8oQwbsw/Rx9JwOECR3u2jI
gzNLtiEfiEBgucZ5MgDEgNJdB03qCvaqUmYXN7Lwog==
-----END EC PRIVATE KEY-----
@@ -0,0 +1,24 @@
#!/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,6 +17,19 @@ for algorithm in rsa ec; do
"$openssl_bin" x509 -req -in "$scratch/$algorithm.csr" -CA root.pem -CAkey "$scratch/root.key" \ "$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" -set_serial 10 -days 3650 -sha256 -out "$algorithm-cert.pem"
done 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" rsa -in rsa-pkcs8.pem -traditional -out rsa-pkcs1.pem
"$openssl_bin" ec -in ec-pkcs8.pem -out ec-sec1.pem "$openssl_bin" ec -in ec-pkcs8.pem -out ec-sec1.pem
for cipher in aes128 aes192 aes256 des3; do for cipher in aes128 aes192 aes256 des3; do
@@ -70,6 +83,14 @@ done
"$openssl_bin" pkcs8 -provider default -provider legacy -topk8 -in rsa-pkcs8.pem \ "$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 -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. # Incomplete identity archives exercise validation before native TLS import.
"$openssl_bin" pkcs12 -export -nokeys -in rsa-cert.pem \ "$openssl_bin" pkcs12 -export -nokeys -in rsa-cert.pem \
-name fixture -passout pass:fixture-password -out certificate-only.pfx -name fixture -passout pass:fixture-password -out certificate-only.pfx
@@ -78,3 +99,4 @@ done
# Plain PKCS#12 bags let the import tests omit optional IDs and reorder bags. # Plain PKCS#12 bags let the import tests omit optional IDs and reorder bags.
python3 "$(dirname "$0")/generate-plain-pfx.py" python3 "$(dirname "$0")/generate-plain-pfx.py"
bash "$(dirname "$0")/generate-pss-chain.sh"
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDEDCCAfigAwIBAgIBAjANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDDA5QU1Mg
Q2hhaW4gUm9vdDAeFw0yNjExMDcwNTIxNTJaFw0zNjExMDQwNTIxNTJaMBkxFzAV
BgNVBAMMDlBTUyBJc3N1aW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAkjFaot6TCYfvnmfxSGfpqd2X+633FdjuaJLFf+G/EAccA7SVwtyGAJuT
/+RE3q0JO9I502mPRIWxkKOH0KU1dQK92iIup2lhc4WOtaGFvk+KGu3UrIQhgK8N
h0bEkiPcO160M3MEBo3mZGC933n/q+ean1nHcxrh3vp6t4fAUmH8B46+ww2QgUR0
nJorVh/gAmrzRmgRfRy3FKHRh9sZLrguJqlNOe8g3x/brmFV2dd4vl1iX84+Xxs3
9WfyrYGH0Sy3HAUv7ur5z8j9eiPTdy3UvGpDo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pA9RbcSNPMe+POUxGb6pk3
mSV4ymmotWtyr0GqNa/FgujjZ68TWwvhrJFD0kQap3flM3/82ThJCk9HsJ9osjPM
mNEHccfgASpPVgpkvLUjtITUb7aO1cdjHK1gFknNQSy/jZyMClfhnwvXiqqgWqme
f9Ih4LSOdrek2teuI5Mo
-----END PRIVATE KEY-----
+280
View File
@@ -0,0 +1,280 @@
/* 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;
}
@@ -0,0 +1,83 @@
//! 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"),
);
}
+1 -1
View File
@@ -18,7 +18,7 @@ Install build and runtime dependencies:
```sh ```sh
sudo pkg install git rust libiconv gettext-tools autoconf automake libtool patch \ sudo pkg install git rust libiconv gettext-tools autoconf automake libtool patch \
gmake pkgconf libxml2 gnutls p11-kit nettle gmp gnome-keyring \ gmake pkgconf libxml2 gnutls p11-kit nettle gmp liblz4 gnome-keyring \
libayatana-appindicator polkit webkit2-gtk_41 xdg-utils libayatana-appindicator polkit webkit2-gtk_41 xdg-utils
``` ```
Generated
+3 -3
View File
@@ -63,11 +63,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1792506237, "lastModified": 1793795574,
"narHash": "sha256-Q/8KLB6jNfpaUN1HAedE/u/Et9feE/zYSsutBLKrCFk=", "narHash": "sha256-pgG/CO+txdf2sA2z6DsM+2G3F9ajfIp/3BMC4wfKMDY=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "5adc50831c259f87faeb09ddf930d43597197473", "rev": "13e53762c5afaf384d4614e94527a9ccfafe41d0",
"type": "github" "type": "github"
}, },
"original": { "original": {
+6 -6
View File
@@ -29,8 +29,8 @@
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml); cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
pname = "globalprotect-openconnect"; pname = "globalprotect-openconnect";
version = cargoToml.workspace.package.version; version = cargoToml.workspace.package.version;
releaseTag = "v3.2.0"; releaseTag = "v3.3.0";
releaseVersion = "3.2.0"; releaseVersion = "3.3.0";
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
@@ -55,8 +55,8 @@
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name; cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
gpguiHashes = { gpguiHashes = {
x86_64 = "sha256-Y0MbRebzQCPjvXUyWF8grBxGPuvDhIlnvEoEkFl5WMI="; x86_64 = "sha256-6+rt47Cu/6uLwM3FgUaP/0qvTALF+UJRFD2nkybNCTg=";
aarch64 = "sha256-TnQPKllHSRfl/ir6PYZE6dVb8XUtayg7CRZUkWE4jsw="; aarch64 = "sha256-auCDdt6LMwnYJ0B9oneoPYAVfEGa/1GkIs8XkXXv85U=";
}; };
gpguiArchive = pkgs.fetchurl { gpguiArchive = pkgs.fetchurl {
@@ -70,8 +70,8 @@
}; };
binaryHashes = { binaryHashes = {
x86_64 = "sha256-3SvFEL9C8uB+ekp/PygBw0k8vZwdbnBWnvBcfGN8e1A="; x86_64 = "sha256-nsVNOfZ1JxT1mTyiHS3VYyBjbKm5+XsHC/v/fkWwK7A=";
aarch64 = "sha256-3lVKM1lnYQsgAboBCRuzEOFY/uB8+lf+yrxIRJJZtV4="; aarch64 = "sha256-EjvkgYpOsaktnNE+Xta/GoKjILQzijW0U2bN1e/FiAQ=";
}; };
binaryArchive = pkgs.fetchurl { binaryArchive = pkgs.fetchurl {
@@ -30,6 +30,7 @@ pkgbase = globalprotect-openconnect-git
depends = gnutls depends = gnutls
depends = libp11-kit depends = libp11-kit
depends = nettle depends = nettle
depends = libhogweed.so
depends = gmp depends = gmp
depends = shared-mime-info depends = shared-mime-info
depends = desktop-file-utils depends = desktop-file-utils
@@ -42,6 +43,7 @@ pkgbase = globalprotect-openconnect-git
provides = gpgui provides = gpgui
conflicts = globalprotect-openconnect conflicts = globalprotect-openconnect
options = !strip options = !strip
options = !lto
source = globalprotect-openconnect::git+https://github.com/yuezk/GlobalProtect-openconnect.git#branch=main source = globalprotect-openconnect::git+https://github.com/yuezk/GlobalProtect-openconnect.git#branch=main
sha256sums = SKIP sha256sums = SKIP
@@ -22,7 +22,8 @@ source=("${_pkgname_prefix}::git+https://github.com/yuezk/GlobalProtect-openconn
sha256sums=("SKIP") sha256sums=("SKIP")
options=('!strip') # GCC LTO objects from native dependencies cannot be linked by Rust's LLD.
options=('!strip' '!lto')
pkgver() { pkgver() {
cd "${_pkgname_prefix}" cd "${_pkgname_prefix}"