Compare commits

..
1 Commits
Author SHA1 Message Date
Kodiak FiresmithandKevin Yue 754b220a9d fix(gpclient): keep cookie cache when the cached login gets no answer (#712)
* fix(gpclient): keep cookie cache when the cached login gets no answer

A connect or timeout error during the cached gateway login or cached portal
discovery deleted the --cookie-cache file and fell back to SAML, although the
server never rejected the cookie. Keep the cache and return the error for
unanswered requests; only clear it when the server responds.

* fix(gpclient): preserve cached cookies for all failed requests

---------

Co-authored-by: Kevin Yue <[email protected]>
2026-11-17 13:56:19 +08:00
167 changed files with 1279 additions and 9257 deletions

No files matched your search

+1 -4
View File
@@ -12,9 +12,6 @@ on:
channel:
required: true
type: string
build:
required: true
type: string
builder:
required: true
type: string
@@ -88,7 +85,7 @@ jobs:
- name: Build gpgui in Docker
env:
GPGUI_BUILDER: ${{ inputs.builder }}
GPGUI_BUILD_VERSION: ${{ inputs.build }}
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
run: |
+1 -4
View File
@@ -12,9 +12,6 @@ on:
channel:
required: true
type: string
build:
required: true
type: string
secrets:
GH_PAT:
required: true
@@ -38,7 +35,7 @@ jobs:
env:
CARGO_INCREMENTAL: '0'
CARGO_BUILD_JOBS: '2'
GPGUI_BUILD_VERSION: ${{ inputs.build }}
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
GPGUI_GIT_COMMIT: ${{ inputs.gpgui_ref }}
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
+12 -72
View File
@@ -69,10 +69,8 @@ jobs:
actions: read
contents: read
outputs:
gp_sha: ${{ steps.identity.outputs.gp_sha }}
gpgui_sha: ${{ steps.identity.outputs.gpgui_sha }}
version: ${{ steps.identity.outputs.version }}
build_version: ${{ steps.identity.outputs.build_version }}
gp_sha: ${{ steps.sources.outputs.gp_sha }}
gpgui_sha: ${{ steps.sources.outputs.gpgui_sha }}
steps:
- name: Validate stable refs
env:
@@ -121,12 +119,11 @@ jobs:
token: ${{ secrets.GH_PAT }}
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
path: selected/gpgui
- name: Record selected sources and versions
id: identity
- name: Record selected sources
id: sources
run: |
python3 scripts/record-build-sources.py selected-sources/sources.json \
--gp selected/gp --gpgui selected/gpgui \
--build-version "${{ github.run_number }}.${{ github.run_attempt }}"
--gp selected/gp --gpgui selected/gpgui
- name: Retain selected sources for retries
if: steps.restored.outputs.cached != 'true'
uses: actions/upload-artifact@v7
@@ -163,7 +160,7 @@ jobs:
# Tauri generates schemas in the source tree. Keep the host checkout read-only.
cp -R /workspace /tmp/gp-test-workspace
cd /tmp/gp-test-workspace
cargo test --workspace --locked --features gpapi/openssl-tests
cargo test --workspace --locked
# Exercise only the paths that require an actual root process.
sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \
@@ -445,7 +442,6 @@ jobs:
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
build: ${{ needs.validate-inputs.outputs.build_version }}
builder: gpgui-builder-tauri2
verify_desktop_assets: true
secrets:
@@ -459,7 +455,6 @@ jobs:
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
build: ${{ needs.validate-inputs.outputs.build_version }}
builder: gpgui-alpine-builder-tauri2
artifact_suffix: -musl
secrets:
@@ -472,7 +467,6 @@ jobs:
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
build: ${{ needs.validate-inputs.outputs.build_version }}
secrets:
GH_PAT: ${{ secrets.GH_PAT }}
@@ -489,7 +483,7 @@ jobs:
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
channel: ${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
build: ${{ needs.validate-inputs.outputs.build_version }}
build: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
secrets:
GH_PAT: ${{ secrets.GH_PAT }}
WINDOWS_UPDATE_PRIVATE_KEY: ${{ secrets.WINDOWS_UPDATE_PRIVATE_KEY }}
@@ -688,7 +682,7 @@ jobs:
FEED_URL: ${{ vars.SPARKLE_FEED_URL }}
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
run: |
set -euo pipefail
@@ -856,7 +850,7 @@ jobs:
CHANNEL: ${{ (github.event_name == 'workflow_dispatch' && inputs.channel || 'stable') }}
RELEASE_TAG: ${{ (github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name) }}
REQUEST_ID: ${{ format('{0}.{1}.macos', github.run_id, github.run_attempt) }}
BUILD_VERSION: ${{ needs.validate-inputs.outputs.build_version }}
BUILD_VERSION: ${{ format('{0}.{1}', github.run_number, github.run_attempt) }}
WORKFLOW_SHA: ${{ github.sha }}
run: |
set -euo pipefail
@@ -1055,6 +1049,7 @@ jobs:
nettle \
gmp \
gnome-keyring \
libayatana-appindicator \
polkit \
webkit2-gtk_41
pkgconf --exists libxml-2.0 liblz4 gnutls p11-kit-1 hogweed nettle gmp
@@ -1063,7 +1058,7 @@ jobs:
exec 3>&1
(
set -eu
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
@@ -1147,7 +1142,7 @@ jobs:
set -eu
export AUTOCONF_VERSION=2.72
export AUTOMAKE_VERSION=1.17
export GPGUI_BUILD_VERSION=${{ needs.validate-inputs.outputs.build_version }}
export GPGUI_BUILD_VERSION=${{ github.run_number }}.${{ github.run_attempt }}
export GPGUI_UPDATE_CHANNEL=${{ github.event_name == 'workflow_dispatch' && inputs.channel || 'stable' }}
export GPGUI_LICENSE_SIGNING_KEYS='${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}'
@@ -1318,61 +1313,6 @@ jobs:
run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
publish-macos-assets:
needs: [build-macos, gh-release]
if: >-
${{ !cancelled() &&
needs.build-macos.result == 'success' && needs.gh-release.result == 'success' }}
permissions:
actions: read
contents: write
uses: ./.github/workflows/publish-macos-assets.yaml
with:
build_run_id: ${{ github.run_id }}
release_tag: ${{ github.event_name == 'workflow_dispatch' && (inputs.channel == 'stable' && inputs.gp_branch || 'snapshot') || github.ref_name }}
expected_gui: ${{ github.event_name == 'workflow_dispatch' && inputs.macos_gui || 'nsh' }}
secrets: inherit
publish-windows-snapshot-feed:
needs: [validate-inputs, gh-release, publish-macos-assets]
if: >-
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_windows &&
needs.gh-release.result == 'success' &&
(!inputs.build_macos || needs.publish-macos-assets.result == 'success') }}
permissions:
contents: read
uses: ./.github/workflows/publish-windows-update-feed.yaml
with:
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
release_tag: snapshot
version: ${{ needs.validate-inputs.outputs.version }}
channel: snapshot
build: ${{ needs.validate-inputs.outputs.build_version }}
highlights: Development snapshot.
secrets: inherit
publish-macos-unix-snapshot-feeds:
needs: [validate-inputs, gh-release, publish-macos-assets, publish-windows-snapshot-feed]
if: >-
${{ !cancelled() && github.event_name == 'workflow_dispatch' &&
inputs.channel == 'snapshot' && !inputs.build_only && inputs.build_macos &&
needs.gh-release.result == 'success' && needs.publish-macos-assets.result == 'success' &&
(!inputs.build_windows || needs.publish-windows-snapshot-feed.result == 'success') }}
permissions:
contents: write
uses: ./.github/workflows/publish-update-feeds.yaml
with:
gpgui_ref: ${{ needs.validate-inputs.outputs.gpgui_sha }}
gp_ref: ${{ needs.validate-inputs.outputs.gp_sha }}
channel: snapshot
release_tag: snapshot
archive_name: ${{ format('GPConnect_{0}-snapshot.{1}_arm64.zip', needs.validate-inputs.outputs.version, needs.validate-inputs.outputs.build_version) }}
expected_gui: ${{ inputs.macos_gui }}
unix_platforms: ${{ (inputs.build_bsd || inputs.build_bsd_arm64) && 'linux,freebsd,openbsd' || 'linux' }}
highlights: Development snapshot.
secrets: inherit
publish-docker-image:
needs:
- validate-inputs
+1
View File
@@ -54,6 +54,7 @@ jobs:
gettext \
gmp \
gnutls \
libappindicator-gtk3 \
libp11-kit \
libsecret \
libtool \
@@ -1,21 +1,6 @@
name: Publish macOS assets
on:
workflow_call:
inputs:
build_run_id:
required: true
type: string
release_tag:
required: true
type: string
expected_gui:
required: false
default: nsh
type: string
secrets:
GH_PAT:
required: false
workflow_dispatch:
inputs:
build_run_id:
@@ -1,33 +1,6 @@
name: Publish Windows update feed
on:
workflow_call:
inputs:
gpgui_ref:
required: true
type: string
release_tag:
required: true
type: string
version:
required: true
type: string
channel:
required: true
type: string
build:
required: true
type: string
highlights:
required: true
type: string
secrets:
GH_PAT:
required: true
CLOUDFLARE_ACCOUNT_ID:
required: false
CLOUDFLARE_API_TOKEN:
required: false
workflow_dispatch:
inputs:
gpgui_ref:
Generated
+11 -74
View File
@@ -297,8 +297,6 @@ dependencies = [
"anyhow",
"block2",
"browser-launcher",
"common",
"dunce",
"gpapi",
"gtk",
"html-escape",
@@ -309,7 +307,6 @@ dependencies = [
"objc2-security",
"objc2-web-kit",
"regex",
"serde_json",
"tauri",
"tempfile",
"tiny_http",
@@ -319,10 +316,6 @@ dependencies = [
"uuid",
"uzers",
"webkit2gtk",
"webview2-com",
"windows",
"windows-sys 0.61.2",
"winreg 0.55.0",
]
[[package]]
@@ -561,7 +554,6 @@ dependencies = [
"open",
"webbrowser",
"which",
"winreg 0.55.0",
]
[[package]]
@@ -1559,7 +1551,7 @@ dependencies = [
"rustc_version",
"toml 1.1.8+spec-1.1.0",
"vswhom",
"winreg 0.56.0",
"winreg",
]
[[package]]
@@ -1663,16 +1655,6 @@ dependencies = [
"rustc_version",
]
[[package]]
name = "file-rotate"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e8e2fa049328a1f3295991407a88585805d126dfaadf74b9fe8c194c730aafc"
dependencies = [
"chrono",
"flate2",
]
[[package]]
name = "filedescriptor"
version = "0.8.3"
@@ -2147,7 +2129,6 @@ dependencies = [
"directories",
"dns-lookup",
"env_logger",
"file-rotate",
"getrandom 0.4.3",
"gtk",
"humantime",
@@ -2188,7 +2169,6 @@ dependencies = [
"uuid",
"uzers",
"whoami",
"windows-sys 0.61.2",
"x509-cert",
"xmltree",
"zeroize",
@@ -2204,6 +2184,7 @@ dependencies = [
"common",
"compile-time",
"gpapi",
"home",
"log",
"serde_json",
"tauri",
@@ -2272,14 +2253,12 @@ dependencies = [
"askama",
"chrono",
"gpapi",
"log",
"netdev",
"serde",
"serde_json",
"serde_urlencoded",
"uuid",
"uzers",
"windows",
"xmltree",
]
@@ -2294,7 +2273,6 @@ dependencies = [
"common",
"compile-time",
"env_logger",
"file-rotate",
"futures",
"getrandom 0.4.3",
"gpapi",
@@ -2315,8 +2293,6 @@ dependencies = [
"tokio-tungstenite 0.30.0",
"tokio-util",
"uuid",
"windows-service",
"windows-sys 0.61.2",
"xz2",
"zeroize",
]
@@ -2337,15 +2313,7 @@ dependencies = [
name = "gpvpnc"
version = "3.4.0"
dependencies = [
"base64 0.23.1",
"ipnet",
"log",
"serde",
"serde_json",
"tempfile",
"uuid",
"windows-sys 0.61.2",
"winreg 0.56.0",
]
[[package]]
@@ -2463,6 +2431,15 @@ dependencies = [
"digest 0.11.3",
]
[[package]]
name = "home"
version = "0.5.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "html-escape"
version = "0.3.0"
@@ -2838,9 +2815,6 @@ name = "ipnet"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
dependencies = [
"serde",
]
[[package]]
name = "is-docker"
@@ -3861,7 +3835,6 @@ dependencies = [
"log",
"pkg-config",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
@@ -6757,12 +6730,6 @@ dependencies = [
"web-sys",
]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]]
name = "winapi"
version = "0.3.9"
@@ -6913,17 +6880,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-service"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2"
dependencies = [
"bitflags 2.13.2",
"widestring",
"windows-sys 0.61.2",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
@@ -6951,15 +6907,6 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -7126,16 +7073,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "winreg"
version = "0.55.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
dependencies = [
"cfg-if",
"windows-sys 0.59.0",
]
[[package]]
name = "winreg"
version = "0.56.0"
+2
View File
@@ -23,6 +23,8 @@ serde_json.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
compile-time.workspace = true
home = "0.5.12"
# webview auth dependencies
tauri = { workspace = true, optional = true }
-3
View File
@@ -16,9 +16,6 @@ fn main() {
resolve_commit(&repo_root, &source_commit)
);
#[cfg(all(windows, feature = "webview-auth"))]
println!("cargo:rerun-if-changed=icons/windows/icon.ico");
#[cfg(feature = "webview-auth")]
tauri_build::build()
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

+6 -6
View File
@@ -1,8 +1,8 @@
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use auth::forward_auth_callback;
use auth::{BrowserAuthenticator, auth_prelogin};
use clap::Parser;
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use clap::Subcommand;
#[cfg(feature = "webview-auth")]
use gpapi::auth::AuthWindowTheme;
@@ -49,7 +49,7 @@ See 'gpauth -h' for more information.
"
)]
struct Cli {
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[command(subcommand)]
command: Option<CliCommand>,
@@ -134,7 +134,7 @@ struct Cli {
verbose: InfoLevelVerbosity,
}
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[derive(Subcommand)]
enum CliCommand {
#[command(hide = true)]
@@ -272,7 +272,7 @@ fn init_logger(cli: &Cli) {
pub async fn run() {
let cli = Cli::parse();
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
if let Err(err) = forward_auth_callback(callback).await {
eprintln!("Failed to forward authentication callback: {err}");
@@ -382,7 +382,7 @@ mod tests {
}
#[test]
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn callback_arguments_parse_separately() {
let cli = Cli::try_parse_from([
"gpauth",
-5
View File
@@ -1,5 +0,0 @@
{
"bundle": {
"icon": ["icons/windows/icon.ico"]
}
}
-29
View File
@@ -1,29 +0,0 @@
#![cfg(windows)]
use auth::AuthCallbackReceiver;
use std::{process::Stdio, time::Duration};
#[tokio::test]
async fn callback_command_forwards_between_processes() {
let receiver = AuthCallbackReceiver::bind().unwrap();
let child = tokio::process::Command::new(env!("CARGO_BIN_EXE_gpauth"))
.args([
"auth-callback",
"globalprotectcallback:cas-as=1&un=windows-fixture&token=callback-command-test",
])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.unwrap();
let (data, output) = tokio::time::timeout(Duration::from_secs(10), async {
tokio::join!(receiver.receive(), child.wait_with_output())
})
.await
.expect("callback executable did not complete");
let output = output.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
let data = data.unwrap();
assert_eq!(data.username(), "windows-fixture");
assert_eq!(data.token(), Some("callback-command-test"));
}
+154 -19
View File
@@ -36,6 +36,27 @@ fn login_response() -> String {
)
}
async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
let mut request = Vec::new();
loop {
let mut buf = [0; 4096];
let count = stream.read(&mut buf).await.unwrap();
assert_ne!(count, 0, "Request ended before its body");
request.extend_from_slice(&buf[..count]);
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
let length = headers
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.map(|value| value.trim().parse::<usize>().unwrap())
.unwrap_or(0);
if request.len() >= end + 4 + length {
return String::from_utf8(request).unwrap();
}
}
}
}
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
@@ -44,25 +65,7 @@ async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task
let mut requests = Vec::new();
for (status, body) in responses {
let (mut stream, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
loop {
let mut buf = [0; 4096];
let count = stream.read(&mut buf).await.unwrap();
assert_ne!(count, 0, "Request ended before its body");
request.extend_from_slice(&buf[..count]);
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
let length = headers
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.map(|value| value.trim().parse::<usize>().unwrap())
.unwrap_or(0);
if request.len() >= end + 4 + length {
break;
}
}
}
requests.push(String::from_utf8(request).unwrap());
requests.push(read_request(&mut stream).await);
stream
.write_all(
format!(
@@ -126,6 +129,138 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
);
}
#[tokio::test]
async fn unreachable_gateway_keeps_cached_cookie() {
// Nothing listens here: the cached gateway login gets no answer at all.
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let gateway = format!("http://{}", listener.local_addr().unwrap());
drop(listener);
let directory = tempfile::tempdir().unwrap();
let cache = directory.path().join("cookie.json");
let args = TestArgs::parse_from([
"test",
"http://unavailable-portal.invalid",
"--cookie-only",
"--cookie-cache",
cache.to_str().unwrap(),
])
.connect;
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
cookie_store::save(
&cache,
&StoredCookie::new(
args.server.clone(),
"alice".into(),
handler.os_profile.borrow().host_identity().host_id().into(),
gateway,
AuthCookieCredential::new("alice", "portal-cookie", ""),
),
)
.unwrap();
assert!(handler.handle_impl().await.is_err());
assert!(
cache.exists(),
"a login that got no answer must not delete the cookie cache"
);
}
#[tokio::test]
async fn gateway_closing_without_response_keeps_cached_cookie() {
closed_connection_keeps_cached_cookie(false).await;
}
#[tokio::test]
async fn portal_closing_without_response_keeps_cached_cookie() {
closed_connection_keeps_cached_cookie(true).await;
}
async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let worker = tokio::spawn(async move {
tokio::time::timeout(Duration::from_secs(5), async move {
if portal_discovery {
let (mut stream, _) = listener.accept().await.unwrap();
assert!(read_request(&mut stream).await.contains("/global-protect/prelogin.esp"));
let body = "<prelogin-response><status>Success</status></prelogin-response>";
stream
.write_all(
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.as_bytes(),
)
.await
.unwrap();
}
let (mut stream, _) = listener.accept().await.unwrap();
// Read the complete request, then close without sending HTTP headers.
read_request(&mut stream).await
})
.await
.expect("Connection-closing fixture timed out")
});
let directory = tempfile::tempdir().unwrap();
let cache = directory.path().join("cookie.json");
let args = TestArgs::parse_from([
"test",
&origin,
"--cookie-only",
"--cookie-cache",
cache.to_str().unwrap(),
])
.connect;
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
cookie_store::save(
&cache,
&StoredCookie::new(
args.server.clone(),
"alice".into(),
handler.os_profile.borrow().host_identity().host_id().into(),
origin.clone(),
AuthCookieCredential::new("alice", "portal-cookie", ""),
),
)
.unwrap();
let result = if portal_discovery {
handler.connect_portal_with_prelogin(&origin).await
} else {
handler.handle_impl().await
};
let error = result.unwrap_err();
let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else {
panic!("Expected a network error, got {error:?}");
};
assert!(network.is_request());
assert!(!network.is_connect());
assert!(!network.is_timeout());
assert!(cache.exists(), "an unanswered request must not delete the cookie cache");
let request = worker.await.unwrap();
assert!(request.contains("portal-cookie"));
if portal_discovery {
assert!(request.starts_with("POST /global-protect/getconfig.esp "));
} else {
assert!(request.starts_with("POST /ssl-vpn/login.esp "));
}
}
#[tokio::test]
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
let (origin, worker) = gateway(vec![
+13
View File
@@ -101,6 +101,11 @@ impl ConnectHandler<'_> {
{
return Some(Err(error));
}
// A failed request does not establish that the cookie was rejected.
if is_network_error(&error) {
warn!("Cached gateway authentication request failed: {error}");
return Some(Err(error));
}
cookie_store::clear(&path);
warn!("Cached gateway authentication failed: {error}");
return None;
@@ -830,3 +835,11 @@ mod tests {
);
}
}
/// A failed request says nothing about whether a cached cookie is still valid.
pub(super) fn is_network_error(error: &anyhow::Error) -> bool {
matches!(
error.downcast_ref::<gpapi::error::PortalError>(),
Some(gpapi::error::PortalError::NetworkError(_))
)
}
+5
View File
@@ -292,6 +292,11 @@ impl<'a> ConnectHandler<'a> {
Ok(config) => Some((cred, config)),
Err(error) => {
self.check_cancelled()?;
// A failed request does not establish that the cookie was rejected.
if gateway::is_network_error(&error) {
warn!("Cached portal authentication request failed: {error}");
return Err(error);
}
warn!("Cached portal authentication failed: {error}");
self.clear_cookie_cache();
None
+2 -12
View File
@@ -30,24 +30,14 @@ uuid = { workspace = true, features = ["v4"] }
zeroize.workspace = true
tempfile.workspace = true
getrandom = "0.4"
mac_address = "1.2.1"
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "socket", "user"] }
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
mac_address = "1.2.1"
[target.'cfg(unix)'.dev-dependencies]
mac_address = "1.2.1"
[dev-dependencies]
openssl.workspace = true
tokio-tungstenite.workspace = true
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
[target.'cfg(target_os = "macos")'.dependencies]
gpvpnc = { path = "../../crates/gpvpnc" }
[target.'cfg(windows)'.dependencies]
file-rotate = "0.8.0"
windows-service = "0.8.1"
windows-sys = { version = "0.61", features = ["Win32_System_Pipes"] }
+10 -3
View File
@@ -6,7 +6,7 @@ use std::time::Duration;
use anyhow::{Context, bail};
use clap::Parser;
use common::paths::service_lock_file;
use common::constants::GP_SERVICE_LOCK_FILE;
use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger;
#[cfg(debug_assertions)]
@@ -25,7 +25,14 @@ use crate::{
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
};
use crate::VERSION;
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[cfg(target_os = "macos")]
struct RedactingMacosLogger {
@@ -264,7 +271,7 @@ impl Cli {
return Ok(dev_service_lock_file_path(socket));
}
Ok(service_lock_file())
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
}
fn init_logger(&self) -> Arc<Redaction> {
-12
View File
@@ -1,12 +0,0 @@
use clap::Parser;
use gpapi::clap::InfoLevelVerbosity;
#[derive(Parser)]
#[command(version = crate::VERSION)]
struct Cli {
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
pub fn run() -> anyhow::Result<()> {
let cli = Cli::parse();
crate::windows_service::dispatch(cli.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info))
}
+5 -2
View File
@@ -75,7 +75,7 @@ impl DesktopClient {
loop {
match self.read_control().await? {
Some(DESKTOP_GUI_INSTALLER) => {
self.write_all(&[u8::from(crate::gui_installation::installer().is_some())]).await?;
self.write_all(&[u8::from(crate::request_dispatcher::gui_installer().is_some())]).await?;
}
Some(DESKTOP_SWITCH_BEGIN) => {
ensure!(pending.is_none(), "A GUI switch is already pending");
@@ -299,7 +299,10 @@ mod tests {
let mut reader = reader;
let mut capability = [0];
reader.read_exact(&mut capability).unwrap();
assert_eq!(capability[0], u8::from(crate::gui_installation::installer().is_some()));
assert_eq!(
capability[0],
u8::from(crate::request_dispatcher::gui_installer().is_some())
);
reader
})
.await
+1 -1
View File
@@ -366,7 +366,7 @@ mod tests {
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
);
for source in [0, u8::MAX] {
for source in [0, 4] {
let json = serde_json::json!({
"version": 1,
"anchor": {
-359
View File
@@ -1,359 +0,0 @@
use gpapi::utils::checksum::verify_checksum;
use std::{
fs::{self, File, OpenOptions, Permissions},
io::{BufReader, Read, Write},
os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::Path,
};
use tar::Archive;
use tempfile::NamedTempFile;
use xz2::read::XzDecoder;
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
#[derive(Debug)]
pub(crate) enum InstallError {
Checksum(anyhow::Error),
Install(anyhow::Error),
}
pub(crate) fn installer() -> Option<std::path::PathBuf> {
std::env::current_exe()
.ok()
.and_then(|executable| {
executable
.parent()?
.parent()
.map(|prefix| prefix.join("libexec/gpclient/gp-gui-installer"))
})
.filter(|path| path.is_file())
}
pub(crate) fn install(src: &Path, checksum: &str, target: &Path) -> Result<(), InstallError> {
let installer = installer();
install_gui_with_installer(src, checksum, target, installer.as_deref())
}
fn install_gui_with_installer(
src: &Path,
checksum: &str,
target: &Path,
installer: Option<&Path>,
) -> Result<(), InstallError> {
let Some(dir) = target.parent() else {
return Err(InstallError::Install(anyhow::anyhow!(
"Failed to get parent directory of GUI binary"
)));
};
fs::create_dir_all(dir).map_err(|err| InstallError::Install(err.into()))?;
let staged_archive = stage_gui_archive(src, dir)?;
let archive_path = staged_archive.path().to_string_lossy();
verify_checksum(&archive_path, checksum).map_err(InstallError::Checksum)?;
// A package may need to prepare downloaded executables for its runtime.
// Resolve this helper beside the running service, never from the request or PATH.
if let Some(installer) = installer {
let status = std::process::Command::new(installer)
.arg(staged_archive.path())
.arg(checksum)
.arg(target)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.status()
.map_err(|err| InstallError::Install(err.into()))?;
return if status.success() {
Ok(())
} else {
Err(InstallError::Install(anyhow::anyhow!(
"GUI package installation failed: {status}"
)))
};
}
let tar = XzDecoder::new(BufReader::new(
staged_archive
.reopen()
.map_err(|err| InstallError::Install(err.into()))?,
))
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
let mut archive = Archive::new(tar);
let binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
file
.as_file()
.set_permissions(Permissions::from_mode(0o755))
.map_err(|err| InstallError::Install(err.into()))?;
file
.as_file()
.sync_all()
.map_err(|err| InstallError::Install(err.into()))?;
file.persist(&target).map_err(|err| InstallError::Install(err.into()))?;
File::open(dir)
.and_then(|directory| directory.sync_all())
.map_err(|err| InstallError::Install(err.into()))?;
Ok(())
}
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, InstallError> {
let mut source = OpenOptions::new()
.read(true)
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
.open(src)
.map_err(|err| InstallError::Install(err.into()))?;
let metadata = source.metadata().map_err(|err| InstallError::Install(err.into()))?;
let source_size = metadata.len();
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
return Err(InstallError::Install(anyhow::anyhow!(
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
)));
}
let mut staged = NamedTempFile::new_in(dir).map_err(|err| InstallError::Install(err.into()))?;
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
.map_err(|err| InstallError::Install(err.into()))?;
if copied != source_size {
return Err(InstallError::Install(anyhow::anyhow!(
"GUI update archive changed while it was being read"
)));
}
staged.flush().map_err(|err| InstallError::Install(err.into()))?;
staged
.as_file()
.sync_all()
.map_err(|err| InstallError::Install(err.into()))?;
Ok(staged)
}
fn extract_gui_binary<R: Read>(
archive: &mut Archive<R>,
dir: &Path,
binary_name: &str,
) -> Result<NamedTempFile, InstallError> {
for entry in archive.entries().map_err(|err| InstallError::Install(err.into()))? {
let mut entry = entry.map_err(|err| InstallError::Install(err.into()))?;
let is_gui = entry
.path()
.map_err(|err| InstallError::Install(err.into()))?
.file_name()
.is_some_and(|name| name == binary_name);
if is_gui && entry.header().entry_type().is_file() {
let declared_size = entry.size();
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
return Err(InstallError::Install(anyhow::anyhow!(
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
)));
}
let mut file = NamedTempFile::new_in(dir).map_err(|err| InstallError::Install(err.into()))?;
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| InstallError::Install(err.into()))?;
if copied != declared_size {
return Err(InstallError::Install(anyhow::anyhow!(
"GUI binary size does not match its archive header"
)));
}
file.flush().map_err(|err| InstallError::Install(err.into()))?;
return Ok(file);
}
}
Err(InstallError::Install(anyhow::anyhow!(
"GUI update archive does not contain a non-empty regular {binary_name} file"
)))
}
#[cfg(test)]
mod tests {
use std::{io::Cursor, os::unix::fs::PermissionsExt};
use tar::{Builder, EntryType, Header};
use xz2::write::XzEncoder;
use super::*;
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
let mut data = Vec::new();
{
let mut builder = Builder::new(&mut data);
let mut header = Header::new_gnu();
header.set_entry_type(entry_type);
header.set_size(contents.len() as u64);
header.set_mode(0o755);
header.set_cksum();
builder.append_data(&mut header, "gpgui", contents).unwrap();
builder.finish().unwrap();
}
data
}
fn compressed_gui_archive(contents: &[u8]) -> NamedTempFile {
let tar = archive_with_entry(EntryType::Regular, contents);
let mut encoder = XzEncoder::new(Vec::new(), 6);
encoder.write_all(&tar).unwrap();
let compressed = encoder.finish().unwrap();
let mut archive = NamedTempFile::new().unwrap();
archive.write_all(&compressed).unwrap();
archive.flush().unwrap();
archive
}
#[test]
fn rejects_non_file_and_empty_gui_entries() {
let output = tempfile::tempdir().unwrap();
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
let data = archive_with_entry(entry_type, contents);
let mut archive = Archive::new(Cursor::new(data));
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
}
}
#[test]
fn extracts_non_empty_regular_gui_entry() {
let output = tempfile::tempdir().unwrap();
let data = archive_with_entry(EntryType::Regular, b"gui binary");
let mut archive = Archive::new(Cursor::new(data));
let extracted = extract_gui_binary(&mut archive, output.path(), "gpgui").unwrap();
let contents = std::fs::read(extracted.path()).unwrap();
assert_eq!(contents, b"gui binary");
}
#[test]
fn rejects_invalid_archive_sources() {
let output = tempfile::tempdir().unwrap();
assert!(stage_gui_archive(output.path(), output.path()).is_err());
let oversized = output.path().join("oversized.tar.xz");
File::create(&oversized)
.unwrap()
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
.unwrap();
assert!(stage_gui_archive(&oversized, output.path()).is_err());
}
#[test]
fn rejects_oversized_gui_entry() {
let output = tempfile::tempdir().unwrap();
let mut header = Header::new_gnu();
header.set_entry_type(EntryType::Regular);
header.set_size(MAX_GUI_BINARY_SIZE + 1);
header.set_mode(0o755);
header.set_path("gpgui").unwrap();
header.set_cksum();
let mut data = header.as_bytes().to_vec();
data.resize(512 * 3, 0);
let mut archive = Archive::new(Cursor::new(data));
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
}
#[test]
fn installs_gui_at_the_supplied_target() {
let archive = compressed_gui_archive(b"gui binary");
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpclient/gpgui");
install(archive.path(), &checksum, &target).unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"gui binary");
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
}
#[test]
fn installs_nsh_beside_tauri_without_replacing_it() {
let output = tempfile::tempdir().unwrap();
let tauri = output.path().join("gpgui");
std::fs::write(&tauri, b"tauri").unwrap();
let mut encoder = XzEncoder::new(Vec::new(), 1);
{
let mut archive = Builder::new(&mut encoder);
let mut header = Header::new_gnu();
header.set_size(3);
header.set_mode(0o755);
header.set_cksum();
archive
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
.unwrap();
archive.finish().unwrap();
}
let mut archive = NamedTempFile::new().unwrap();
archive.write_all(&encoder.finish().unwrap()).unwrap();
archive.flush().unwrap();
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let nsh = output.path().join("gpgui-nsh");
install(archive.path(), &checksum, &nsh).unwrap();
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
}
#[test]
fn checksum_failure_preserves_the_existing_gui() {
let archive = compressed_gui_archive(b"replacement");
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpclient/gpgui");
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(&target, b"existing").unwrap();
assert!(install(archive.path(), "invalid", &target).is_err());
assert_eq!(std::fs::read(target).unwrap(), b"existing");
}
#[test]
fn package_installer_receives_a_verified_staged_archive() {
let archive = compressed_gui_archive(b"gui binary");
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpgui-nsh");
let installer = output.path().join("installer");
std::fs::write(
&installer,
"#!/bin/sh\nset -eu\ntest -f \"$1\"\nprintf '%s' \"$2\" > \"$3\"\n",
)
.unwrap();
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
assert!(install_gui_with_installer(archive.path(), "invalid", &target, Some(&installer)).is_err());
assert!(!target.exists());
install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).unwrap();
assert_eq!(std::fs::read_to_string(target).unwrap(), checksum);
}
#[test]
fn package_installation_failure_preserves_the_existing_gui() {
let archive = compressed_gui_archive(b"replacement");
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpgui");
std::fs::write(&target, b"existing").unwrap();
let installer = output.path().join("installer");
std::fs::write(&installer, "#!/bin/sh\nexit 1\n").unwrap();
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
assert!(install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).is_err());
assert_eq!(std::fs::read(target).unwrap(), b"existing");
}
#[test]
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
let archive = compressed_gui_archive(&binary);
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let temporary = tempfile::tempdir().unwrap();
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| temporary.path().to_owned());
std::fs::create_dir_all(&output).unwrap();
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
let target = output.join("gpclient/gpgui");
for upgrade in [false, true] {
if upgrade {
std::fs::write(&target, b"old GUI").unwrap();
}
install(archive.path(), &checksum, &target).unwrap();
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
assert_eq!(std::fs::read(&target).unwrap(), binary);
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
}
}
}
+15 -29
View File
@@ -85,7 +85,7 @@ impl HipPreviews {
})
.await;
let result = match generated {
Ok(Ok(report)) => preview_result(&registry, session_id, report),
Ok(Ok(xml)) => preview_result(&registry, session_id, xml),
Ok(Err(error)) => {
log::warn!("HIP preview failed: {error:#}");
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
@@ -132,20 +132,17 @@ impl HipPreviews {
}
}
fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::hip::HipReport) -> ServiceResult {
let result = registry
.store_hip_preview(session_id, report.xml)
.and_then(|preview_id| {
registry
.hip_preview_chunk(session_id, preview_id, 0)
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
preview_id: preview_id.to_string(),
offset: 0,
xml,
complete,
windows_updates: report.windows_updates,
})
});
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
registry
.hip_preview_chunk(session_id, preview_id, 0)
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
preview_id: preview_id.to_string(),
offset: 0,
xml,
complete,
})
});
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
}
@@ -155,7 +152,7 @@ fn generate(
desktop_uid: Option<u32>,
identity: HostIdentity,
cancellation: CancellationToken,
) -> anyhow::Result<gpapi::hip::HipReport> {
) -> anyhow::Result<String> {
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
ensure!(
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
@@ -191,15 +188,7 @@ fn generate(
};
let xml = match &request.source {
HipSource::Disabled => bail!("HIP is disabled"),
HipSource::Generated => {
return gphip::generate_report_details(
&gphip::ReportInput {
profile,
context: gphip::ReportContext::Preview,
},
&check,
);
}
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
HipSource::Edited { .. } => {
let xml = edited_report.context("Edited HIP report is unavailable")?;
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
@@ -215,10 +204,7 @@ fn generate(
}
};
check()?;
Ok(gpapi::hip::HipReport {
xml,
windows_updates: None,
})
Ok(xml)
}
#[cfg(test)]
+44 -48
View File
@@ -1,4 +1,4 @@
use std::{io, sync::Arc};
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
use anyhow::{Context, ensure};
use gpapi::{
@@ -6,17 +6,7 @@ use gpapi::{
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
};
use gphip::{ReportContext, ReportInput};
use openconnect::HipRequest;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use openconnect::HipScript;
#[cfg(unix)]
#[path = "hip_source/unix.rs"]
mod scripts;
#[cfg(windows)]
#[path = "hip_source/windows.rs"]
mod scripts;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use scripts::script_environment;
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
pub(crate) struct HipExecution {
pub source: openconnect::HipSource,
@@ -46,7 +36,7 @@ impl HipApproval {
pub(crate) fn resolve(
source: &HipSource,
desktop_uid: Option<u32>,
restricted_desktop: bool,
brokered_macos: bool,
edited_report: Option<Arc<str>>,
profile: Option<OsProfile>,
) -> anyhow::Result<HipExecution> {
@@ -73,11 +63,22 @@ pub(crate) fn resolve(
}
HipSource::UserScript { path } => {
approval = None;
ensure_custom_available(restricted_desktop)?;
scripts::user_script(path, desktop_uid)?
ensure_custom_available(brokered_macos)?;
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
let path = PathBuf::from(path);
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
"HIP custom script must be an executable regular file"
);
let script =
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
openconnect::HipSource::Script(script)
}
HipSource::ApprovedRootScript { approval_id } => {
ensure_custom_available(restricted_desktop)?;
ensure_custom_available(brokered_macos)?;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
@@ -112,10 +113,10 @@ pub(crate) fn resolve(
})
}
fn ensure_custom_available(restricted_desktop: bool) -> anyhow::Result<()> {
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
ensure!(
!cfg!(target_os = "macos") && !restricted_desktop,
"Custom HIP scripts are unavailable on this platform"
!cfg!(target_os = "macos") && !brokered_macos,
"Custom HIP scripts are unavailable on macOS"
);
Ok(())
}
@@ -148,6 +149,27 @@ pub(crate) fn generate(
}
}
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
let user =
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
let home = user.dir.to_string_lossy().into_owned();
Ok(HipScriptEnvironment {
variables: vec![
(
"PATH".into(),
gpapi::process::collection::command_path(uid == 0)?
.into_string()
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
),
("LC_ALL".into(), "C".into()),
("HOME".into(), home.clone()),
("USER".into(), user.name.clone()),
("LOGNAME".into(), user.name),
],
cwd: home,
})
}
pub(crate) fn profile(
identity: &HostIdentity,
os: ClientOs,
@@ -158,22 +180,19 @@ pub(crate) fn profile(
control: &dyn gpapi::collection::CollectionControl,
) -> io::Result<OsProfile> {
let identity = gpapi::os_profile::desktop::identity_from_parts(
hostname.as_deref().unwrap_or(identity.computer()).into(),
host_id.as_deref().unwrap_or(identity.host_id()).into(),
hostname.unwrap_or_else(|| identity.computer().into()),
host_id.unwrap_or_else(|| identity.host_id().into()),
identity.serialno().into(),
identity.mac_addr().into(),
);
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
if let Some(hostname) = hostname {
builder = builder.computer_name_override(hostname);
}
if let Some(version) = version {
builder = builder.client_version(version);
}
if let Some(os_version) = os_version {
builder = builder.os_version(os_version);
}
gpapi::os_profile::desktop::collect_profile_with_control(builder, host_id.as_deref(), control)
gpapi::os_profile::desktop::collect_profile_with_control(builder, None, control)
}
fn generation_error(error: anyhow::Error) -> io::Error {
@@ -238,29 +257,6 @@ mod tests {
assert_eq!(profile.host_identity().serialno(), "serial");
}
#[cfg(windows)]
#[test]
fn native_windows_profile_retains_negotiated_host_id() {
let identity = gpapi::os_profile::HostIdentity::from_parts(
"device".into(),
"hardware-seed".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let profile = profile(
&identity,
ClientOs::Windows,
None,
None,
Some("negotiated-host".into()),
None,
&gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
)
.unwrap();
assert_eq!(profile.host_id(), "negotiated-host");
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
}
#[test]
fn callback_errors_preserve_cancellation() {
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
-37
View File
@@ -1,37 +0,0 @@
use anyhow::{Context, ensure};
use openconnect::{HipScript, HipScriptEnvironment};
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
pub(super) fn user_script(path: &str, desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
let path = PathBuf::from(path);
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
"HIP custom script must be an executable regular file"
);
let script =
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
Ok(openconnect::HipSource::Script(script))
}
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
let user =
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
let home = user.dir.to_string_lossy().into_owned();
Ok(HipScriptEnvironment {
variables: vec![
(
"PATH".into(),
gpapi::process::collection::command_path(uid == 0)?
.into_string()
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
),
("LC_ALL".into(), "C".into()),
("HOME".into(), home.clone()),
("USER".into(), user.name.clone()),
("LOGNAME".into(), user.name),
],
cwd: home,
})
}
-3
View File
@@ -1,3 +0,0 @@
pub(super) fn user_script(_path: &str, _desktop_uid: Option<u32>) -> anyhow::Result<openconnect::HipSource> {
anyhow::bail!("Custom HIP scripts are unavailable on Windows")
}
+1 -32
View File
@@ -1,15 +1,11 @@
#[cfg_attr(windows, path = "cli/windows.rs")]
mod cli;
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
mod credential_lease;
#[cfg(unix)]
mod desktop_client;
#[cfg(all(debug_assertions, unix))]
#[cfg(debug_assertions)]
mod dev_bootstrap;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
mod device_anchor;
#[cfg(unix)]
mod gui_installation;
mod handlers;
mod hip_preview;
mod hip_source;
@@ -17,41 +13,14 @@ mod hip_source;
mod macos_broker;
mod request_dispatcher;
mod routes;
#[cfg(unix)]
mod runtime_user;
mod session_registry;
mod vpn_script;
mod vpn_task;
#[cfg(windows)]
mod windows_patches;
mod ws_connection;
mod ws_server;
#[cfg(windows)]
mod windows_service;
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[cfg(unix)]
#[tokio::main]
async fn main() {
cli::run().await;
}
#[cfg(windows)]
fn main() -> std::process::ExitCode {
match cli::run() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(error) => {
eprintln!("{error:#}");
std::process::ExitCode::FAILURE
}
}
}
+377 -37
View File
@@ -1,15 +1,27 @@
use std::sync::{Arc, atomic::AtomicBool};
use std::{
fs::{self, File, OpenOptions, Permissions},
io::{BufReader, Read, Write},
os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::Path,
sync::{Arc, atomic::AtomicBool},
};
use gpapi::{
service::{
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
transport::{ServiceErrorCode, ServiceResult},
},
utils::redact::Redaction,
utils::{checksum::verify_checksum, redact::Redaction},
};
use log::{info, warn};
#[cfg(unix)]
use tar::Archive;
use tempfile::NamedTempFile;
use tokio::sync::Mutex;
use xz2::read::XzDecoder;
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
pub(crate) struct SessionAuthority {
pub registry: Arc<crate::session_registry::SessionRegistry>,
@@ -63,17 +75,12 @@ pub struct RequestDispatcher {
lifecycle: crate::vpn_task::LifecycleHandle,
gui_restart_requested: Arc<AtomicBool>,
redaction: Arc<Redaction>,
#[cfg(unix)]
install_lock: Mutex<()>,
gui_management_enabled: bool,
restricted_desktop: bool,
externally_brokered: bool,
}
impl RequestDispatcher {
#[cfg(windows)]
pub(crate) fn patch_checks(&self) -> Arc<crate::windows_patches::PatchChecks> {
self.lifecycle.patch_checks.clone()
}
pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver<crate::vpn_task::TunnelBinding> {
self.lifecycle.subscribe_tunnel()
}
@@ -82,16 +89,15 @@ impl RequestDispatcher {
gui_restart_requested: Arc<AtomicBool>,
redaction: Arc<Redaction>,
gui_management_enabled: bool,
restricted_desktop: bool,
externally_brokered: bool,
) -> Self {
Self {
lifecycle,
gui_restart_requested,
redaction,
#[cfg(unix)]
install_lock: Mutex::new(()),
gui_management_enabled,
restricted_desktop,
externally_brokered,
}
}
@@ -196,7 +202,7 @@ impl RequestDispatcher {
edited_report,
} => {
let prepared =
crate::vpn_task::prepare_connection(*request, self.restricted_desktop, preparation.cancellation()).await;
crate::vpn_task::prepare_connection(*request, self.externally_brokered, preparation.cancellation()).await;
return match prepared {
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
Err(error) => {
@@ -266,34 +272,31 @@ impl RequestDispatcher {
| WsRequest::GetHipApprovalStatus { .. }
| WsRequest::ReadHipPreviewChunk(_)
| WsRequest::GetLastSubmittedHipReport
| WsRequest::SetTunnelStatisticsEnabled { .. }
| WsRequest::SetWindowsPatchInterest { .. }
| WsRequest::RefreshWindowsPatches { .. } => {
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
unreachable!("session-bound request was already dispatched")
}
}
}
fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
if !self.restricted_desktop {
if !self.externally_brokered {
return Ok(());
}
if request.args().vpnc_script().is_some() {
return Err("Custom VPN scripts are unavailable on this platform");
return Err("macOS does not support custom VPN scripts");
}
if matches!(
request.args().hip_source(),
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
) {
return Err("Custom HIP scripts are unavailable on this platform");
return Err("macOS does not support custom HIP scripts");
}
if request.args().certificate().is_some() || request.args().sslkey().is_some() {
return Err("Client identity must be provided as certificate data");
return Err("macOS client identity must be provided as protected data, not root-readable paths");
}
Ok(())
}
#[cfg(unix)]
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
return ServiceResult::rejected(
@@ -305,17 +308,14 @@ impl RequestDispatcher {
let path = request.path;
let checksum = request.checksum;
let target = request.variant.update_target();
let installed = tokio::task::spawn_blocking(move || {
crate::gui_installation::install(std::path::Path::new(&path), &checksum, &target)
})
.await;
let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await;
match installed {
Ok(Ok(())) => ServiceResult::Accepted,
Ok(Err(crate::gui_installation::InstallError::Checksum(err))) => {
Ok(Err(GuiInstallError::Checksum(err))) => {
warn!("Failed to verify GUI update checksum: {err}");
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
}
Ok(Err(crate::gui_installation::InstallError::Install(err))) => {
Ok(Err(GuiInstallError::Install(err))) => {
warn!("Failed to install GUI update: {err}");
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
}
@@ -325,20 +325,335 @@ impl RequestDispatcher {
}
}
}
#[cfg(windows)]
async fn update_gui(&self, _request: UpdateGuiRequest) -> ServiceResult {
ServiceResult::rejected(
ServiceErrorCode::InvalidRequest,
"Use the Windows installer to update GP Connect",
)
}
#[derive(Debug)]
enum GuiInstallError {
Checksum(anyhow::Error),
Install(anyhow::Error),
}
pub(crate) fn gui_installer() -> Option<std::path::PathBuf> {
std::env::current_exe()
.ok()
.and_then(|executable| {
executable
.parent()?
.parent()
.map(|prefix| prefix.join("libexec/gpclient/gp-gui-installer"))
})
.filter(|path| path.is_file())
}
fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiInstallError> {
let installer = gui_installer();
install_gui_with_installer(src, checksum, target, installer.as_deref())
}
fn install_gui_with_installer(
src: &Path,
checksum: &str,
target: &Path,
installer: Option<&Path>,
) -> Result<(), GuiInstallError> {
let Some(dir) = target.parent() else {
return Err(GuiInstallError::Install(anyhow::anyhow!(
"Failed to get parent directory of GUI binary"
)));
};
fs::create_dir_all(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
let staged_archive = stage_gui_archive(src, dir)?;
let archive_path = staged_archive.path().to_string_lossy();
verify_checksum(&archive_path, checksum).map_err(GuiInstallError::Checksum)?;
// A package may need to prepare downloaded executables for its runtime.
// Resolve this helper beside the running service, never from the request or PATH.
if let Some(installer) = installer {
let status = std::process::Command::new(installer)
.arg(staged_archive.path())
.arg(checksum)
.arg(target)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.status()
.map_err(|err| GuiInstallError::Install(err.into()))?;
return if status.success() {
Ok(())
} else {
Err(GuiInstallError::Install(anyhow::anyhow!(
"GUI package installation failed: {status}"
)))
};
}
let tar = XzDecoder::new(BufReader::new(
staged_archive
.reopen()
.map_err(|err| GuiInstallError::Install(err.into()))?,
))
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
let mut archive = Archive::new(tar);
let binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
file
.as_file()
.set_permissions(Permissions::from_mode(0o755))
.map_err(|err| GuiInstallError::Install(err.into()))?;
file
.as_file()
.sync_all()
.map_err(|err| GuiInstallError::Install(err.into()))?;
file
.persist(&target)
.map_err(|err| GuiInstallError::Install(err.into()))?;
File::open(dir)
.and_then(|directory| directory.sync_all())
.map_err(|err| GuiInstallError::Install(err.into()))?;
Ok(())
}
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
let mut source = OpenOptions::new()
.read(true)
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
.open(src)
.map_err(|err| GuiInstallError::Install(err.into()))?;
let metadata = source.metadata().map_err(|err| GuiInstallError::Install(err.into()))?;
let source_size = metadata.len();
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
return Err(GuiInstallError::Install(anyhow::anyhow!(
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
)));
}
let mut staged = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
.map_err(|err| GuiInstallError::Install(err.into()))?;
if copied != source_size {
return Err(GuiInstallError::Install(anyhow::anyhow!(
"GUI update archive changed while it was being read"
)));
}
staged.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
staged
.as_file()
.sync_all()
.map_err(|err| GuiInstallError::Install(err.into()))?;
Ok(staged)
}
fn extract_gui_binary<R: Read>(
archive: &mut Archive<R>,
dir: &Path,
binary_name: &str,
) -> Result<NamedTempFile, GuiInstallError> {
for entry in archive.entries().map_err(|err| GuiInstallError::Install(err.into()))? {
let mut entry = entry.map_err(|err| GuiInstallError::Install(err.into()))?;
let is_gui = entry
.path()
.map_err(|err| GuiInstallError::Install(err.into()))?
.file_name()
.is_some_and(|name| name == binary_name);
if is_gui && entry.header().entry_type().is_file() {
let declared_size = entry.size();
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
return Err(GuiInstallError::Install(anyhow::anyhow!(
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
)));
}
let mut file = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| GuiInstallError::Install(err.into()))?;
if copied != declared_size {
return Err(GuiInstallError::Install(anyhow::anyhow!(
"GUI binary size does not match its archive header"
)));
}
file.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
return Ok(file);
}
}
Err(GuiInstallError::Install(anyhow::anyhow!(
"GUI update archive does not contain a non-empty regular {binary_name} file"
)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vpn_task::test_connect_request as test_request;
use gpapi::gateway::Gateway;
use std::{io::Cursor, os::unix::fs::PermissionsExt};
use gpapi::{
gateway::Gateway,
service::transport::{ServiceErrorCode, ServiceResult},
};
use tar::{Builder, EntryType, Header};
use xz2::write::XzEncoder;
use super::*;
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
let mut data = Vec::new();
{
let mut builder = Builder::new(&mut data);
let mut header = Header::new_gnu();
header.set_entry_type(entry_type);
header.set_size(contents.len() as u64);
header.set_mode(0o755);
header.set_cksum();
builder.append_data(&mut header, "gpgui", contents).unwrap();
builder.finish().unwrap();
}
data
}
fn compressed_gui_archive(contents: &[u8]) -> NamedTempFile {
let tar = archive_with_entry(EntryType::Regular, contents);
let mut encoder = XzEncoder::new(Vec::new(), 6);
encoder.write_all(&tar).unwrap();
let compressed = encoder.finish().unwrap();
let mut archive = NamedTempFile::new().unwrap();
archive.write_all(&compressed).unwrap();
archive.flush().unwrap();
archive
}
#[test]
fn rejects_non_file_and_empty_gui_entries() {
let output = tempfile::tempdir().unwrap();
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
let data = archive_with_entry(entry_type, contents);
let mut archive = Archive::new(Cursor::new(data));
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
}
}
#[test]
fn extracts_non_empty_regular_gui_entry() {
let output = tempfile::tempdir().unwrap();
let data = archive_with_entry(EntryType::Regular, b"gui binary");
let mut archive = Archive::new(Cursor::new(data));
let extracted = extract_gui_binary(&mut archive, output.path(), "gpgui").unwrap();
let contents = std::fs::read(extracted.path()).unwrap();
assert_eq!(contents, b"gui binary");
}
#[test]
fn rejects_invalid_archive_sources() {
let output = tempfile::tempdir().unwrap();
assert!(stage_gui_archive(output.path(), output.path()).is_err());
let oversized = output.path().join("oversized.tar.xz");
File::create(&oversized)
.unwrap()
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
.unwrap();
assert!(stage_gui_archive(&oversized, output.path()).is_err());
}
#[test]
fn rejects_oversized_gui_entry() {
let output = tempfile::tempdir().unwrap();
let mut header = Header::new_gnu();
header.set_entry_type(EntryType::Regular);
header.set_size(MAX_GUI_BINARY_SIZE + 1);
header.set_mode(0o755);
header.set_path("gpgui").unwrap();
header.set_cksum();
let mut data = header.as_bytes().to_vec();
data.resize(512 * 3, 0);
let mut archive = Archive::new(Cursor::new(data));
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
}
#[test]
fn installs_gui_at_the_supplied_target() {
let archive = compressed_gui_archive(b"gui binary");
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpclient/gpgui");
install_gui_at(archive.path(), &checksum, &target).unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"gui binary");
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
}
#[test]
fn installs_nsh_beside_tauri_without_replacing_it() {
let output = tempfile::tempdir().unwrap();
let tauri = output.path().join("gpgui");
std::fs::write(&tauri, b"tauri").unwrap();
let mut encoder = XzEncoder::new(Vec::new(), 1);
{
let mut archive = Builder::new(&mut encoder);
let mut header = Header::new_gnu();
header.set_size(3);
header.set_mode(0o755);
header.set_cksum();
archive
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
.unwrap();
archive.finish().unwrap();
}
let mut archive = NamedTempFile::new().unwrap();
archive.write_all(&encoder.finish().unwrap()).unwrap();
archive.flush().unwrap();
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let nsh = output.path().join("gpgui-nsh");
install_gui_at(archive.path(), &checksum, &nsh).unwrap();
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
}
#[test]
fn checksum_failure_preserves_the_existing_gui() {
let archive = compressed_gui_archive(b"replacement");
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpclient/gpgui");
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(&target, b"existing").unwrap();
assert!(install_gui_at(archive.path(), "invalid", &target).is_err());
assert_eq!(std::fs::read(target).unwrap(), b"existing");
}
#[test]
fn package_installer_receives_a_verified_staged_archive() {
let archive = compressed_gui_archive(b"gui binary");
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpgui-nsh");
let installer = output.path().join("installer");
std::fs::write(
&installer,
"#!/bin/sh\nset -eu\ntest -f \"$1\"\nprintf '%s' \"$2\" > \"$3\"\n",
)
.unwrap();
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
assert!(install_gui_with_installer(archive.path(), "invalid", &target, Some(&installer)).is_err());
assert!(!target.exists());
install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).unwrap();
assert_eq!(std::fs::read_to_string(target).unwrap(), checksum);
}
#[test]
fn package_installation_failure_preserves_the_existing_gui() {
let archive = compressed_gui_archive(b"replacement");
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let output = tempfile::tempdir().unwrap();
let target = output.path().join("gpgui");
std::fs::write(&target, b"existing").unwrap();
let installer = output.path().join("installer");
std::fs::write(&installer, "#!/bin/sh\nexit 1\n").unwrap();
std::fs::set_permissions(&installer, Permissions::from_mode(0o755)).unwrap();
assert!(install_gui_with_installer(archive.path(), &checksum, &target, Some(&installer)).is_err());
assert_eq!(std::fs::read(target).unwrap(), b"existing");
}
#[tokio::test]
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
let dispatcher = RequestDispatcher::new(
@@ -385,7 +700,7 @@ mod tests {
let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string()));
assert_eq!(
dispatcher.validate_connect_request(&custom),
Err("Custom VPN scripts are unavailable on this platform")
Err("macOS does not support custom VPN scripts")
);
}
@@ -394,7 +709,32 @@ mod tests {
});
assert_eq!(
dispatcher.validate_connect_request(&custom),
Err("Custom HIP scripts are unavailable on this platform")
Err("macOS does not support custom HIP scripts")
);
}
#[test]
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
let archive = compressed_gui_archive(&binary);
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let temporary = tempfile::tempdir().unwrap();
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| temporary.path().to_owned());
std::fs::create_dir_all(&output).unwrap();
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
let target = output.join("gpclient/gpgui");
for upgrade in [false, true] {
if upgrade {
std::fs::write(&target, b"old GUI").unwrap();
}
install_gui_at(archive.path(), &checksum, &target).unwrap();
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
assert_eq!(std::fs::read(&target).unwrap(), binary);
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
}
}
}
-36
View File
@@ -62,8 +62,6 @@ enum SessionStatus {
}
struct SessionRecord {
#[cfg(windows)]
windows_identity: Option<Arc<gpapi::windows::PipeClientIdentity>>,
non_tunnel: Option<AttachmentAttempt>,
closed_attachment: Option<Uuid>,
secret: Zeroizing<[u8; 32]>,
@@ -257,8 +255,6 @@ impl SessionRegistry {
sessions.insert(
credential.session_id(),
SessionRecord {
#[cfg(windows)]
windows_identity: None,
non_tunnel: None,
closed_attachment: None,
secret: Zeroizing::new(*credential.secret()),
@@ -277,38 +273,6 @@ impl SessionRegistry {
Ok(credential)
}
#[cfg(windows)]
pub(crate) fn issue_windows(
&self,
product_version: &str,
identity: Arc<gpapi::windows::PipeClientIdentity>,
) -> Result<Arc<SessionCredential>, SessionError> {
let credential = self.issue(product_version, None)?;
// The credential is not published until its Windows owner is retained.
self
.sessions
.lock()
.map_err(|_| SessionError::Unavailable)?
.get_mut(&credential.session_id())
.ok_or(SessionError::Unauthorized)?
.windows_identity = Some(identity);
Ok(credential)
}
#[cfg(windows)]
pub(crate) fn windows_identity(
&self,
session_id: Uuid,
) -> Result<Arc<gpapi::windows::PipeClientIdentity>, SessionError> {
self
.sessions
.lock()
.map_err(|_| SessionError::Unavailable)?
.get(&session_id)
.and_then(|record| record.windows_identity.clone())
.ok_or(SessionError::Unauthorized)
}
#[cfg(target_os = "macos")]
pub fn is_empty(&self) -> bool {
let Ok(mut sessions) = self.sessions.lock() else {
+1 -7
View File
@@ -1,9 +1,6 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[path = "privileged_unix.rs"]
mod platform;
#[cfg(windows)]
#[path = "windows.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform;
@@ -11,8 +8,7 @@ mod platform;
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd",
target_os = "macos",
windows
target_os = "macos"
)))]
#[path = "default.rs"]
mod platform;
@@ -20,5 +16,3 @@ mod platform;
mod selection;
pub(crate) use platform::builder;
#[cfg(windows)]
pub(crate) use platform::recover_network;
-24
View File
@@ -1,24 +0,0 @@
use gpapi::service::request::ConnectArgs;
use openconnect::{Vpn, VpnBuilder};
use std::sync::Mutex;
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
pub(crate) fn recover_network() -> std::io::Result<()> {
gpvpnc::windows::recover(RECOVERY_KEY)
}
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
anyhow::ensure!(
args.vpnc_script().is_none(),
"Windows does not support custom VPN scripts"
);
let network = Mutex::new(gpvpnc::windows::NetworkConfigurator::new(RECOVERY_KEY)?);
Ok(
Vpn::builder(server, cookie).network_configuration_handler(move |configuration| {
network
.lock()
.map_err(|_| std::io::Error::other("Windows network state is unavailable"))?
.configure(&configuration.reason, &configuration.environment)
}),
)
}
+4 -9
View File
@@ -31,8 +31,6 @@ mod script_tun;
#[derive(Clone)]
pub(crate) struct LifecycleHandle {
#[cfg(windows)]
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
events: mpsc::Sender<LifecycleEvent>,
admissions: Arc<Mutex<Admissions>>,
tunnel: watch::Sender<TunnelBinding>,
@@ -128,7 +126,6 @@ impl LifecycleHandle {
ServiceResult::Accepted
}
#[cfg(any(unix, test))]
pub async fn disconnect_and_wait(&self) -> bool {
let completion = {
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
@@ -450,7 +447,7 @@ pub(crate) struct VpnTask {
events: mpsc::Receiver<LifecycleEvent>,
lifecycle: LifecycleHandle,
vpn_state_tx: watch::Sender<VpnState>,
restricted_desktop: bool,
brokered_macos: bool,
registry: Arc<crate::session_registry::SessionRegistry>,
active: Option<ActiveAttempt>,
cancel_token: CancellationToken,
@@ -459,13 +456,11 @@ pub(crate) struct VpnTask {
impl VpnTask {
pub fn new(
vpn_state_tx: watch::Sender<VpnState>,
restricted_desktop: bool,
brokered_macos: bool,
registry: Arc<crate::session_registry::SessionRegistry>,
) -> (Self, LifecycleHandle) {
let (events_tx, events) = mpsc::channel(4);
let lifecycle = LifecycleHandle {
#[cfg(windows)]
patch_checks: crate::windows_patches::PatchChecks::new(),
events: events_tx,
admissions: Arc::new(Mutex::new(Admissions::default())),
tunnel: watch::channel(TunnelBinding::default()).0,
@@ -475,7 +470,7 @@ impl VpnTask {
events,
lifecycle: lifecycle.clone(),
vpn_state_tx,
restricted_desktop,
brokered_macos,
registry,
active: None,
cancel_token: CancellationToken::new(),
@@ -622,7 +617,7 @@ impl VpnTask {
desktop_uid,
edited_report,
session_id,
restricted_desktop: self.restricted_desktop,
brokered_macos: self.brokered_macos,
registry: self.registry.clone(),
lifecycle: self.lifecycle.clone(),
},
+7 -12
View File
@@ -30,7 +30,7 @@ pub(super) struct ConnectionResources {
/// the complete ledger and its retained identity resources to the service.
pub(crate) async fn prepare_connection(
request: ConnectRequest,
restricted_desktop: bool,
brokered_macos: bool,
cancellation: CancellationToken,
) -> anyhow::Result<PreparedConnection> {
let mode = request.args().packet_delivery().clone();
@@ -77,16 +77,11 @@ pub(crate) async fn prepare_connection(
};
check()?;
let args = setup_request.args();
let identity = super::prepare_identity(args, restricted_desktop || non_tunnel)?;
#[cfg(target_os = "macos")]
let directory = restricted_desktop.then(|| std::path::PathBuf::from("/var/run/com.yuezk.gpgui"));
#[cfg(windows)]
let directory = Some(common::paths::service_private_dir());
#[cfg(all(unix, not(target_os = "macos")))]
let directory: Option<std::path::PathBuf> = None;
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
let identity_files = identity
.as_ref()
.map(|identity| identity.write_files(directory.as_deref()))
.map(|identity| identity.write_files(directory))
.transpose()?;
let host = args.host_identity().context("Authenticated host identity is missing")?;
let profile = crate::hip_source::profile(
@@ -186,8 +181,8 @@ mod tests {
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
#[tokio::test]
async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() {
for (restricted_desktop, non_tunnel) in [(true, false), (false, true), (true, true)] {
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
.with_certificate(Some("/identity.pem".into()));
@@ -197,7 +192,7 @@ mod tests {
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
}
let request = serde_json::from_value(wire).unwrap();
let error = prepare_connection(request, restricted_desktop, CancellationToken::new())
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
.await
.err()
.unwrap();
+8 -29
View File
@@ -20,7 +20,7 @@ pub(super) struct AttemptInput {
pub desktop_uid: Option<u32>,
pub edited_report: Option<Arc<str>>,
pub session_id: Option<Uuid>,
pub restricted_desktop: bool,
pub brokered_macos: bool,
pub registry: Arc<crate::session_registry::SessionRegistry>,
pub lifecycle: LifecycleHandle,
}
@@ -31,7 +31,6 @@ struct TunnelInput {
source: Arc<openconnect::HipSource>,
session_id: Option<Uuid>,
registry: Arc<crate::session_registry::SessionRegistry>,
#[cfg(unix)]
desktop_uid: Option<u32>,
}
@@ -50,30 +49,13 @@ pub(super) fn spawn(
) -> JoinHandle<()> {
tokio::spawn(async move {
let attempt = input.attempt;
#[cfg(windows)]
let _patch_interest = {
let args = input.connection.request.args();
let profile = &input.connection.resources.profile;
(matches!(args.hip_source(), gpapi::hip::HipSource::Generated)
&& profile.is_native()
&& profile.client_os() == gpapi::os_profile::ClientOs::Windows
&& (input.connection.request.plan().policy().collect_hip_data()
|| input
.connection
.request
.plan()
.members()
.iter()
.any(|member| member.authentication.mode() == SessionMode::Tunnel)))
.then(|| input.lifecycle.patch_checks.consumer())
};
let mut failure = None;
let mut approval = None;
if !cancellation.is_cancelled() {
let request = input.connection.request.clone();
let resources = input.connection.resources.clone();
let desktop_uid = input.desktop_uid;
let brokered = input.restricted_desktop;
let brokered = input.brokered_macos;
let edited = input.edited_report.clone();
let setup_cancel = cancellation.clone();
let execution = tokio::task::spawn_blocking(move || {
@@ -123,7 +105,6 @@ pub(super) fn spawn(
source,
session_id: input.session_id,
registry: input.registry.clone(),
#[cfg(unix)]
desktop_uid: input.desktop_uid,
};
input.connection.request.release_script_tun_bootstrap();
@@ -272,14 +253,12 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
),
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
#[cfg(unix)]
let owner = input.desktop_uid.context("Desktop identity is unavailable")?;
#[cfg(windows)]
let owner = input
.registry
.windows_identity(input.session_id.context("Desktop session is unavailable")?)?;
let (builder, script_tun) =
super::script_tun::builder(member.gateway.server(), member.authentication.cookie(), request, owner)?;
let (builder, script_tun) = super::script_tun::builder(
member.gateway.server(),
member.authentication.cookie(),
request,
input.desktop_uid.context("Desktop identity is unavailable")?,
)?;
(builder, Some(script_tun))
}
};
+123 -143
View File
@@ -1,19 +1,40 @@
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
use super::{LifecycleEvent, LifecycleHandle};
use anyhow::{Context, bail, ensure};
use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message};
use openconnect::{Vpn, tunnel::Event};
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
use std::{sync::Arc, time::Duration};
use tokio::{sync::mpsc, time::Instant};
use tokio::{net::UnixStream, sync::mpsc, time::Instant};
use tokio_util::sync::CancellationToken;
#[cfg(unix)]
#[path = "script_tun/unix.rs"]
mod platform;
#[cfg(windows)]
#[path = "script_tun/windows.rs"]
mod platform;
pub(super) use platform::{PreparedScriptTun, builder};
pub(super) struct PreparedScriptTun {
pub control: std::os::unix::net::UnixStream,
pub bootstrap: Bootstrap,
}
pub(super) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
uid: u32,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
ensure!(uid != 0, "Script-tun worker requires a desktop user");
let (control, child) = std::os::unix::net::UnixStream::pair()?;
let builder = Vpn::builder(server, cookie).script_tun_program(
request.program.to_str().context("Program is not UTF-8")?,
&request.args,
uid,
child.into(),
)?;
Ok((
builder,
PreparedScriptTun {
control,
bootstrap: request.bootstrap.clone(),
},
))
}
#[derive(Debug)]
pub(super) struct NetworkChanged;
@@ -32,7 +53,7 @@ enum Native {
pub(super) async fn run(
identity: Identity,
vpn: Arc<Vpn>,
mut prepared: PreparedScriptTun,
prepared: PreparedScriptTun,
approval: &crate::hip_source::HipApproval,
lifecycle: &LifecycleHandle,
cancellation: CancellationToken,
@@ -41,8 +62,6 @@ pub(super) async fn run(
registry: Arc<crate::session_registry::SessionRegistry>,
sessions: &mut gpapi::session::desktop::GatewaySessions,
) -> anyhow::Result<()> {
let channel = prepared.connect().await?;
let mut control = ConsumerControl::new(channel);
let attempt = identity.attempt;
let (native_tx, native) = mpsc::channel(64);
let observed = native_tx.clone();
@@ -58,7 +77,7 @@ pub(super) async fn run(
monitor: monitor.clone(),
})
.await;
if event_result.is_err() || cancellation.is_cancelled() {
if event_result.is_err() {
monitor.stop().await;
return Ok(());
}
@@ -72,50 +91,31 @@ pub(super) async fn run(
tokio::pin!(worker);
let mut worker_done = false;
let stop = cancellation.child_token();
let result = {
let supervisor = supervise(
identity,
&mut control,
std::mem::take(&mut prepared.bootstrap),
native,
stop.clone(),
events,
);
tokio::pin!(supervisor);
let mut supervisor_done = false;
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
let result = loop {
tokio::select! {
biased;
result = &mut supervisor => { supervisor_done = true; break result; }
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
_ = approval_poll.tick() => {
if !approval.approval_is_valid() || !registry.has_session(session_id) {
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
}
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
tokio::pin!(supervisor);
let mut supervisor_done = false;
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
let result = loop {
tokio::select! {
biased;
result = &mut supervisor => { supervisor_done = true; break result; }
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
_ = approval_poll.tick() => {
if !approval.approval_is_valid() || !registry.has_session(session_id) {
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
}
}
};
stop.cancel();
// Keep the consumer's control and packet endpoints alive until OpenConnect
// consumes cancellation and logs out. Early EOF would interrupt that logout.
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
if !supervisor_done {
let _ = supervisor.await;
}
result
};
control.stop().await;
let cleanup = prepared.stop_worker();
monitor.stop().await;
if result.is_ok() {
cleanup?;
} else if let Err(error) = cleanup {
log::warn!("Could not stop packet worker: {error:#}");
stop.cancel();
if !supervisor_done {
let _ = supervisor.await;
}
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
monitor.stop().await;
result
}
@@ -128,113 +128,93 @@ enum WorkerState {
Suspending,
}
// Own the channel independently of its supervision future so run() can drain
// the native VPN before telling the consumer to stop or closing its endpoints.
struct ConsumerControl {
output: tokio::io::WriteHalf<platform::ControlStream>,
messages: mpsc::Receiver<std::io::Result<Message>>,
reader: tokio::task::JoinHandle<()>,
}
impl ConsumerControl {
fn new(channel: platform::ControlStream) -> Self {
let (mut input, output) = tokio::io::split(channel);
let (messages_tx, messages) = mpsc::channel(8);
let reader = tokio::spawn(async move {
loop {
let message = receive(&mut input).await;
let failed = message.is_err();
if messages_tx.send(message).await.is_err() || failed {
break;
}
}
});
Self {
output,
messages,
reader,
}
}
async fn stop(&mut self) {
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut self.output, &Message::Stop)).await;
self.reader.abort();
let _ = (&mut self.reader).await;
}
}
impl Drop for ConsumerControl {
fn drop(&mut self) {
self.reader.abort();
}
}
// Production and generic-consumer tests exercise this same state machine.
// The same control loop runs against native observations in production and a
// generic socket consumer in tests; VPN ownership stays in run().
async fn supervise(
identity: Identity,
control: &mut ConsumerControl,
mut bootstrap: Bootstrap,
mut prepared: PreparedScriptTun,
mut native: mpsc::Receiver<Native>,
cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>,
) -> anyhow::Result<()> {
let attempt = identity.attempt;
let ConsumerControl { output, messages, .. } = control;
prepared.control.set_nonblocking(true)?;
let control = UnixStream::from_std(prepared.control)?;
let (mut input, mut output) = control.into_split();
let (messages_tx, mut messages) = mpsc::channel(8);
let reader = tokio::spawn(async move {
loop {
let message = receive(&mut input).await;
let failed = message.is_err();
if messages_tx.send(message).await.is_err() || failed {
break;
}
}
});
let mut network = None;
let mut session = None;
let mut worker = WorkerState::Preparing;
let mut online = false;
let mut was_connected = false;
let mut deadline: Option<Instant> = None;
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
worker = WorkerState::Ready;
}
Message::Activated if worker == WorkerState::Activating => {
ensure!(online, "Script-tun activation completed while VPN was offline");
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
worker = WorkerState::Active; was_connected = true; deadline = None;
}
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
Message::Error { message } => bail!("Script-tun worker: {message}"),
_ => bail!("Unexpected script-tun consumer message"),
},
event = native.recv() => match event.context("Native event stream ended")? {
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
Native::Event(Event::Configuration(config)) => {
let observed = config.context("VPN configuration is absent").and_then(observed_network);
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
let observed = observed?;
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
else {
send(output, &Message::Configure { identity, bootstrap: std::mem::take(&mut bootstrap), network: observed.clone() }).await?;
network = Some(observed);
deadline = Some(Instant::now() + Duration::from_secs(10));
let result = async {
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
worker = WorkerState::Ready;
}
}
Native::Event(Event::Reconnecting) => {
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
online = false;
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
send(output, &Message::Suspend).await?; worker = WorkerState::Suspending;
deadline = Some(Instant::now() + Duration::from_secs(10));
Message::Activated if worker == WorkerState::Activating => {
ensure!(online, "Script-tun activation completed while VPN was offline");
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
worker = WorkerState::Active; was_connected = true; deadline = None;
}
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
Message::Error { message } => bail!("Script-tun worker: {message}"),
_ => bail!("Unexpected script-tun consumer message"),
},
event = native.recv() => match event.context("Native event stream ended")? {
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
Native::Event(Event::Configuration(config)) => {
let observed = config.context("VPN configuration is absent").and_then(observed_network);
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
let observed = observed?;
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
else {
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
network = Some(observed);
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnecting) => {
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
online = false;
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
}
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
send(output, &Message::Activate).await?;
worker = WorkerState::Activating;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Ok(())
Ok(())
}.await;
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await;
drop(output);
reader.abort();
let _ = reader.await;
result
}
fn observed_network(
@@ -263,5 +243,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa
Ok(())
}
#[cfg(all(test, unix))]
#[cfg(test)]
mod tests;
@@ -1,8 +1,6 @@
use super::*;
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
use openconnect::{VpnSessionInfo, tunnel::Configuration};
use tokio::io::AsyncWriteExt;
use tokio::net::UnixStream;
// A generic consumer, with no proxy settings or private worker protocol.
struct Consumer {
@@ -25,26 +23,16 @@ impl Consumer {
launch_id: uuid::Uuid::new_v4(),
};
let cancel = CancellationToken::new();
let stopped = cancel.clone();
let task = tokio::spawn(async move {
let mut prepared = PreparedScriptTun {
control: Some(control),
let task = tokio::spawn(supervise(
identity,
PreparedScriptTun {
control,
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
};
let channel = prepared.connect().await?;
let mut control = ConsumerControl::new(channel);
let result = supervise(
identity,
&mut control,
prepared.bootstrap,
observations,
stopped,
events,
)
.await;
control.stop().await;
result
});
},
observations,
cancel.clone(),
events,
));
Self {
control: UnixStream::from_std(child).unwrap(),
native,
@@ -303,36 +291,3 @@ async fn reconnect_during_activation_returns_clear_error_without_connected() {
);
assert!(consumer.events.try_recv().is_err());
}
#[tokio::test]
async fn supervision_completion_keeps_consumer_alive_until_owner_stops_it() {
let (channel, mut peer) = UnixStream::pair().unwrap();
let mut control = ConsumerControl::new(channel);
let (_native, observations) = mpsc::channel(1);
let (events, _notifications) = mpsc::channel(1);
let cancellation = CancellationToken::new();
cancellation.cancel();
supervise(
Identity {
service_instance: uuid::Uuid::new_v4(),
attempt: 1,
launch_id: uuid::Uuid::new_v4(),
},
&mut control,
Bootstrap::default(),
observations,
cancellation,
events,
)
.await
.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(30), receive(&mut peer))
.await
.is_err()
);
control.stop().await;
assert!(matches!(receive(&mut peer).await.unwrap(), Message::Stop));
drop(control);
assert!(receive(&mut peer).await.is_err());
}
@@ -1,44 +0,0 @@
use anyhow::{Context, ensure};
use gpapi::script_tun::{Bootstrap, ScriptTunRequest};
use openconnect::{Vpn, VpnBuilder};
pub(super) type ControlStream = tokio::net::UnixStream;
pub(crate) struct PreparedScriptTun {
pub(super) control: Option<std::os::unix::net::UnixStream>,
pub bootstrap: Bootstrap,
}
pub(crate) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
uid: u32,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
ensure!(uid != 0, "Script-tun worker requires a desktop user");
let (control, child) = std::os::unix::net::UnixStream::pair()?;
let builder = Vpn::builder(server, cookie).script_tun_program(
request.program.to_str().context("Program is not UTF-8")?,
&request.args,
uid,
child.into(),
)?;
Ok((
builder,
PreparedScriptTun {
control: Some(control),
bootstrap: request.bootstrap.clone(),
},
))
}
impl PreparedScriptTun {
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
let control = self.control.take().context("Worker control pipe is unavailable")?;
control.set_nonblocking(true)?;
Ok(tokio::net::UnixStream::from_std(control)?)
}
// The native OpenConnect Unix launcher owns/reaps its child on disconnect.
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
Ok(())
}
}
@@ -1,69 +0,0 @@
use anyhow::{Context, ensure};
use gpapi::{
process::user_process::UserProcess,
script_tun::{Bootstrap, ScriptTunRequest},
windows::PipeClientIdentity,
};
use openconnect::{Vpn, VpnBuilder};
use std::{os::windows::io::AsRawHandle, sync::Arc, time::Duration};
use tokio::net::windows::named_pipe::NamedPipeServer;
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
pub(super) type ControlStream = NamedPipeServer;
pub(crate) struct PreparedScriptTun {
control: Option<NamedPipeServer>,
worker: UserProcess,
pub(super) bootstrap: Bootstrap,
}
pub(crate) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
owner: Arc<PipeClientIdentity>,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
let attempt = uuid::Uuid::new_v4();
let control_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Control");
let packet_name = format!(r"\\.\pipe\GPConnect.ScriptTun.{attempt}.Packets");
let control = owner.create_control_pipe(&control_name)?;
let mut packets = owner.create_packet_pipe(&packet_name)?;
let worker = UserProcess::launch(
owner.primary_token(),
&request.program,
&request.args,
&[
("OPENCONNECT_SCRIPT_TUN_CONTROL_PIPE", &control_name),
("VPN_PIPE", &packet_name),
],
)
.context("Could not launch the user-session packet worker")?;
packets.connect(worker.id(), Duration::from_secs(10))?;
// PacketPipe creates only raw overlapped Win32 I/O and never registers IOCP.
let builder = unsafe { Vpn::builder(server, cookie).script_tun_pipe(packets.into_handle()) };
Ok((
builder,
PreparedScriptTun {
control: Some(control),
worker,
bootstrap: request.bootstrap.clone(),
},
))
}
impl PreparedScriptTun {
pub(super) async fn connect(&mut self) -> anyhow::Result<ControlStream> {
ensure!(!self.worker.has_exited()?, "The packet worker exited during startup");
let control = self.control.take().context("Worker control pipe is unavailable")?;
tokio::time::timeout(Duration::from_secs(10), control.connect())
.await
.context("Packet control connection timed out")??;
let mut pid = 0;
if unsafe { GetNamedPipeClientProcessId(control.as_raw_handle(), &mut pid) } == 0 {
return Err(std::io::Error::last_os_error().into());
}
ensure!(pid == self.worker.id(), "Unexpected packet control client");
Ok(control)
}
pub(super) fn stop_worker(&mut self) -> anyhow::Result<()> {
Ok(self.worker.stop()?)
}
}
-159
View File
@@ -1,159 +0,0 @@
//! One service-owned local patch search, independent of report generation.
use gpapi::{
collection::{CollectionBudget, CollectionControl},
process::collection::CollectorCommands,
};
use std::{
collections::HashSet,
sync::{Arc, Mutex},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
const INTERVAL: Duration = Duration::from_secs(15 * 60);
const SEARCH_TIMEOUT: Duration = Duration::from_secs(60);
enum Command {
Interest(Uuid, bool),
CheckIfDue,
Refresh(Option<u64>, oneshot::Sender<bool>),
}
pub(crate) struct PatchChecks {
tx: mpsc::UnboundedSender<Command>,
rx: Mutex<Option<mpsc::UnboundedReceiver<Command>>>,
}
pub(crate) struct Consumer {
checks: Arc<PatchChecks>,
id: Uuid,
}
impl Drop for Consumer {
fn drop(&mut self) {
self.checks.set_interest(self.id, false);
}
}
impl PatchChecks {
pub(crate) fn new() -> Arc<Self> {
let (tx, rx) = mpsc::unbounded_channel();
Arc::new(Self {
tx,
rx: Mutex::new(Some(rx)),
})
}
pub(crate) fn set_interest(&self, id: Uuid, enabled: bool) {
let _ = self.tx.send(Command::Interest(id, enabled));
}
pub(crate) fn check_if_due(&self) {
let _ = self.tx.send(Command::CheckIfDue);
}
pub(crate) fn consumer(self: &Arc<Self>) -> Consumer {
let id = Uuid::new_v4();
self.set_interest(id, true);
Consumer {
checks: self.clone(),
id,
}
}
pub(crate) async fn refresh(&self, after: Option<u64>) -> bool {
let (tx, rx) = oneshot::channel();
if self.tx.send(Command::Refresh(after, tx)).is_err() {
return false;
}
rx.await.unwrap_or(false)
}
pub(crate) async fn run(&self, stop: CancellationToken) {
let Some(mut commands) = self.rx.lock().unwrap().take() else {
return;
};
let mut consumers = HashSet::new();
let mut waiters = Vec::<oneshot::Sender<bool>>::new();
let mut worker = None;
// Reading status never searches Windows Update. Missing/unreadable data is due immediately.
let status = tokio::task::spawn_blocking({
let stop = stop.clone();
move || helper("--patch-status", None, stop)
})
.await;
let mut next = match status {
Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()),
_ => 0,
};
loop {
tokio::select! {
_ = stop.cancelled() => break,
command = commands.recv() => {
match command {
Some(Command::Interest(id, enabled)) => {
if enabled { consumers.insert(id); } else { consumers.remove(&id); }
}
Some(Command::CheckIfDue) => {
if worker.is_none() && now() >= next { worker = Some(start(None, stop.clone())); }
}
Some(Command::Refresh(after, reply)) => {
waiters.push(reply);
if worker.is_none() { worker = Some(start(after, stop.clone())); }
}
None => break,
}
}
result = async { match &mut worker { Some(task) => task.await, None => std::future::pending().await } } => {
worker = None;
let success = matches!(&result, Ok(Ok(Some(_))));
if !success { log::warn!("Local Windows patch check failed: {result:?}"); }
for reply in waiters.drain(..) { let _ = reply.send(success); }
next = match result {
Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()),
_ => now().saturating_add(INTERVAL.as_secs()),
};
}
_ = tokio::time::sleep(Duration::from_secs(next.saturating_sub(now()).min(30))),
if worker.is_none() && !consumers.is_empty() => {
if now() >= next { worker = Some(start(None, stop.clone())); }
}
}
}
if let Some(task) = worker {
let _ = task.await;
}
for reply in waiters {
let _ = reply.send(false);
}
}
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn start(after: Option<u64>, stop: CancellationToken) -> tokio::task::JoinHandle<anyhow::Result<Option<u64>>> {
tokio::task::spawn_blocking(move || helper("--refresh-patches", after, stop))
}
fn helper(command: &str, after: Option<u64>, stop: CancellationToken) -> anyhow::Result<Option<u64>> {
let budget = CollectionBudget::new(SEARCH_TIMEOUT);
let check = || {
if stop.is_cancelled() {
return Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"Patch check cancelled",
));
}
budget.check()
};
let path = std::env::current_exe()?.with_file_name("gp-posture.exe");
let after = after.map(|after| after.to_string());
let mut args = vec![command];
if let Some(after) = &after {
args.push(after);
}
let output = CollectorCommands::new(&check)
.run_executable(&path, &args)?
.ok_or_else(|| anyhow::anyhow!("Windows posture helper is unavailable"))?;
anyhow::ensure!(output.status.success(), "Windows posture helper failed");
Ok(serde_json::from_slice(&output.stdout)?)
}
@@ -1,92 +0,0 @@
//! A credential lease binds the existing desktop session to its Windows token.
use crate::session_registry::SessionRegistry;
use anyhow::{Context, ensure};
use gpapi::{
service::transport::WINDOWS_ADMISSION_REQUEST,
windows::{PipeClientIdentity, create_service_admission_pipe},
};
use std::{sync::Arc, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::windows::named_pipe::NamedPipeServer,
task::JoinSet,
};
use tokio_util::sync::CancellationToken;
pub(super) struct Admission {
listener: NamedPipeServer,
registry: Arc<SessionRegistry>,
}
struct Lease {
registry: Arc<SessionRegistry>,
session: uuid::Uuid,
}
impl Drop for Lease {
fn drop(&mut self) {
self.registry.revoke(self.session);
}
}
impl Admission {
pub fn new(registry: Arc<SessionRegistry>) -> anyhow::Result<Self> {
Ok(Self {
listener: create_service_admission_pipe(true)?,
registry,
})
}
pub async fn run(mut self, cancel: CancellationToken) -> anyhow::Result<()> {
let mut clients = JoinSet::new();
let result = loop {
tokio::select! {
_ = cancel.cancelled() => break Ok(()),
result = self.listener.connect() => {
if let Err(error) = result { break Err(error.into()); }
let next = match create_service_admission_pipe(false) { Ok(next) => next, Err(error) => break Err(error.into()) };
let pipe = std::mem::replace(&mut self.listener, next);
let registry = self.registry.clone();
let cancel = cancel.clone();
clients.spawn(async move {
if let Err(error) = serve(pipe, registry, cancel).await { log::warn!("Desktop credential lease ended: {error:#}"); }
});
}
_ = clients.join_next(), if !clients.is_empty() => {},
}
};
// Drop each lease before the shared registry and service runtime disappear.
clients.abort_all();
while clients.join_next().await.is_some() {}
result
}
}
async fn serve(
mut pipe: NamedPipeServer,
registry: Arc<SessionRegistry>,
cancel: CancellationToken,
) -> anyhow::Result<()> {
let mut request = [0; WINDOWS_ADMISSION_REQUEST.len()];
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
result = tokio::time::timeout(Duration::from_secs(10), pipe.read_exact(&mut request)) => { result.context("Desktop admission timed out")??; }
}
ensure!(
request == WINDOWS_ADMISSION_REQUEST,
"Invalid desktop admission request"
);
// This synchronous call impersonates, duplicates and reverts before any await.
let identity = Arc::new(PipeClientIdentity::from_pipe(&pipe)?);
let credential = registry.issue_windows(env!("CARGO_PKG_VERSION"), identity)?;
let _lease = Lease {
registry,
session: credential.session_id(),
};
let frame = credential.encode_frame()?;
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
result = tokio::time::timeout(Duration::from_secs(10), pipe.write_all(&frame)) => { result.context("Desktop credential delivery timed out")??; }
}
let mut byte = [0];
tokio::select! {
_ = cancel.cancelled() => {},
result = pipe.read(&mut byte) => { ensure!(result? == 0, "Unexpected desktop lease message"); }
}
Ok(())
}
@@ -1,72 +0,0 @@
use std::{fs::OpenOptions, io, path::Path};
use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount};
const ROTATE_BYTES: usize = 5 * 1024 * 1024;
const ARCHIVE_COUNT: usize = 3;
pub(super) fn writer(path: &Path) -> io::Result<FileRotate<AppendCount>> {
// Keep startup failure explicit: FileRotate's constructor suppresses open errors.
OpenOptions::new().create(true).read(true).append(true).open(path)?;
Ok(FileRotate::new(
path,
AppendCount::new(ARCHIVE_COUNT),
ContentLimit::BytesSurpassed(ROTATE_BYTES),
Compression::None,
None,
))
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs, io::Write};
#[test]
fn keeps_the_latest_three_archives_and_complete_current_entry() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("gpservice.log");
fs::write(dir.path().join("unrelated.log"), "keep").unwrap();
let mut log = writer(&path).unwrap();
for marker in b'0'..=b'5' {
log.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
}
log.flush().unwrap();
drop(log);
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
let archive = dir.path().join(format!("gpservice.log.{suffix}"));
assert_eq!(fs::read(archive).unwrap(), vec![marker; ROTATE_BYTES + 1]);
}
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 5);
assert_eq!(fs::read_to_string(dir.path().join("unrelated.log")).unwrap(), "keep");
}
#[test]
fn restart_appends_and_accounts_for_existing_file_size() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("gpservice.log");
fs::write(&path, "before restart\n").unwrap();
{
let mut log = writer(&path).unwrap();
log.write_all(b"after restart\n").unwrap();
}
assert_eq!(fs::read_to_string(&path).unwrap(), "before restart\nafter restart\n");
let entry = vec![b'x'; ROTATE_BYTES + 1];
fs::write(&path, &entry).unwrap();
{
let mut log = writer(&path).unwrap();
log.write_all(b"new entry\n").unwrap();
}
assert_eq!(fs::read(&path).unwrap(), b"new entry\n");
assert_eq!(fs::read(dir.path().join("gpservice.log.1")).unwrap(), entry);
}
#[test]
fn invalid_log_path_remains_a_startup_error() {
let dir = tempfile::tempdir().unwrap();
assert!(writer(dir.path()).is_err());
}
}
-159
View File
@@ -1,159 +0,0 @@
//! Service Control Manager hosting; the GUI remains in the user's desktop session.
mod admission;
mod logging;
use crate::{
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
};
use anyhow::{Context, ensure};
use gpapi::{
service::vpn_state::VpnState,
utils::{lock_file::LockFile, redact::Redaction},
};
use std::{
ffi::OsString,
io::Write,
sync::{Arc, OnceLock, atomic::AtomicBool},
time::Duration,
};
use tokio::sync::{mpsc, watch};
use tokio_util::sync::CancellationToken;
use windows_service::{
define_windows_service,
service::{ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType},
service_control_handler::{self, ServiceControlHandlerResult, ServiceStatusHandle},
service_dispatcher,
};
const NAME: &str = common::paths::SERVICE_NAME;
static LOG_LEVEL: OnceLock<log::Level> = OnceLock::new();
define_windows_service!(ffi_service_main, service_main);
pub(crate) fn dispatch(level: log::Level) -> anyhow::Result<()> {
let _ = LOG_LEVEL.set(level);
service_dispatcher::start(NAME, ffi_service_main).context("Start GP Connect through the Windows service manager")?;
Ok(())
}
fn status(handle: &ServiceStatusHandle, state: ServiceState, failure: bool) -> windows_service::Result<()> {
let running = state == ServiceState::Running;
let pending = matches!(state, ServiceState::StartPending | ServiceState::StopPending);
handle.set_service_status(ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: state,
controls_accepted: if running {
ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN
} else {
ServiceControlAccept::empty()
},
exit_code: if failure {
ServiceExitCode::ServiceSpecific(1)
} else {
ServiceExitCode::Win32(0)
},
checkpoint: u32::from(pending),
wait_hint: if pending {
Duration::from_secs(30)
} else {
Duration::ZERO
},
process_id: None,
})
}
fn service_main(_arguments: Vec<OsString>) {
let stop = CancellationToken::new();
let requested = stop.clone();
let handle = match service_control_handler::register(NAME, move |control| match control {
ServiceControl::Stop | ServiceControl::Shutdown => {
requested.cancel();
ServiceControlHandlerResult::NoError
}
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
_ => ServiceControlHandlerResult::NotImplemented,
}) {
Ok(handle) => handle,
Err(_) => return,
};
let result = (|| -> anyhow::Result<()> {
status(&handle, ServiceState::StartPending, false)?;
ensure!(
gpapi::windows::current_user_sid()? == "S-1-5-18",
"GP Connect must run as LocalSystem"
);
let redaction = initialize_logger()?;
log::info!("gpservice started: {}", crate::VERSION);
crate::vpn_script::recover_network()?;
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
runtime.block_on(run(&handle, stop, redaction))
})();
if let Err(error) = &result {
log::error!("Windows service stopped: {error:#}");
}
let _ = status(&handle, ServiceState::Stopped, result.is_err());
}
fn initialize_logger() -> anyhow::Result<Arc<Redaction>> {
let state = common::paths::service_lock_file();
let directory = state.parent().context("Service state directory is unavailable")?;
// The installer provisions these directories and their machine-wide ACLs.
// Starting the daemon must not create a user-writable fallback location.
ensure!(
directory.is_dir() && common::paths::service_private_dir().is_dir(),
"Install the GP Connect Windows service before starting it"
);
let writer = logging::writer(&directory.join("gpservice.log"))?;
let redaction = Arc::new(Redaction::new());
let filter = redaction.clone();
let logger = env_logger::builder()
.filter_level(log::LevelFilter::Trace)
.target(env_logger::Target::Pipe(Box::new(writer)))
.format(move |buffer, record| {
writeln!(
buffer,
"[{} {:<5} {}] {}",
buffer.timestamp(),
record.level(),
record.module_path().unwrap_or_default(),
filter.redact_str(&record.args().to_string())
)
})
.build();
gpapi::logger::init_with_logger(*LOG_LEVEL.get().unwrap_or(&log::Level::Info), logger);
Ok(redaction)
}
async fn run(handle: &ServiceStatusHandle, stop: CancellationToken, redaction: Arc<Redaction>) -> anyhow::Result<()> {
let lock = Arc::new(LockFile::new(common::paths::service_lock_file(), std::process::id()));
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
let admission = admission::Admission::new(registry.clone())?;
let (state, observed) = watch::channel(VpnState::Disconnected);
let (mut vpn, lifecycle) = VpnTask::new(state, true, registry.clone());
let dispatcher = Arc::new(RequestDispatcher::new(
lifecycle,
Arc::new(AtomicBool::new(false)),
redaction,
false,
true,
));
let websocket = WsServer::new(env!("CARGO_PKG_VERSION"), registry, dispatcher, observed, lock.clone());
let service_cancel = websocket.cancel_token();
let vpn_cancel = vpn.cancel_token();
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(4);
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
let vpn_stop = service_cancel.clone();
let vpn_handle = tokio::spawn(async move { vpn.start(vpn_stop).await });
let websocket_shutdown = shutdown_tx.clone();
let websocket_handle = tokio::spawn(async move { websocket.start(websocket_shutdown, ready_tx).await });
ready_rx.await.context("Desktop protocol listener failed to start")?;
let lease_cancel = service_cancel.clone();
let admission_handle = tokio::spawn(async move {
if let Err(error) = admission.run(lease_cancel).await {
log::error!("Desktop admission stopped: {error:#}");
let _ = shutdown_tx.send(()).await;
}
});
status(handle, ServiceState::Running, false)?;
tokio::select! { _ = stop.cancelled() => {}, _ = shutdown_rx.recv() => {} }
let _ = status(handle, ServiceState::StopPending, false);
vpn_cancel.cancel();
service_cancel.cancel();
let _ = tokio::join!(vpn_handle, websocket_handle, admission_handle);
lock.unlock()?;
log::info!("gpservice stopped");
Ok(())
}
-48
View File
@@ -410,48 +410,6 @@ async fn handle_client_message(
return Ok(());
}
if let WsRequest::SetWindowsPatchInterest { enabled } = &request {
#[cfg(windows)]
ctx.patch_checks.set_interest(control.connection_id(), *enabled);
#[cfg(not(windows))]
let _ = enabled;
control
.send(ConnectionCommand::Reply {
id,
result: ServiceResult::Accepted,
})
.map_err(|_| ())?;
return Ok(());
}
if let WsRequest::RefreshWindowsPatches { after } = &request {
#[cfg(windows)]
{
let checks = ctx.patch_checks.clone();
let control = control.clone();
let after = Some(after.unwrap_or(0));
tokio::spawn(async move {
let success = checks.refresh(after).await;
let result = if success {
ServiceResult::Accepted
} else {
ServiceResult::rejected(ServiceErrorCode::Internal, "Couldn’t check local updates.")
};
let _ = control.send(ConnectionCommand::Reply { id, result });
});
}
#[cfg(not(windows))]
{
let _ = after;
control
.send(ConnectionCommand::Reply {
id,
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Windows patch checks are unavailable"),
})
.map_err(|_| ())?;
}
return Ok(());
}
if let WsRequest::StoreEditedHipReportChunk(report) = request {
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
let result = if report.upload_id.is_some() && upload_id.is_none() {
@@ -493,7 +451,6 @@ async fn handle_client_message(
offset: chunk.offset,
xml,
complete,
windows_updates: None,
})
})
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
@@ -510,7 +467,6 @@ async fn handle_client_message(
offset: 0,
xml,
complete,
windows_updates: None,
},
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
},
@@ -545,10 +501,6 @@ async fn handle_client_message(
}
if let WsRequest::PreviewHipReport(preview) = request {
#[cfg(windows)]
if preview.client_os == gpapi::os_profile::ClientOs::Windows && matches!(preview.source, HipSource::Generated) {
ctx.patch_checks.check_if_due();
}
let edited_report = if let HipSource::Edited { report_id } = &preview.source {
let report_id = match Uuid::parse_str(report_id) {
Ok(id) => id,
-16
View File
@@ -63,8 +63,6 @@ pub(crate) struct WsServerContext {
state: Mutex<ServiceState>,
handshake_slots: Arc<Semaphore>,
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
#[cfg(windows)]
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
}
impl WsServerContext {
@@ -77,8 +75,6 @@ impl WsServerContext {
Self {
product_version,
registry,
#[cfg(windows)]
patch_checks: dispatcher.patch_checks(),
dispatcher,
state: Mutex::new(ServiceState {
revision: 0,
@@ -187,8 +183,6 @@ impl WsServerContext {
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
self.registry.disconnect_if_current(session_id, generation);
#[cfg(windows)]
self.patch_checks.set_interest(connection_id, false);
let mut state = self.state.lock().await;
state.connections.remove(&connection_id);
state.refresh_demand();
@@ -350,7 +344,6 @@ impl WsServer {
}
}
#[cfg(unix)]
pub fn context(&self) -> Arc<WsServerContext> {
Arc::clone(&self.ctx)
}
@@ -370,12 +363,6 @@ impl WsServer {
};
let _ = ready_tx.send(());
#[cfg(windows)]
let patch_task = {
let checks = self.ctx.patch_checks.clone();
let stop = self.cancel_token.clone();
tokio::spawn(async move { checks.run(stop).await })
};
tokio::select! {
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
info!("VPN state watch task completed");
@@ -390,9 +377,6 @@ impl WsServer {
info!("WS server cancelled");
}
}
self.cancel_token.cancel();
#[cfg(windows)]
let _ = patch_task.await;
self.ctx.hip_previews.shutdown().await;
let _ = shutdown_tx.send(()).await;
}
-19
View File
@@ -1,24 +1,5 @@
# Changelog
## Unreleased
### Added
- Added Windows x64 and ARM64 support with a native desktop interface, background service, embedded sign-in, and in-app updates.
- Added a Windows system tray flyout with placement on the tray's monitor.
### Improved
- Updated Native Shell and enabled only the features used by GP Connect to reduce executable size.
- Matched window presentation settings to native system tray and menu bar terminology.
- Refined Windows sign-in, icons, logs, folder actions, and service log retention.
### Fixed
- Fixed Windows menu dismissal, dropdown hover feedback, and XML report scrolling.
- Fixed focus rings briefly appearing on mouse clicks and reappearing when opening Settings with the mouse.
- Removed unused AppIndicator library requirements from Linux and FreeBSD packages.
## 3.4.0
### Added
+1 -17
View File
@@ -20,6 +20,7 @@ browser-launcher = { path = "../browser-launcher", default-features = false, fea
tiny_http = { version = "0.12", optional = true }
tempfile = { workspace = true, optional = true }
uuid = { version = "1", optional = true, features = ["v4"] }
uzers = { workspace = true, optional = true }
# Webview auth dependencies
tauri = { workspace = true, optional = true }
@@ -27,7 +28,6 @@ regex = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true }
html-escape = { version = "0.3", optional = true }
url = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
webkit2gtk = { version = "2", optional = true }
@@ -60,9 +60,6 @@ webview-auth = [
"dep:tokio-util",
"dep:html-escape",
"dep:url",
"dep:serde_json",
"dep:webview2-com",
"dep:windows",
"dep:gtk",
"dep:webkit2gtk",
"dep:block2",
@@ -97,16 +94,3 @@ release-devtools = ["webview-auth", "tauri/devtools"]
[dev-dependencies]
tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
uzers = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_UI_WindowsAndMessaging"] }
# Child webviews let the Windows host own layout beside native controls.
tauri = { workspace = true, optional = true, features = ["unstable"] }
webview2-com = { version = "0.39", optional = true }
windows = { version = "0.62", optional = true, features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_UI_Controls", "Win32_UI_HiDpi", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
dunce = "1"
winreg = "0.55"
common = { path = "../common" }
+65 -4
View File
@@ -3,6 +3,7 @@ use std::{
io::ErrorKind,
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
path::{Path, PathBuf},
time::Duration,
};
use anyhow::{Context, bail};
@@ -13,9 +14,16 @@ use tokio::{
time::timeout,
};
mod protocol;
pub use protocol::validate_auth_callback;
use protocol::*;
const CALLBACK_SCHEME: &str = "globalprotectcallback";
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
const PROTOCOL_VERSION: u8 = 1;
const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
const IO_TIMEOUT: Duration = Duration::from_secs(5);
// Acceptance acknowledges delivery, including an authentication failure.
const STATUS_ACCEPTED: u8 = 0;
const STATUS_INVALID_CALLBACK: u8 = 1;
const STATUS_UNSUPPORTED_VERSION: u8 = 2;
#[cfg(target_os = "macos")]
mod macos;
@@ -224,9 +232,62 @@ fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
Ok(())
}
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
if callback.len() > MAX_CALLBACK_SIZE {
bail!("Authentication callback exceeds the maximum supported size");
}
let Some((scheme, data)) = callback.split_once(':') else {
bail!("Authentication callback URL is invalid");
};
if scheme != CALLBACK_SCHEME || data.is_empty() {
bail!("Authentication callback URL is invalid");
}
Ok(())
}
enum CallbackReadError {
UnsupportedVersion,
Invalid,
Io,
}
async fn read_callback(stream: &mut UnixStream) -> Result<String, CallbackReadError> {
let mut magic = [0_u8; 4];
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
if &magic != PROTOCOL_MAGIC {
return Err(CallbackReadError::Invalid);
}
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
if version != PROTOCOL_VERSION {
return Err(CallbackReadError::UnsupportedVersion);
}
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
if length == 0 || length > MAX_CALLBACK_SIZE {
return Err(CallbackReadError::Invalid);
}
let mut payload = vec![0; length];
stream
.read_exact(&mut payload)
.await
.map_err(|_| CallbackReadError::Io)?;
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
Ok(callback)
}
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u8(status).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use tempfile::tempdir;
use super::*;
-73
View File
@@ -1,73 +0,0 @@
//! Bounded authentication callback wire format, shared by local transports.
use anyhow::bail;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
pub(super) const CALLBACK_SCHEME: &str = "globalprotectcallback";
pub(super) const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
pub(super) const PROTOCOL_VERSION: u8 = 1;
pub(super) const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
pub(super) const IO_TIMEOUT: Duration = Duration::from_secs(5);
// Acceptance acknowledges delivery, including an authentication failure.
pub(super) const STATUS_ACCEPTED: u8 = 0;
pub(super) const STATUS_INVALID_CALLBACK: u8 = 1;
pub(super) const STATUS_UNSUPPORTED_VERSION: u8 = 2;
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
if callback.len() > MAX_CALLBACK_SIZE {
bail!("Authentication callback exceeds the maximum supported size");
}
let Some((scheme, data)) = callback.split_once(':') else {
bail!("Authentication callback URL is invalid");
};
if scheme != CALLBACK_SCHEME || data.is_empty() {
bail!("Authentication callback URL is invalid");
}
Ok(())
}
pub(super) enum CallbackReadError {
UnsupportedVersion,
Invalid,
Io,
}
pub(super) async fn read_callback(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
) -> Result<String, CallbackReadError> {
let mut magic = [0_u8; 4];
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
if &magic != PROTOCOL_MAGIC {
return Err(CallbackReadError::Invalid);
}
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
if version != PROTOCOL_VERSION {
return Err(CallbackReadError::UnsupportedVersion);
}
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
if length == 0 || length > MAX_CALLBACK_SIZE {
return Err(CallbackReadError::Invalid);
}
let mut payload = vec![0; length];
stream
.read_exact(&mut payload)
.await
.map_err(|_| CallbackReadError::Io)?;
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
Ok(callback)
}
pub(super) async fn write_response(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
status: u8,
) -> anyhow::Result<()> {
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u8(status).await?;
Ok(())
}
-170
View File
@@ -1,170 +0,0 @@
//! Per-user Windows named pipe for browser authentication callbacks.
use anyhow::{Context, bail};
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use std::{io, os::windows::io::AsRawHandle};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer},
time::timeout,
};
#[path = "protocol.rs"]
mod protocol;
pub use protocol::validate_auth_callback;
use protocol::*;
use windows_sys::Win32::{
System::Pipes::GetNamedPipeServerProcessId, UI::WindowsAndMessaging::AllowSetForegroundWindow,
};
pub struct AuthCallbackReceiver {
listener: NamedPipeServer,
}
impl AuthCallbackReceiver {
pub fn bind() -> anyhow::Result<Self> {
Ok(Self {
listener: gpapi::windows::create_user_pipe(&pipe_name()?, true)
.context("Another browser authentication is already waiting")?,
})
}
pub async fn receive(mut self) -> anyhow::Result<SamlAuthData> {
loop {
self.listener.connect().await?;
let mut stream = &mut self.listener;
let callback = timeout(IO_TIMEOUT, read_callback(&mut stream)).await;
let result = match callback {
Ok(Ok(callback)) => match SamlAuthData::from_gpcallback(&callback) {
Ok(data) => {
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
Some(Ok(data))
}
Err(error @ AuthDataParseError::AuthenticationFailed(_)) => {
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
Some(Err(error.into()))
}
Err(_) => {
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
None
}
},
Ok(Err(CallbackReadError::UnsupportedVersion)) => {
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
None
}
_ => None,
};
// DisconnectNamedPipe discards unread response bytes. Wait for the client
// to confirm it consumed the response before disconnecting this instance.
let _ = timeout(IO_TIMEOUT, stream.read_u8()).await;
self.listener.disconnect()?;
if let Some(result) = result {
if let Err(error) = delegate_foreground_to_parent() {
log::debug!("Could not delegate authentication foreground permission to the parent: {error}");
}
return result;
}
}
}
}
fn pipe_name() -> anyhow::Result<String> {
Ok(format!(
r"\\.\pipe\GPConnect.Auth.{}",
gpapi::windows::current_user_sid()?
))
}
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
validate_auth_callback(callback)?;
timeout(IO_TIMEOUT, async {
let mut stream = ClientOptions::new()
.open(pipe_name()?)
.context("No external-browser authentication is waiting for a callback")?;
stream.write_all(PROTOCOL_MAGIC).await?;
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u32(callback.len() as u32).await?;
stream.write_all(callback.as_bytes()).await?;
let version = stream.read_u8().await?;
let status = stream.read_u8().await?;
// The receiver waits for our acknowledgement before returning to its caller.
if version == PROTOCOL_VERSION && status == STATUS_ACCEPTED {
if let Err(error) = delegate_foreground_to_receiver(&stream) {
log::debug!("Could not delegate browser foreground permission to the authenticator: {error}");
}
}
stream.write_u8(status).await?;
anyhow::ensure!(
version == PROTOCOL_VERSION,
"Authentication callback protocol version mismatch"
);
match status {
STATUS_ACCEPTED => Ok(()),
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
_ => bail!("Authentication callback protocol is unsupported"),
}
})
.await
.context("Timed out forwarding the authentication callback")?
}
fn delegate_foreground_to_receiver(stream: &NamedPipeClient) -> io::Result<()> {
let mut process_id = 0;
unsafe {
if GetNamedPipeServerProcessId(stream.as_raw_handle(), &mut process_id) == 0 {
return Err(io::Error::last_os_error());
}
}
allow_foreground(process_id)
}
fn delegate_foreground_to_parent() -> anyhow::Result<()> {
let Some(process_id) = std::env::var_os(gpapi::process::auth_launcher::AUTH_PARENT_PROCESS_ID_ENV) else {
return Ok(());
};
let process_id = process_id.to_string_lossy().parse::<u32>()?;
allow_foreground(process_id)?;
Ok(())
}
fn allow_foreground(process_id: u32) -> io::Result<()> {
if unsafe { AllowSetForegroundWindow(process_id) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
use winreg::{RegKey, enums::HKEY_CURRENT_USER};
let executable = common::binary_paths::gpauth();
anyhow::ensure!(executable.is_file(), "The authentication helper is missing");
let root = RegKey::predef(HKEY_CURRENT_USER);
let (scheme, _) = root.create_subkey(r"Software\Classes\globalprotectcallback")?;
scheme.set_value("", &"URL:GlobalProtect authentication callback")?;
scheme.set_value("URL Protocol", &"")?;
let (application, _) = scheme.create_subkey("Application")?;
application.set_value("ApplicationName", &"GP Connect Login")?;
let (command, _) = scheme.create_subkey(r"shell\open\command")?;
// URL association activation requires a shell path, not Rust's verbatim
// canonical path (\\?\C:\...), even though CreateProcess accepts both.
let executable = dunce::simplified(&executable);
command.set_value("", &format!("\"{}\" auth-callback \"%1\"", executable.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn forwards_browser_callback_over_private_windows_pipe() {
let receiver = AuthCallbackReceiver::bind().unwrap();
// The first-instance flag preserves one pending browser authentication per user.
assert!(AuthCallbackReceiver::bind().is_err());
let sender = tokio::spawn(async {
forward_auth_callback("globalprotectcallback:cas-as=1&[email protected]&token=test-token").await
});
let data = timeout(std::time::Duration::from_secs(5), receiver.receive())
.await
.unwrap()
.unwrap();
sender.await.unwrap().unwrap();
assert_eq!(data.username(), "[email protected]");
assert_eq!(data.token(), Some("test-token"));
}
}
-1
View File
@@ -8,7 +8,6 @@ use gpapi::{
mod browser;
#[cfg(feature = "browser-auth")]
#[cfg_attr(windows, path = "callback/windows.rs")]
mod callback;
#[cfg(feature = "browser-auth")]
+1 -6
View File
@@ -12,17 +12,12 @@ mod platform_impl;
#[path = "webview/macos.rs"]
mod platform_impl;
#[cfg(windows)]
#[path = "webview/windows.rs"]
mod platform_impl;
#[cfg(not(any(
windows,
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
compile_error!("webview-auth is only supported on Windows, macOS and GTK/WebKitGTK Unix targets");
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
+2 -2
View File
@@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken;
#[derive(Debug)]
pub(crate) enum AuthDataLocation {
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
Headers,
Body,
}
@@ -155,7 +155,7 @@ impl AuthMessenger {
}
}
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
use log::warn;
+1 -2
View File
@@ -22,7 +22,7 @@ impl RecoveryStatus {
Self::Hidden => "",
Self::Restarting => "Restarting sign-in…",
Self::Loading => "Loading sign-in…",
Self::Failed => "Couldn’t load sign-in.",
Self::Failed => "Couldn’t restart sign-in.",
Self::Rejected => "Sign-in wasn’t completed.",
Self::Tls {
reason: TlsFailureReason::Handshake,
@@ -55,7 +55,6 @@ impl RecoveryStatus {
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
}
#[cfg(not(windows))]
pub fn is_busy(self) -> bool {
matches!(self, Self::Restarting | Self::Loading)
}
-4
View File
@@ -2,9 +2,7 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum TlsFailureReason {
Expired,
#[cfg(not(windows))]
NotYetValid,
#[cfg(not(windows))]
Untrusted,
HostnameMismatch,
InvalidCertificate,
@@ -19,9 +17,7 @@ impl TlsFailureReason {
pub fn message(self) -> &'static str {
match self {
Self::Expired => "The certificate has expired.",
#[cfg(not(windows))]
Self::NotYetValid => "The certificate is not valid yet.",
#[cfg(not(windows))]
Self::Untrusted => "The certificate was issued by an untrusted authority.",
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
Self::InvalidCertificate => "The server’s certificate could not be verified.",
+24 -44
View File
@@ -1,8 +1,6 @@
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
use anyhow::bail;
#[cfg(not(windows))]
use gpapi::utils::window::get_title_bar_height;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
use gpapi::{
@@ -10,51 +8,24 @@ use gpapi::{
error::ServerTlsError,
gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::redact::redact_uri,
utils::{redact::redact_uri, window::get_title_bar_height},
};
use log::{info, warn};
#[cfg(target_os = "macos")]
use tauri::Manager;
#[cfg(not(windows))]
use tauri::WebviewUrl;
use tauri::{AppHandle, WindowEvent};
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
use tokio::{sync::oneshot, time};
use crate::auth_prelogin;
#[cfg(not(windows))]
use super::address_bar::TOOLBAR_HEIGHT;
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
#[cfg(not(windows))]
type AuthWindow = tauri::WebviewWindow;
#[cfg(windows)]
use super::platform_impl::{AuthWindow, create_auth_window};
#[cfg(not(windows))]
fn create_auth_window(app: &AppHandle, title: &str, theme: Option<tauri::Theme>) -> anyhow::Result<AuthWindow> {
let builder = AuthWindow::builder(app, "auth_window", WebviewUrl::default())
.title(title)
.theme(theme)
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let builder = builder.on_navigation(super::platform_impl::open_okta_verify);
Ok(
builder
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
.min_inner_size(400.0, 300.0)
.focused(true)
.visible(false)
.center()
.build()?,
)
}
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
pub(super) trait PlatformWebviewExt {
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
pub trait PlatformWebviewExt {
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
@@ -83,7 +54,7 @@ pub(super) trait PlatformWebviewExt {
}
}
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub trait GetHeader {
fn get_header(&self, key: &str) -> Option<String>;
}
@@ -154,7 +125,19 @@ impl<'a> WebviewAuthenticator<'a> {
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_messenger = Arc::new(AuthMessenger::new());
let auth_window = create_auth_window(app_handle, self.window_title, native_theme(self.window_theme))?;
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
.title(self.window_title)
.theme(native_theme(self.window_theme))
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let auth_window_builder = auth_window_builder.on_navigation(super::platform_impl::open_okta_verify);
let auth_window = auth_window_builder
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
.min_inner_size(400.0, 300.0)
.focused(true)
.visible(false)
.center()
.build()?;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
@@ -187,7 +170,7 @@ impl<'a> WebviewAuthenticator<'a> {
async fn wait_for_auth(
&self,
auth_window: &AuthWindow,
auth_window: &WebviewWindow,
auth_messenger: Arc<AuthMessenger>,
) -> anyhow::Result<SamlAuthData> {
let mut recovery = Recovery::default();
@@ -327,16 +310,13 @@ impl<'a> WebviewAuthenticator<'a> {
async fn setup_auth_window(
&self,
auth_window: &AuthWindow,
auth_window: &WebviewWindow,
auth_messenger: Arc<AuthMessenger>,
) -> anyhow::Result<()> {
info!("Setting up auth window...");
if self.clean {
info!("Clearing all browsing data...");
#[cfg(windows)]
super::platform_impl::clear_browsing_data(auth_window).await?;
#[cfg(not(windows))]
auth_window.clear_all_browsing_data()?;
}
@@ -381,7 +361,7 @@ impl<'a> WebviewAuthenticator<'a> {
Ok(())
}
fn handle_not_found(&self, auth_window: &AuthWindow, auth_messenger: &Arc<AuthMessenger>) {
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
@@ -390,7 +370,7 @@ impl<'a> WebviewAuthenticator<'a> {
auth_messenger.schedule_raise_window(2);
}
fn update_recovery(&self, auth_window: &AuthWindow, status: RecoveryStatus) -> anyhow::Result<()> {
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> {
if status != RecoveryStatus::Hidden {
self.raise_window(auth_window);
}
@@ -417,7 +397,7 @@ impl<'a> WebviewAuthenticator<'a> {
fn load_restarted_sign_in(
&self,
auth_window: &AuthWindow,
auth_window: &WebviewWindow,
messenger: &Arc<AuthMessenger>,
auth_request: String,
) -> anyhow::Result<()> {
@@ -435,7 +415,7 @@ impl<'a> WebviewAuthenticator<'a> {
Ok(())
}
fn raise_window(&self, auth_window: &AuthWindow) {
fn raise_window(&self, auth_window: &WebviewWindow) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
-380
View File
@@ -1,380 +0,0 @@
//! WebView2 authentication. All COM objects and native controls stay on the UI thread.
use std::{
cell::{Cell, RefCell},
collections::HashMap,
rc::Rc,
sync::Arc,
};
use super::{
auth_messenger::{AuthDataLocation, AuthError, AuthEvent, AuthMessenger},
recovery::RecoveryStatus,
webview_auth::{GetHeader, PlatformWebviewExt},
};
use anyhow::{Context, bail};
use gpapi::auth::SamlAuthData;
use tauri::{
AppHandle, LogicalPosition, Webview, WebviewBuilder, WebviewUrl, Window, WindowBuilder, webview::PlatformWebview,
};
use webview2_com::{
ClearBrowsingDataCompletedHandler, CoTaskMemPWSTR, DOMContentLoadedEventHandler, ExecuteScriptCompletedHandler,
Microsoft::Web::WebView2::Win32::*, NavigationCompletedEventHandler, NavigationStartingEventHandler,
SourceChangedEventHandler, WebResourceResponseReceivedEventHandler,
};
use windows::core::{BOOL, HSTRING, Interface, PWSTR};
#[path = "windows/controls.rs"]
mod controls;
#[path = "windows/tls.rs"]
mod tls;
/// Windows hosts native chrome and a manually sized child webview in one window.
/// Host-owned child bounds keep the page surface below the native controls
/// throughout live resizing.
#[derive(Clone)]
pub(super) struct AuthWindow {
window: Window,
webview: Webview,
}
impl std::ops::Deref for AuthWindow {
type Target = Window;
fn deref(&self) -> &Window {
&self.window
}
}
impl AuthWindow {
pub(super) fn with_webview(&self, callback: impl FnOnce(PlatformWebview) + Send + 'static) -> tauri::Result<()> {
self.webview.with_webview(callback)
}
}
impl gpapi::utils::window::WindowExt for AuthWindow {
fn raise(&self) -> anyhow::Result<()> {
self.window.show()?;
self.window.set_focus()?;
self.webview.set_focus()?;
Ok(())
}
}
pub(super) fn create_auth_window(
app: &AppHandle,
title: &str,
theme: Option<tauri::Theme>,
) -> anyhow::Result<AuthWindow> {
let window = WindowBuilder::new(app, "auth_window")
.title(title)
.theme(theme)
.inner_size(900.0, 650.0 + super::address_bar::TOOLBAR_HEIGHT)
.min_inner_size(400.0, 300.0)
.focused(true)
.visible(false)
.center()
.build()?;
let webview = window.add_child(
WebviewBuilder::new("auth_webview", WebviewUrl::default())
.devtools(cfg!(any(debug_assertions, feature = "release-devtools"))),
LogicalPosition::new(0.0, 0.0),
window.inner_size()?,
)?;
Ok(AuthWindow { window, webview })
}
thread_local! {
static STATES: RefCell<HashMap<usize, Rc<State>>> = RefCell::default();
}
struct State {
core: ICoreWebView2,
controller: ICoreWebView2Controller,
messenger: Arc<AuthMessenger>,
controls: controls::Controls,
pending: Cell<Option<u64>>,
navigations: RefCell<HashMap<u64, u64>>,
document: RefCell<(String, u64)>,
tls: RefCell<tls::Policy>,
}
fn text(get: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
let mut value = PWSTR::null();
let result = get(&mut value);
let value = CoTaskMemPWSTR::from(value);
result?;
Ok(value.to_string())
}
fn state(webview: &PlatformWebview) -> anyhow::Result<Rc<State>> {
let core = unsafe { webview.controller().CoreWebView2()? };
STATES
.with_borrow(|states| states.get(&(core.as_raw() as usize)).cloned())
.context("Authentication controls are unavailable")
}
impl State {
fn read_html(&self, generation: u64) -> windows::core::Result<()> {
if generation != self.messenger.generation() {
return Ok(());
}
let messenger = Arc::clone(&self.messenger);
unsafe {
self.core.ExecuteScript(
&HSTRING::from("document.documentElement.outerHTML"),
&ExecuteScriptCompletedHandler::create(Box::new(move |result, json| {
result?;
if let Ok(html) = serde_json::from_str::<String>(&json) {
messenger.read_from_html(&html, generation);
}
Ok(())
})),
)
}
}
fn listen(self: &Rc<Self>) -> windows::core::Result<()> {
let mut token = 0;
let weak = Rc::downgrade(self);
let starting = NavigationStartingEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let mut id = 0;
args.NavigationId(&mut id)?;
let generation = *state
.navigations
.borrow_mut()
.entry(id)
.or_insert_with(|| state.pending.take().unwrap_or_else(|| state.messenger.generation()));
let uri = text(|p| args.Uri(p))?;
if uri.starts_with("globalprotectcallback:") {
args.SetCancel(true)?;
match SamlAuthData::from_gpcallback(&uri) {
Ok(data) => state
.messenger
.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
Err(error) => state
.messenger
.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(error.into()))),
}
} else if generation == state.messenger.generation() {
*state.document.borrow_mut() = (uri, generation);
state.messenger.cancel_raise_window();
}
}
Ok(())
}));
unsafe {
self.core.add_NavigationStarting(&starting, &mut token)?;
}
let weak = Rc::downgrade(self);
let loaded = DOMContentLoadedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
let mut id = 0;
unsafe {
args.NavigationId(&mut id)?;
}
let generation = state.navigations.borrow().get(&id).copied();
if let Some(generation) = generation {
state.read_html(generation)?;
}
Ok(())
}));
unsafe {
self
.core
.cast::<ICoreWebView2_2>()?
.add_DOMContentLoaded(&loaded, &mut token)?;
}
let weak = Rc::downgrade(self);
let completed = NavigationCompletedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let mut id = 0;
args.NavigationId(&mut id)?;
let Some(generation) = state.navigations.borrow_mut().remove(&id) else {
return Ok(());
};
let mut success = BOOL(0);
args.IsSuccess(&mut success)?;
if success.as_bool() {
state.read_html(generation)?;
state.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
} else {
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
args.WebErrorStatus(&mut error)?;
if error != COREWEBVIEW2_WEB_ERROR_STATUS_OPERATION_CANCELED {
state.messenger.send_auth_event(AuthEvent::Error(
generation,
AuthError::LoadFailed(anyhow::anyhow!("WebView2 navigation failed ({})", error.0)),
));
}
}
}
Ok(())
}));
unsafe {
self.core.add_NavigationCompleted(&completed, &mut token)?;
}
let weak = Rc::downgrade(self);
let source = SourceChangedEventHandler::create(Box::new(move |_, _| {
if let Some(state) = weak.upgrade() {
let uri = unsafe { text(|p| state.core.Source(p))? };
state.controls.set_address(&uri)?;
}
Ok(())
}));
unsafe {
self.core.add_SourceChanged(&source, &mut token)?;
}
let weak = Rc::downgrade(self);
let response = WebResourceResponseReceivedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let uri = text(|p| args.Request()?.Uri(p))?;
let (document, generation) = state.document.borrow().clone();
// Subresources must not supply authentication credentials for the page.
if uri == document && generation == state.messenger.generation() {
state
.messenger
.read_from_response(&Headers(args.Response()?.Headers()?), generation);
}
}
Ok(())
}));
unsafe {
self
.core
.cast::<ICoreWebView2_2>()?
.add_WebResourceResponseReceived(&response, &mut token)?;
}
tls::install(self)?;
Ok(())
}
}
struct Headers(ICoreWebView2HttpResponseHeaders);
impl GetHeader for Headers {
fn get_header(&self, key: &str) -> Option<String> {
unsafe { text(|p| self.0.GetHeader(&HSTRING::from(key), p)).ok() }
}
}
impl PlatformWebviewExt for PlatformWebview {
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
let controller = self.controller();
let core = unsafe { controller.CoreWebView2()? };
let key = core.as_raw() as usize;
let controls = controls::Controls::new(window, &controller, key)?;
let state = Rc::new(State {
core,
controller,
messenger,
controls,
pending: Cell::new(None),
navigations: RefCell::default(),
document: RefCell::new((String::new(), 0)),
tls: RefCell::default(),
});
STATES.with_borrow_mut(|states| states.insert(key, Rc::clone(&state)));
state.listen()?;
state.controls.layout(&state)?;
Ok(())
}
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
let state = state(self)?;
state.controls.update(&state, status)?;
Ok(())
}
fn stop_loading(&self) {
let _ = unsafe { self.controller().CoreWebView2().and_then(|wv| wv.Stop()) };
}
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
tls::confirm(state(self)?.as_ref())
}
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
state(self)?.tls.borrow_mut().ignore_errors = true;
Ok(())
}
fn user_agent(&self) -> anyhow::Result<String> {
unsafe {
Ok(text(|p| {
self
.controller()
.CoreWebView2()?
.Settings()?
.cast::<ICoreWebView2Settings2>()?
.UserAgent(p)
})?)
}
}
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
unsafe {
self
.controller()
.CoreWebView2()?
.Settings()?
.cast::<ICoreWebView2Settings2>()?
.SetUserAgent(&HSTRING::from(user_agent))?;
}
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
let state = state(self)?;
state.pending.set(Some(state.messenger.generation()));
unsafe {
state.core.Navigate(&HSTRING::from(url))?;
}
Ok(())
}
fn load_html(&self, html: &str) -> anyhow::Result<()> {
let state = state(self)?;
state.pending.set(Some(state.messenger.generation()));
unsafe {
state.core.NavigateToString(&HSTRING::from(html))?;
}
Ok(())
}
}
/// WebView2 clears profiles asynchronously; do not navigate until cookies are gone.
pub(super) async fn clear_browsing_data(window: &AuthWindow) -> anyhow::Result<()> {
let (tx, rx) = tokio::sync::oneshot::channel();
window.with_webview(move |wv| {
let tx = Rc::new(RefCell::new(Some(tx)));
let complete = Rc::clone(&tx);
let callback = ClearBrowsingDataCompletedHandler::create(Box::new(move |result| {
if let Some(tx) = complete.borrow_mut().take() {
let _ = tx.send(result);
}
Ok(())
}));
let result = (|| unsafe {
wv.controller()
.CoreWebView2()?
.cast::<ICoreWebView2_13>()?
.Profile()?
.cast::<ICoreWebView2Profile2>()?
.ClearBrowsingDataAll(&callback)
})();
if let Err(error) = result {
if let Some(tx) = tx.borrow_mut().take() {
let _ = tx.send(Err(error));
}
}
})?;
rx.await.context("Could not clear sign-in data")??;
Ok(())
}
-391
View File
@@ -1,391 +0,0 @@
//! Native controls remain outside the identity provider's document.
use super::*;
use windows::{
Win32::{
Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM},
Graphics::Gdi::*,
UI::{
Controls::EM_SETRECT,
HiDpi::{GetDpiForWindow, SystemParametersInfoForDpi},
Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
WindowsAndMessaging::*,
},
},
core::{PCWSTR, w},
};
const SUBCLASS: usize = 0x47504155;
const ADDRESS_SUBCLASS: usize = 0x47504156;
const ADDRESS_HEIGHT: i32 = 24;
const TOOLBAR_HEIGHT: i32 = 34;
const RECOVERY_PADDING: i32 = 4;
const RETRY: usize = 101;
const PROCEED: usize = 102;
const CANCEL: usize = 103;
pub(super) struct Controls {
pub(super) parent: HWND,
webview_host: HWND,
address: HWND,
message: HWND,
retry: HWND,
proceed: HWND,
cancel: HWND,
status: Cell<RecoveryStatus>,
recovery_bounds: Cell<RECT>,
font: Cell<Option<(u32, HFONT)>>,
}
impl Controls {
pub(super) fn new(window: &AuthWindow, controller: &ICoreWebView2Controller, key: usize) -> anyhow::Result<Self> {
// The host owns both the toolbar and the child webview's remaining area.
let parent = HWND(window.hwnd()?.0);
let mut webview_host = HWND::default();
unsafe {
controller.ParentWindow(&mut webview_host)?;
}
let child = |class: PCWSTR, title: &str, style: WINDOW_STYLE, id: usize| -> windows::core::Result<HWND> {
unsafe {
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE::default(),
class,
&HSTRING::from(title),
WS_CHILD | style,
0,
0,
0,
0,
Some(parent),
Some(HMENU(id as *mut _)),
None,
None,
)?;
Ok(hwnd)
}
};
let controls = Self {
parent,
webview_host,
address: child(
w!("EDIT"),
super::super::address_bar::LOADING_ADDRESS,
WS_VISIBLE | WS_BORDER | WINDOW_STYLE(ES_READONLY as u32 | ES_MULTILINE as u32 | ES_AUTOHSCROLL as u32),
0,
)?,
message: child(w!("STATIC"), "", WINDOW_STYLE::default(), 0)?,
retry: child(w!("BUTTON"), "Try Again", WS_TABSTOP, RETRY)?,
proceed: child(w!("BUTTON"), "Continue Anyway…", WS_TABSTOP, PROCEED)?,
cancel: child(w!("BUTTON"), "Cancel", WS_TABSTOP, CANCEL)?,
status: Cell::new(RecoveryStatus::Hidden),
recovery_bounds: Cell::new(RECT::default()),
font: Cell::new(None),
};
unsafe {
anyhow::ensure!(
SetWindowSubclass(controls.address, Some(address_proc), ADDRESS_SUBCLASS, 0).as_bool(),
"Could not style the sign-in address"
);
anyhow::ensure!(
SetWindowSubclass(parent, Some(window_proc), SUBCLASS, key).as_bool(),
"Could not install sign-in controls"
);
}
Ok(controls)
}
pub(super) fn set_address(&self, uri: &str) -> windows::core::Result<()> {
unsafe {
SetWindowTextW(
self.address,
&HSTRING::from(super::super::address_bar::display_address(Some(uri))),
)
}
}
pub(super) fn update(&self, state: &State, status: RecoveryStatus) -> windows::core::Result<()> {
self.status.set(status);
let message = if status.detail().is_empty() {
status.message().to_owned()
} else {
format!("{}\r\n{}", status.message(), status.detail())
};
unsafe {
SetWindowTextW(self.message, &HSTRING::from(message))?;
for (hwnd, visible) in [
(self.message, status != RecoveryStatus::Hidden),
(self.retry, status.can_retry()),
(self.proceed, status.can_continue()),
(self.cancel, status.blocks_page()),
] {
let _ = ShowWindow(hwnd, if visible { SW_SHOW } else { SW_HIDE });
}
state.controller.SetIsVisible(!status.blocks_page())?;
}
self.layout(state)
}
pub(super) fn layout(&self, state: &State) -> windows::core::Result<()> {
unsafe {
let dpi = GetDpiForWindow(self.parent);
let scale = dpi as f64 / 96.0;
let px = |value: i32| (value as f64 * scale).round() as i32;
let mut bounds = RECT::default();
GetClientRect(self.parent, &mut bounds)?;
let width = bounds.right;
if self.font.get().is_none_or(|(current_dpi, _)| current_dpi != dpi) {
let mut metrics = NONCLIENTMETRICSW {
cbSize: std::mem::size_of::<NONCLIENTMETRICSW>() as u32,
..Default::default()
};
SystemParametersInfoForDpi(
SPI_GETNONCLIENTMETRICS.0,
metrics.cbSize,
Some(&mut metrics as *mut _ as *mut _),
0,
dpi,
)?;
metrics.lfMessageFont.lfHeight = -px(13);
let font = CreateFontIndirectW(&metrics.lfMessageFont);
if font.is_invalid() {
return Err(windows::core::Error::from_thread());
}
for control in [self.address, self.message, self.retry, self.proceed, self.cancel] {
SendMessageW(control, WM_SETFONT, Some(WPARAM(font.0 as usize)), Some(LPARAM(1)));
}
if let Some((_, old)) = self.font.replace(Some((dpi, font))) {
let _ = DeleteObject(old.into());
}
}
MoveWindow(
self.address,
px(8),
px(5),
(width - px(16)).max(0),
px(ADDRESS_HEIGHT),
true,
)?;
// A one-line formatting rectangle centers the native read-only edit text.
// ES_AUTOHSCROLL keeps long URLs on one line and lets users select/copy them.
let mut client = RECT::default();
GetClientRect(self.address, &mut client)?;
let dc = GetDC(Some(self.address));
let previous = SelectObject(dc, self.font.get().expect("font initialized").1.into());
let mut text_metrics = TEXTMETRICW::default();
let measured = GetTextMetricsW(dc, &mut text_metrics);
SelectObject(dc, previous);
ReleaseDC(Some(self.address), dc);
measured.ok()?;
let top = ((client.bottom - text_metrics.tmHeight) / 2).max(0);
let text = RECT {
left: px(6),
top,
right: client.right - px(6),
bottom: top + text_metrics.tmHeight,
};
SendMessageW(
self.address,
EM_SETRECT,
Some(WPARAM(0)),
Some(LPARAM(&text as *const _ as isize)),
);
let status = self.status.get();
let buttons = [
(self.cancel, status.blocks_page(), 70),
(self.proceed, status.can_continue(), 136),
(self.retry, status.can_retry(), 84),
];
let button_width: i32 = buttons
.iter()
.filter(|(_, visible, _)| *visible)
.map(|(_, _, size)| size + 6)
.sum();
let stacked = width < px(700) && button_width > 0;
let message_height = if status.detail().is_empty() { 20 } else { 40 };
let row_height = message_height.max(28);
let recovery_content_height = if stacked { message_height + 8 + 28 } else { row_height };
// Equal padding surrounds the controls; the divider occupies one physical pixel.
let recovery_height = px(recovery_content_height + 2 * RECOVERY_PADDING) + 1;
let header_height = if status == RecoveryStatus::Hidden {
px(TOOLBAR_HEIGHT)
} else {
px(TOOLBAR_HEIGHT) + recovery_height
};
self.recovery_bounds.set(RECT {
left: 0,
top: px(TOOLBAR_HEIGHT),
right: width,
bottom: header_height,
});
let message_width = if stacked {
width - px(24)
} else {
width - px(24 + button_width)
};
MoveWindow(
self.message,
px(12),
px(TOOLBAR_HEIGHT + RECOVERY_PADDING + if stacked { 0 } else { (row_height - message_height) / 2 }),
message_width.max(0),
px(message_height),
true,
)?;
let button_top = TOOLBAR_HEIGHT
+ RECOVERY_PADDING
+ if stacked {
message_height + 8
} else {
(row_height - 28) / 2
};
let mut right = width - px(8);
for (hwnd, visible, size) in buttons {
if visible {
right -= px(size);
MoveWindow(hwnd, right, px(button_top), px(size), px(28), true)?;
right -= px(6);
}
}
let content_height = (bounds.bottom - header_height).max(0);
MoveWindow(self.webview_host, 0, header_height, width, content_height, true)?;
state.controller.SetBounds(RECT {
left: 0,
top: 0,
right: width,
bottom: content_height,
})?;
let _ = InvalidateRect(Some(self.parent), None, true);
}
Ok(())
}
}
impl Drop for Controls {
fn drop(&mut self) {
if let Some((_, font)) = self.font.get() {
unsafe {
let _ = DeleteObject(font.into());
}
}
}
}
/// Keep the native edit's selection and accessibility, with a quiet, flat frame.
unsafe extern "system" fn address_proc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
_: usize,
) -> LRESULT {
if msg == WM_NCDESTROY {
unsafe {
let _ = RemoveWindowSubclass(hwnd, Some(address_proc), id);
}
}
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
// EDIT also repaints its frame during WM_PAINT, so style it after native drawing.
if matches!(msg, WM_NCPAINT | WM_PAINT) {
unsafe {
let dc = GetWindowDC(Some(hwnd));
let mut bounds = RECT::default();
if !dc.is_invalid() && GetWindowRect(hwnd, &mut bounds).is_ok() {
let background = GetSysColor(COLOR_3DFACE);
let foreground = GetSysColor(COLOR_WINDOWTEXT);
let mut border = 0;
for shift in [0, 8, 16] {
let channel = (((background >> shift) & 255) * 82 + ((foreground >> shift) & 255) * 18) / 100;
border |= channel << shift;
}
let brush = CreateSolidBrush(COLORREF(border));
FrameRect(
dc,
&RECT {
left: 0,
top: 0,
right: bounds.right - bounds.left,
bottom: bounds.bottom - bounds.top,
},
brush,
);
let _ = DeleteObject(brush.into());
}
ReleaseDC(Some(hwnd), dc);
}
}
result
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
key: usize,
) -> LRESULT {
let state = STATES.with_borrow(|states| states.get(&key).cloned());
if msg == WM_CTLCOLORSTATIC {
unsafe {
let dc = HDC(wparam.0 as *mut _);
let is_message = state
.as_ref()
.is_some_and(|state| state.controls.message.0 as isize == lparam.0);
let background = if is_message { COLOR_3DFACE } else { COLOR_WINDOW };
SetTextColor(dc, COLORREF(GetSysColor(COLOR_WINDOWTEXT)));
SetBkColor(dc, COLORREF(GetSysColor(background)));
return LRESULT(GetSysColorBrush(background).0 as isize);
}
}
// Paint the native toolbar and recovery surface outside the child webview.
if msg == WM_ERASEBKGND {
unsafe {
let mut bounds = RECT::default();
if GetClientRect(hwnd, &mut bounds).is_ok() {
let dc = HDC(wparam.0 as *mut _);
FillRect(dc, &bounds, GetSysColorBrush(COLOR_WINDOW));
if let Some(state) = &state {
let row = state.controls.recovery_bounds.get();
if row.bottom > row.top {
FillRect(dc, &row, GetSysColorBrush(COLOR_3DFACE));
let divider = RECT {
top: row.bottom - 1,
..row
};
FillRect(dc, &divider, GetSysColorBrush(COLOR_3DLIGHT));
}
}
}
}
return LRESULT(1);
}
if let Some(state) = &state {
if msg == WM_COMMAND && (wparam.0 >> 16) == BN_CLICKED as usize {
let event = match wparam.0 & 0xffff {
RETRY => Some(AuthEvent::Retry),
PROCEED => Some(AuthEvent::RequestTlsException),
CANCEL => Some(AuthEvent::Close),
_ => None,
};
if let Some(event) = event {
state.messenger.send_auth_event(event);
return LRESULT(0);
}
}
}
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
if msg == WM_SIZE || msg == WM_DPICHANGED {
if let Some(state) = &state {
let _ = state.controls.layout(state);
}
}
if msg == WM_NCDESTROY {
unsafe {
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
}
STATES.with_borrow_mut(|states| states.remove(&key));
if let Some(state) = state {
super::tls::clear_exceptions(&state.core);
}
}
result
}
-128
View File
@@ -1,128 +0,0 @@
use super::super::tls::{TlsFailure, TlsFailureReason};
use super::*;
use std::collections::HashSet;
use webview2_com::{ClearServerCertificateErrorActionsCompletedHandler, ServerCertificateErrorDetectedEventHandler};
use windows::Win32::UI::WindowsAndMessaging::{IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_YESNO, MessageBoxW};
#[derive(Default)]
pub(super) struct Policy {
pub ignore_errors: bool,
approved: HashSet<(String, String)>,
pending: Option<Failure>,
}
#[derive(Clone)]
struct Failure {
identity: (String, String),
failure: TlsFailure,
generation: u64,
}
fn reason(error: COREWEBVIEW2_WEB_ERROR_STATUS) -> TlsFailureReason {
match error {
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT => TlsFailureReason::HostnameMismatch,
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED => TlsFailureReason::Expired,
_ => TlsFailureReason::InvalidCertificate,
}
}
pub(super) fn install(state: &Rc<State>) -> windows::core::Result<()> {
let weak = Rc::downgrade(state);
let handler = ServerCertificateErrorDetectedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let uri = text(|p| args.RequestUri(p))?;
let host = url::Url::parse(&uri)
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_default();
let pem = text(|p| args.ServerCertificate()?.ToPemEncoding(p))?;
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
args.ErrorStatus(&mut error)?;
let identity = (host.clone(), pem);
let mut policy = state.tls.borrow_mut();
if policy.ignore_errors || policy.approved.contains(&identity) {
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_ALWAYS_ALLOW)?;
} else {
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_CANCEL)?;
let generation = state.document.borrow().1;
let failure = TlsFailure {
host,
reason: reason(error),
can_continue: error != COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_REVOKED,
};
state
.messenger
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure.clone())));
policy.pending = Some(Failure {
identity,
failure,
generation,
});
}
}
Ok(())
}));
let mut token = 0;
unsafe {
state
.core
.cast::<ICoreWebView2_14>()?
.add_ServerCertificateErrorDetected(&handler, &mut token)
}
}
pub(super) fn confirm(state: &State) -> anyhow::Result<()> {
let pending = state
.tls
.borrow()
.pending
.clone()
.context("No certificate error to confirm")?;
if !pending.failure.can_continue || pending.generation != state.messenger.generation() {
bail!("This certificate exception is no longer available");
}
let answer = unsafe {
MessageBoxW(
Some(state.controls.parent),
&HSTRING::from(pending.failure.confirmation_message()),
&HSTRING::from(pending.failure.confirmation_title()),
MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
)
};
if answer == IDYES {
let identity = pending.identity.clone();
let generation = pending.generation;
state.tls.borrow_mut().approved.insert(identity);
state.messenger.send_auth_event(AuthEvent::TlsAccepted(generation));
}
Ok(())
}
// WebView2 caches approvals in the session. Do not leave them for another sign-in window.
pub(super) fn clear_exceptions(core: &ICoreWebView2) {
if let Ok(core) = core.cast::<ICoreWebView2_14>() {
let _ = unsafe {
core.ClearServerCertificateErrorActions(&ClearServerCertificateErrorActionsCompletedHandler::create(Box::new(
|_| Ok(()),
)))
};
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_certificate_failure_reasons() {
assert_eq!(
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT),
TlsFailureReason::HostnameMismatch
);
assert_eq!(
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED),
TlsFailureReason::Expired
);
}
}
+3 -10
View File
@@ -10,17 +10,10 @@ license = "MIT"
[dependencies]
anyhow.workspace = true
log.workspace = true
open = { version = "5", optional = true }
webbrowser = { version = "1", optional = true }
which = { workspace = true, optional = true }
[features]
default = []
launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"]
[target.'cfg(windows)'.dependencies]
winreg = { version = "0.55", optional = true }
[target.'cfg(unix)'.dependencies]
open = { version = "5", optional = true }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
which = { workspace = true, optional = true }
launcher = ["dep:open", "dep:webbrowser", "dep:which"]
+2 -5
View File
@@ -1,11 +1,8 @@
#[cfg(all(feature = "launcher", windows))]
#[path = "platform/windows.rs"]
mod platform;
#[cfg(all(feature = "launcher", target_os = "macos"))]
#[path = "platform/macos.rs"]
mod platform;
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
#[path = "platform/generic.rs"]
mod platform;
@@ -41,7 +38,7 @@ impl<'a> Browser<'a> {
}
}
#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))]
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
pub(crate) fn as_str(&self) -> &str {
match self {
Browser::Auto => "auto",
@@ -1,35 +0,0 @@
//! Windows browsers are resolved through their registered App Paths.
use crate::Browser;
use anyhow::{Context, bail};
use std::path::PathBuf;
use winreg::{
RegKey,
enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
};
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
let executable = match browser {
Browser::Auto | Browser::Default => return webbrowser::open(url).context("Could not open the browser"),
Browser::Chrome => registered_browser("chrome.exe").context("Chrome is not installed")?,
Browser::Edge => registered_browser("msedge.exe").context("Edge is not installed")?,
Browser::Firefox => registered_browser("firefox.exe").context("Firefox is not installed")?,
Browser::Safari => bail!("Safari is not available on Windows"),
Browser::Other(program) => PathBuf::from(program),
};
std::process::Command::new(executable)
.arg(url)
.spawn()
.context("Could not open the configured browser")?;
Ok(())
}
fn registered_browser(name: &str) -> Option<PathBuf> {
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE].into_iter().find_map(|hive| {
let key = RegKey::predef(hive)
.open_subkey(format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{name}"))
.ok()?;
let path: String = key.get_value("").ok()?;
let path = PathBuf::from(path.trim_matches('"'));
path.is_file().then_some(path)
})
}
+5 -10
View File
@@ -5,16 +5,11 @@ fn main() {
let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap();
let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui");
let suffix = if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
".exe"
} else {
""
};
let gp_service_binary = workspace_dir.join(format!("target/debug/gpservice{suffix}"));
let gp_client_binary = workspace_dir.join(format!("target/debug/gpclient{suffix}"));
let gp_auth_binary = workspace_dir.join(format!("target/debug/gpauth{suffix}"));
let gp_gui_helper_binary = workspace_dir.join(format!("target/debug/gpgui-helper{suffix}"));
let gp_gui_binary = gpgui_dir.join(format!("target/debug/gpgui{suffix}"));
let gp_service_binary = workspace_dir.join("target/debug/gpservice");
let gp_client_binary = workspace_dir.join("target/debug/gpclient");
let gp_auth_binary = workspace_dir.join("target/debug/gpauth");
let gp_gui_helper_binary = workspace_dir.join("target/debug/gpgui-helper");
let gp_gui_binary = gpgui_dir.join("target/debug/gpgui");
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display());
+1 -1
View File
@@ -89,7 +89,7 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> {
let executable = executable.canonicalize().ok()?;
let bin_dir = executable.parent()?;
let binary = bin_dir.join(format!("{binary_name}{}", std::env::consts::EXE_SUFFIX));
let binary = bin_dir.join(binary_name);
if is_file(&binary) {
return Some(binary);
}
+1
View File
@@ -2,6 +2,7 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
#[cfg(target_os = "linux")]
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
#[cfg(target_os = "linux")]
-1
View File
@@ -1,3 +1,2 @@
pub mod binary_paths;
pub mod constants;
pub mod paths;
-32
View File
@@ -1,32 +0,0 @@
//! Machine-wide service state shared by the daemon and desktop clients.
use std::path::PathBuf;
pub fn service_lock_file() -> PathBuf {
#[cfg(unix)]
{
PathBuf::from("/var/run/gpservice.lock")
}
#[cfg(windows)]
{
std::env::var_os("ProgramData")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
.join("GP Connect")
.join("gpservice.lock")
}
}
#[cfg(windows)]
pub const SERVICE_PIPE: &str = r"\\.\pipe\GPConnect.Service";
#[cfg(windows)]
pub const SERVICE_NAME: &str = "GPConnect";
/// Installer-owned SYSTEM/Administrators-only state, including temporary keys.
#[cfg(windows)]
pub fn service_private_dir() -> PathBuf {
service_lock_file()
.parent()
.expect("service state directory")
.join("Private")
}
+4 -32
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license = "MIT"
[dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
common = { path = "../common" }
anyhow.workspace = true
base64.workspace = true
@@ -34,6 +35,7 @@ thiserror.workspace = true
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
url.workspace = true
regex.workspace = true
uzers = { workspace = true, optional = true }
serde_urlencoded.workspace = true
md5.workspace = true
sha2.workspace = true
@@ -46,9 +48,6 @@ snow.workspace = true
zeroize = { workspace = true, features = ["serde"] }
getrandom = "0.4"
# Used only by the opt-in certificate interoperability tests.
openssl = { workspace = true, optional = true }
# Optional dependencies for features
tauri = { workspace = true, optional = true }
clap = { workspace = true, optional = true }
@@ -79,6 +78,7 @@ cc = "1"
pkg-config = "0.3"
[dev-dependencies]
openssl.workspace = true
libloading = "0.9"
proptest.workspace = true
tokio = { workspace = true, features = ["test-util"] }
@@ -89,32 +89,4 @@ desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:u
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
openssl-tests = ["dep:openssl"]
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog", "dep:file-rotate"]
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
uzers = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies]
file-rotate = { version = "0.8.0", optional = true }
windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation"] }
[target.'cfg(windows)'.dev-dependencies]
windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] }
[[test]]
name = "certificate_compatibility"
required-features = ["openssl-tests"]
[[test]]
name = "client_certificate_chain"
required-features = ["openssl-tests"]
[[test]]
name = "client_certificate_extensions"
required-features = ["openssl-tests"]
[[test]]
name = "client_certificate_tls12_hash"
required-features = ["openssl-tests"]
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
-16
View File
@@ -1,16 +0,0 @@
# gpapi tests
Ordinary tests do not require OpenSSL. To run the Windows logger regression test:
```sh
cargo test -p gpapi --features logger --lib logger::windows::tests
```
The certificate interoperability suite uses OpenSSL as an independent TLS and
signature implementation. Full CI enables it explicitly:
```sh
cargo test -p gpapi --features logger,openssl-tests
```
This optional suite requires OpenSSL development headers and libraries.
+2 -16
View File
@@ -10,7 +10,6 @@ pub enum AnchorSource {
UnixMac,
UnixRandom,
MacosIokit,
WindowsSmbios,
}
impl From<AnchorSource> for u8 {
@@ -19,7 +18,6 @@ impl From<AnchorSource> for u8 {
AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3,
AnchorSource::WindowsSmbios => 4,
}
}
}
@@ -43,7 +41,6 @@ impl TryFrom<u8> for AnchorSource {
1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit),
4 => Ok(Self::WindowsSmbios),
value => Err(InvalidAnchorSource(value)),
}
}
@@ -68,7 +65,6 @@ impl DeviceAnchor {
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
AnchorSource::WindowsSmbios => b"gp-device-anchor:v1:windows-smbios-uuid:".as_slice(),
};
let mut input = domain.to_vec();
input.extend_from_slice(seed.as_ref());
@@ -85,7 +81,7 @@ mod tests {
#[test]
fn preserves_existing_hardware_ids_for_all_sources() {
let cases: [(AnchorSource, &[u8], &str); 4] = [
let cases: [(AnchorSource, &[u8], &str); 3] = [
(
AnchorSource::UnixMac,
&[0, 17, 34, 51, 68, 85],
@@ -101,11 +97,6 @@ mod tests {
b"12345678-1234-5678-9abc-def012345678",
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
),
(
AnchorSource::WindowsSmbios,
b"12345678-1234-5678-9abc-def012345678",
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
),
];
for (source, seed, expected) in cases {
let anchor = DeviceAnchor::derive(source, seed);
@@ -133,17 +124,12 @@ mod tests {
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
assert_eq!(serde_json::to_string(&AnchorSource::WindowsSmbios).unwrap(), "4");
assert_eq!(
serde_json::from_str::<AnchorSource>("4").unwrap(),
AnchorSource::WindowsSmbios
);
assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac
);
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("5").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
}
}
+1 -11
View File
@@ -109,7 +109,6 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "openssl-tests")]
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
@@ -181,12 +180,10 @@ mod tests {
);
}
#[cfg(feature = "openssl-tests")]
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
server_with_client_auth(tls, SslVerifyMode::NONE)
}
#[cfg(feature = "openssl-tests")]
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
@@ -236,7 +233,6 @@ mod tests {
(address, worker)
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
use crate::{
@@ -258,7 +254,6 @@ mod tests {
assert_eq!(tls.server, address);
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn certificate_bypass_allows_prelogin() {
use crate::{
@@ -275,7 +270,6 @@ mod tests {
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
let (address, worker) = server(false);
@@ -309,7 +303,7 @@ mod tests {
assert_eq!(classify(&error), None);
}
#[cfg(all(feature = "desktop", unix))]
#[cfg(feature = "desktop")]
#[test]
fn rendering_recovery_retains_client_certificate_requirement() {
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
@@ -336,7 +330,6 @@ mod tests {
);
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
use crate::{
@@ -378,7 +371,6 @@ mod tests {
}
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
use crate::{
@@ -411,7 +403,6 @@ mod tests {
assert!(!error.to_string().contains("passphrase"));
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
use crate::{
@@ -444,7 +435,6 @@ mod tests {
}
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
use crate::{
+10 -5
View File
@@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root)?;
let status = parse_extend_session_status(&root, &response)?;
info!("Extend-session gateway response status: {}", status);
@@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<Str
Ok(form)
}
fn parse_extend_session_status(root: &Element) -> anyhow::Result<String> {
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Extend-session response is missing status");
warn!("Malformed extend-session response body: {}", response.trim());
bail!("Malformed extend session response")
}
}
@@ -231,7 +231,10 @@ mod tests {
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(parse_extend_session_status(&root).unwrap(), "success");
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
}
#[test]
@@ -239,7 +242,9 @@ mod tests {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root).unwrap_err().to_string(),
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
"Malformed extend session response"
);
}
-15
View File
@@ -45,18 +45,3 @@ mod tests {
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
}
}
/// Collection metadata for the exact XML returned by a generated preview.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HipReport {
pub xml: String,
pub windows_updates: Option<WindowsUpdateStatus>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WindowsUpdateStatus {
/// Present only when this report includes a completed local patch observation.
pub checked_at: Option<u64>,
}
-3
View File
@@ -31,6 +31,3 @@ pub mod clap;
#[cfg(feature = "desktop")]
pub mod script_tun;
#[cfg(all(feature = "desktop", windows))]
pub mod windows;
-14
View File
@@ -12,20 +12,6 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
type BoxedLogger = Box<dyn Log + Send + Sync>;
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::init_file;
/// Keep helper diagnostics with the application's records when a file logger owns them.
pub fn diagnostic_writer() -> Box<dyn std::io::Write + Send> {
#[cfg(windows)]
if let Some(writer) = windows::diagnostic_writer() {
return writer;
}
Box::new(std::io::stderr())
}
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
#[cfg(target_os = "macos")]
if log_format == LogFormat::Text && macos_unified_log_enabled() {
-98
View File
@@ -1,98 +0,0 @@
use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount};
use std::{
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
sync::{Arc, Mutex, OnceLock},
};
const ROTATE_BYTES: usize = 5 * 1024 * 1024;
const ARCHIVE_COUNT: usize = 3;
static DIAGNOSTICS: OnceLock<DiagnosticWriter> = OnceLock::new();
#[derive(Clone)]
struct DiagnosticWriter(Arc<Mutex<FileRotate<AppendCount>>>);
impl DiagnosticWriter {
fn open(path: &Path) -> io::Result<Self> {
if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
// FileRotate's constructor suppresses open errors, so check the destination first.
OpenOptions::new().create(true).append(true).open(path)?;
Ok(Self(Arc::new(Mutex::new(FileRotate::new(
path,
AppendCount::new(ARCHIVE_COUNT),
ContentLimit::BytesSurpassed(ROTATE_BYTES),
Compression::None,
None,
)))))
}
}
impl Write for DiagnosticWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self
.0
.lock()
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
.write(bytes)
}
fn flush(&mut self) -> io::Result<()> {
self
.0
.lock()
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
.flush()
}
}
pub fn init_file(path: &Path, level: log::Level) -> io::Result<()> {
let writer = DiagnosticWriter::open(path)?;
let logger = super::build_env_logger(crate::log_format::LogFormat::Text)
.target(env_logger::Target::Pipe(Box::new(writer.clone())))
.build();
DIAGNOSTICS
.set(writer)
.map_err(|_| io::Error::other("File logging is already initialized"))?;
super::init_with_logger(level, logger);
Ok(())
}
pub(super) fn diagnostic_writer() -> Option<Box<dyn Write + Send>> {
DIAGNOSTICS
.get()
.map(|writer| Box::new(writer.clone()) as Box<dyn Write + Send>)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gui_and_helper_writers_share_rotation_and_keep_only_three_archives() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("logs/gui.log");
let mut gui = DiagnosticWriter::open(&path).unwrap();
let mut helper = gui.clone();
for marker in b'0'..=b'5' {
let writer = if marker % 2 == 0 { &mut gui } else { &mut helper };
writer.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
}
helper.flush().unwrap();
drop((gui, helper));
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
assert_eq!(
fs::read(path.with_extension(format!("log.{suffix}"))).unwrap(),
vec![marker; ROTATE_BYTES + 1]
);
}
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 4);
let mut reopened = DiagnosticWriter::open(&path).unwrap();
reopened.write_all(b"after restart\n").unwrap();
reopened.flush().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"after restart\n");
}
}
+1 -8
View File
@@ -173,12 +173,6 @@ pub fn collect_profile_with_control(
Some(identity) => identity.clone(),
None => collect_with_host_id_and_control(host_id_override, control)?,
};
#[cfg(windows)]
let identity = if builder.client_os == ClientOs::Windows {
windows::native_profile_identity(identity, host_id_override)?
} else {
identity
};
let runtime_os = runtime_client_os();
// Preserve the old behavior: only probe the native version when reporting it.
let (os_version, software_version) = if builder.client_os == runtime_os {
@@ -187,8 +181,7 @@ pub fn collect_profile_with_control(
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
};
control.check()?;
// The builder may carry cached hardware identity; use the resolved profile identity.
Ok(builder.host_identity(identity.clone()).build(HostSnapshot {
Ok(builder.build(HostSnapshot {
runtime_os,
identity,
os_version,
+2 -85
View File
@@ -137,24 +137,14 @@ fn assert_mac(value: &str, separator: char) {
}
#[test]
fn builder_preserves_supplied_hardware_fields() {
fn builder_delegates_default_identity_to_host_identity() {
let expected = collect_identity();
let profile = collect_profile(
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
None,
);
assert!(
profile
.host_identity()
.computer()
.eq_ignore_ascii_case(expected.computer())
);
assert_eq!(profile.host_identity().serialno(), expected.serialno());
assert_eq!(profile.host_identity().mac_addr(), expected.mac_addr());
if runtime_client_os() != ClientOs::Windows {
assert_eq!(profile.host_identity().host_id(), expected.host_id());
}
assert_eq!(profile.host_identity(), &expected);
}
#[test]
@@ -188,76 +178,3 @@ fn controlled_profile_collection_propagates_cancellation_and_deadline() {
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
#[cfg(windows)]
#[test]
fn native_windows_profile_uses_installation_id_and_emulation_keeps_its_seed() {
let identity = HostIdentity::from_parts(
"test-host".into(),
"hardware-seed".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let control = CollectionBudget::new(Duration::from_secs(60));
let native = collect_profile_with_control(
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
None,
&control,
)
.unwrap();
// Read independently through the registry CLI to check the native API's source and view.
let output = std::process::Command::new("reg")
.args([
"query",
r"HKLM\SOFTWARE\Microsoft\Cryptography",
"/v",
"MachineGuid",
"/reg:64",
])
.output()
.unwrap();
assert!(output.status.success());
let text = String::from_utf8(output.stdout).unwrap();
let expected = text
.lines()
.find_map(|line| {
let mut parts = line.split_whitespace();
(parts.next()? == "MachineGuid").then(|| parts.last().unwrap())
})
.unwrap();
assert_eq!(native.host_id(), expected);
assert_eq!(native.host_identity().host_id(), expected);
assert!(native.computer().eq_ignore_ascii_case(&fallback_hostname()));
let with_host_id = collect_profile_with_control(
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
Some("explicit-host-id"),
&control,
)
.unwrap();
assert_eq!(with_host_id.host_id(), "explicit-host-id");
assert_eq!(with_host_id.computer(), native.computer());
let overridden = collect_profile_with_control(
OsProfile::builder(ClientOs::Windows)
.host_identity(identity.clone())
.computer_name_override("Custom-Host"),
None,
&control,
)
.unwrap();
assert_eq!(overridden.computer(), "Custom-Host");
for client_os in [ClientOs::Mac, ClientOs::Linux] {
let builder = OsProfile::builder(client_os).host_identity(identity.clone());
let expected = builder.clone().build(HostSnapshot {
runtime_os: ClientOs::Windows,
identity: identity.clone(),
os_version: String::new(),
software_version: String::new(),
});
let actual = collect_profile_with_control(builder, None, &control).unwrap();
assert_eq!(actual.host_identity(), &identity);
assert_eq!(actual.host_id(), expected.host_id());
assert_eq!(actual.serialno(), expected.serialno());
assert_eq!(actual.mac_addr(), expected.mac_addr());
}
}
+19 -66
View File
@@ -1,7 +1,4 @@
use std::{io, os::windows::process::CommandExt, process::Command};
use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RRF_SUBKEY_WOW6464KEY, RegGetValueW};
use windows_sys::Win32::System::SystemInformation::{ComputerNamePhysicalNetBIOS, GetComputerNameExW};
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
@@ -39,7 +36,6 @@ impl RuntimeNativeHostIdentity {
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.creation_flags(CREATE_NO_WINDOW)
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
@@ -54,15 +50,11 @@ fn collect_windows_serial_number() -> Option<String> {
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(|| collect_windows_machine_guid().ok())
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic")
.creation_flags(CREATE_NO_WINDOW)
.args(["csproduct", "get", "uuid"])
.output()
.ok()?;
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
@@ -73,63 +65,24 @@ fn collect_windows_csproduct_uuid() -> Option<String> {
.next()
}
// Native Windows uses the OS installation ID and physical NetBIOS name.
// Keep the hardware identity used to seed other OS profiles unchanged.
pub(super) fn native_profile_identity(
identity: super::HostIdentity,
host_id_override: Option<&str>,
) -> io::Result<super::HostIdentity> {
let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) {
Some(id) => id.to_owned(),
None => collect_windows_machine_guid()?,
};
Ok(super::HostIdentity::from_parts(
collect_windows_computer_name()?,
host_id,
identity.serialno().into(),
identity.mac_addr().into(),
))
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
fn collect_windows_computer_name() -> io::Result<String> {
let mut name = [0u16; 256];
let mut size = name.len() as u32;
// SAFETY: the buffer and character count describe writable UTF-16 storage.
if unsafe { GetComputerNameExW(ComputerNamePhysicalNetBIOS, name.as_mut_ptr(), &mut size) } == 0 {
return Err(io::Error::last_os_error());
}
String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
fn collect_windows_machine_guid() -> io::Result<String> {
let key: Vec<u16> = "SOFTWARE\\Microsoft\\Cryptography\0".encode_utf16().collect();
let value: Vec<u16> = "MachineGuid\0".encode_utf16().collect();
let mut buffer = [0u16; 128];
let mut size = std::mem::size_of_val(&buffer) as u32;
// SAFETY: both names are NUL-terminated; buffer and byte length describe writable storage.
let status = unsafe {
RegGetValueW(
HKEY_LOCAL_MACHINE,
key.as_ptr(),
value.as_ptr(),
RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY,
std::ptr::null_mut(),
buffer.as_mut_ptr().cast(),
&mut size,
)
};
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32));
}
let end = buffer.iter().position(|value| *value == 0).unwrap_or(buffer.len());
let guid = String::from_utf16(&buffer[..end]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
if guid.trim().is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Windows MachineGuid is empty",
));
}
Ok(guid)
parts.last().map(str::to_string)
})
}
impl RuntimeNativeHostIdentity {
+2 -1
View File
@@ -124,7 +124,8 @@ impl OsProfile {
self.runtime_os == self.client_os
}
/// Software version for the target OS profile.
/// Default software version string for the target OS, matching the
/// official client values.
pub fn software_version(&self) -> &str {
&self.software_version
}
+6 -6
View File
@@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() {
}
#[test]
fn csc_support_defaults_match_platform_profiles() {
fn csc_support_defaults_match_official_profiles() {
assert!(!ClientOs::Linux.default_csc_support());
assert!(ClientOs::Mac.default_csc_support());
assert!(ClientOs::Windows.default_csc_support());
}
#[test]
fn prelogin_param_location_matches_platform_profiles() {
fn prelogin_param_location_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -91,7 +91,7 @@ fn embedded_gateway_default_browser_is_zero_for_all() {
}
#[test]
fn external_default_browser_values_match_platform_profiles() {
fn external_default_browser_values_match_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -132,7 +132,7 @@ fn external_default_browser_values_match_platform_profiles() {
}
#[test]
fn saml_password_matches_platform_profiles() {
fn saml_password_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -173,7 +173,7 @@ fn gateway_server_uses_resolved_ipv4_for_all() {
}
#[test]
fn kerberos_support_in_query_matches_platform_profiles() {
fn kerberos_support_in_query_matches_official_profiles() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_platform_profiles() {
}
#[test]
fn os_vendor_matches_platform_profiles() {
fn os_vendor_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
+3 -1
View File
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use anyhow::bail;
use log::{info, warn};
use log::{debug, info, warn};
use reqwest::{Client, StatusCode};
use serde::Serialize;
use specta::Type;
@@ -232,6 +232,7 @@ pub async fn retrieve_config(
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
}
debug!("Portal config response received: {} bytes", res_xml.len());
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
@@ -246,6 +247,7 @@ pub async fn retrieve_config(
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
};
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_policy(&server, cred, root, cancellation).await;
}
+4 -2
View File
@@ -1,5 +1,5 @@
use anyhow::{anyhow, bail};
use log::{info, warn};
use log::{debug, info, warn};
use reqwest::{Client, StatusCode};
use serde::Serialize;
use specta::Type;
@@ -174,8 +174,10 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
Err(anyhow!(PortalError::PreloginError(err.reason)))
})?;
debug!("Prelogin response XML: {}", res_xml);
let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| {
warn!("Failed to parse prelogin response: {err}");
warn!("Parse response error, response: {}", res_xml);
PortalError::PreloginError(err.to_string())
})?;
+10 -77
View File
@@ -21,10 +21,6 @@ use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_c
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
#[cfg(windows)]
/// The caller that receives foreground permission after browser authentication.
pub const AUTH_PARENT_PROCESS_ID_ENV: &str = "GPAUTH_PARENT_PROCESS_ID";
pub struct SamlAuthLauncher<'a> {
cancellation: CancellationToken,
server: &'a str,
@@ -201,8 +197,6 @@ impl<'a> SamlAuthLauncher<'a> {
/// argument that never gets appended.
fn build_command(&self, program: &Path) -> Command {
let mut auth_cmd = Command::new(program);
#[cfg(windows)]
auth_cmd.env(AUTH_PARENT_PROCESS_ID_ENV, std::process::id().to_string());
auth_cmd.arg(self.server);
if self.gateway {
@@ -242,7 +236,7 @@ impl<'a> SamlAuthLauncher<'a> {
}
#[cfg(feature = "webview-auth")]
if self.browser.is_none() {
{
if self.hidpi {
auth_cmd.arg("--hidpi");
}
@@ -312,16 +306,12 @@ impl<'a> SamlAuthLauncher<'a> {
}
};
let mut diagnostic = StderrDiagnostic::default();
#[cfg(feature = "logger")]
let mut stderr = crate::logger::diagnostic_writer();
#[cfg(not(feature = "logger"))]
let mut stderr = std::io::stderr();
let output = run_observed(
command,
&check,
Some(MAX_AUTH_RESULT_BYTES),
&mut |bytes| diagnostic.push(bytes),
&mut stderr,
&mut std::io::stderr(),
stdin,
)?;
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
@@ -376,14 +366,11 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) ->
mod tests {
use super::*;
use crate::os_profile::{ClientOs, OsProfileBuilder};
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
#[cfg(windows)]
use std::os::windows::process::ExitStatusExt;
#[test]
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
use crate::error::{ServerTlsError, ServerTlsErrorKind};
use std::os::unix::process::ExitStatusExt;
let output = std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
@@ -402,6 +389,7 @@ mod tests {
#[test]
fn client_certificate_required_result_survives_process_decoding() {
use crate::error::{ServerTlsError, ServerTlsErrorKind};
use std::os::unix::process::ExitStatusExt;
let output = std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
@@ -421,42 +409,6 @@ mod tests {
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
}
#[cfg(feature = "webview-auth")]
#[test]
fn external_browser_receives_no_embedded_window_arguments() {
let args = child_args(
SamlAuthLauncher::new("vpn.example.com")
.browser(Some("edge"))
.clean(true)
.hidpi(true)
.window_title("GP Connect Login")
.window_theme(AuthWindowTheme::Dark),
);
assert!(args.windows(2).any(|pair| pair == ["--browser", "edge"]));
for option in ["--clean", "--hidpi", "--window-title", "--window-theme"] {
assert!(!args.iter().any(|arg| arg == option), "unexpected {option} in {args:?}");
}
}
#[cfg(feature = "webview-auth")]
#[test]
fn embedded_window_receives_auth_preferences() {
let args = child_args(
SamlAuthLauncher::new("vpn.example.com")
.clean(true)
.window_title("GP Connect Login")
.window_theme(AuthWindowTheme::Dark),
);
assert!(args.iter().any(|arg| arg == "--clean"));
assert!(
args
.windows(2)
.any(|pair| pair == ["--window-title", "GP Connect Login"])
);
assert!(args.windows(2).any(|pair| pair == ["--window-theme", "dark"]));
assert!(!args.iter().any(|arg| arg == "--browser"));
}
#[test]
fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
@@ -499,19 +451,6 @@ mod tests {
.collect()
}
#[cfg(windows)]
#[test]
fn auth_child_receives_its_foreground_parent() {
let command = SamlAuthLauncher::new("portal.example.com").build_command(Path::new("gpauth"));
let parent = command
.as_std()
.get_envs()
.find(|(name, _)| *name == AUTH_PARENT_PROCESS_ID_ENV)
.and_then(|(_, value)| value)
.expect("the authenticator must know its foreground recipient");
assert_eq!(parent, std::process::id().to_string().as_str());
}
/// gpauth writes to the same stderr as its parent, so a caller reading the
/// parent's JSON would hit gpauth's text records mid-stream unless the format
/// is passed down.
@@ -574,14 +513,11 @@ mod tests {
#[test]
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
#[cfg(unix)]
let status = std::process::ExitStatus::from_raw(71 << 8);
#[cfg(windows)]
let status = std::process::ExitStatus::from_raw(0xC0000005);
use std::os::unix::process::ExitStatusExt;
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
let error = decode_auth_output(
std::process::Output {
status,
status: std::process::ExitStatus::from_raw(71 << 8),
stdout,
stderr: Vec::new(),
},
@@ -594,6 +530,7 @@ mod tests {
#[test]
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
use std::os::unix::process::ExitStatusExt;
let error = decode_auth_output(
std::process::Output {
status: std::process::ExitStatus::from_raw(0),
@@ -607,7 +544,6 @@ mod tests {
assert_eq!(error.to_string(), "Failed to parse auth data");
}
#[cfg(unix)]
#[tokio::test]
async fn custom_authenticator_crash_does_not_request_recovery() {
use std::os::unix::fs::PermissionsExt;
@@ -643,11 +579,8 @@ mod tests {
std::fs::write(&custom, "custom").unwrap();
assert!(is_bundled_authenticator(&bundled, &bundled));
assert!(!is_bundled_authenticator(&custom, &bundled));
#[cfg(unix)]
{
let alias = directory.path().join("auth-alias");
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
assert!(is_bundled_authenticator(&alias, &bundled));
}
let alias = directory.path().join("auth-alias");
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
assert!(is_bundled_authenticator(&alias, &bundled));
}
}
+2 -23
View File
@@ -1,41 +1,20 @@
#[cfg(unix)]
mod command_runner;
#[cfg(windows)]
#[path = "windows/command_runner.rs"]
mod command_runner;
#[cfg(unix)]
mod command_traits;
#[cfg(windows)]
#[path = "windows/command_traits.rs"]
mod command_traits;
#[cfg(unix)]
mod desktop_child;
#[cfg(unix)]
mod desktop_session_env;
#[cfg(unix)]
pub(crate) mod gui_helper_launcher;
pub use command_traits::CommandExt;
pub mod auth_launcher;
#[cfg(unix)]
pub mod desktop_launcher;
#[cfg(unix)]
pub mod gui_launcher;
#[cfg(any(target_os = "linux", all(test, unix)))]
#[cfg(any(target_os = "linux", test))]
pub mod gui_switch;
#[cfg(any(target_os = "linux", all(test, unix)))]
#[cfg(any(target_os = "linux", test))]
mod nsh_runtime;
#[cfg(unix)]
pub mod users;
#[cfg(unix)]
pub mod collection;
#[cfg(windows)]
#[path = "windows/collection.rs"]
pub mod collection;
pub mod rendering_recovery;
#[cfg(windows)]
#[path = "windows/user_process.rs"]
pub mod user_process;
@@ -49,17 +49,11 @@ impl RecoveryState {
}
}
#[cfg(unix)]
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
use std::os::unix::process::ExitStatusExt;
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15))
}
#[cfg(windows)]
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
status.code().is_some_and(|code| (code as u32) >= 0xC0000000)
}
pub fn eligible(command: &Command) -> bool {
eligible_with_inheritance(command, true)
}
@@ -198,7 +192,6 @@ mod tests {
assert!(!eligible_with_inheritance(&command, false));
}
#[cfg(unix)]
#[test]
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
use std::os::unix::process::ExitStatusExt;
@@ -220,7 +213,6 @@ mod tests {
assert!(error.to_string().contains("71"));
assert!(error.to_string().contains("second exit 72"));
}
#[cfg(unix)]
#[test]
fn explicit_termination_is_not_a_rendering_crash() {
use std::os::unix::process::ExitStatusExt;
@@ -1,42 +0,0 @@
//! Resolve system collectors from Windows' system directory, never the working directory.
use super::command_runner::run_controlled;
use crate::collection::CollectionControl;
use std::{
io,
path::{Path, PathBuf},
process::{Command, Output},
};
pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl,
}
impl<'a> CollectorCommands<'a> {
pub fn new(control: &'a dyn CollectionControl) -> Self {
Self { control }
}
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
let system = std::env::var_os("SystemRoot")?;
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
path.is_file().then_some(path)
}
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
match self.resolve(name) {
Some(path) => self.run_path(&path, args),
None => Ok(None),
}
}
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.run_path(path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let mut command = Command::new(path);
command.args(args);
match run_controlled(command, self.control, 256 * 1024) {
Ok(output) => Ok(Some(output)),
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
Err(error) => Err(error),
}
}
}
@@ -1,198 +0,0 @@
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
use crate::collection::CollectionControl;
use std::{
io::{self, Read, Write},
os::windows::io::AsRawHandle,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
};
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
pub(crate) enum ChildInput<'a> {
Null,
Terminal,
// Preserve the borrowed input type shared by callers without a Windows launcher.
#[allow(dead_code)]
Frame(&'a [u8]),
}
#[derive(Debug)]
pub(crate) struct ObservedOutput {
pub output: Output,
}
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
run_observed(
command,
control,
Some(limit),
&mut |_| {},
&mut io::sink(),
ChildInput::Null,
)
.map(|observed| observed.output)
}
pub(crate) fn run_observed(
mut command: Command,
control: &dyn CollectionControl,
output_limit: Option<usize>,
observer: &mut dyn FnMut(&[u8]),
stderr_sink: &mut dyn Write,
stdin: ChildInput<'_>,
) -> io::Result<ObservedOutput> {
control.check()?;
// Windows desktop processes must not open a console for each helper.
use std::os::windows::process::CommandExt;
if !matches!(stdin, ChildInput::Terminal) {
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
command.stdout(if output_limit.is_some() {
Stdio::piped()
} else {
Stdio::inherit()
});
command.stderr(Stdio::piped());
command.stdin(match stdin {
ChildInput::Terminal => Stdio::inherit(),
ChildInput::Null => Stdio::null(),
ChildInput::Frame(_) => Stdio::piped(),
});
let mut child = ControlledChild(command.spawn()?);
let input = if let ChildInput::Frame(frame) = stdin {
let mut pipe = child.0.stdin.take().expect("piped stdin");
let frame = frame.to_vec();
Some(thread::spawn(move || pipe.write_all(&frame)))
} else {
None
};
let mut stdout = child.0.stdout.take();
let mut stderr = child.0.stderr.take().expect("piped stderr");
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
loop {
control.check()?;
if let Some(pipe) = &mut stdout {
let length = read_available(pipe, &mut buffer)?;
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
let length = read_available(&mut stderr, &mut buffer)?;
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
if let Some(status) = child.0.try_wait()? {
// Drain the remaining buffered output after the process exits.
if let Some(pipe) = &mut stdout {
loop {
let length = read_available(pipe, &mut buffer)?;
if length == 0 {
break;
}
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
}
loop {
let length = read_available(&mut stderr, &mut buffer)?;
if length == 0 {
break;
}
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
}
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
result?;
}
return Ok(ObservedOutput {
output: Output {
status,
stdout: output,
stderr: Vec::new(),
},
});
}
thread::sleep(Duration::from_millis(10));
}
}
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
let mut available = 0;
let success = unsafe {
PeekNamedPipe(
pipe.as_raw_handle(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
&mut available,
std::ptr::null_mut(),
)
};
if success == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(109) {
return Ok(0);
} // ERROR_BROKEN_PIPE
return Err(error);
}
let length = buffer.len().min(available as usize);
if length == 0 {
return Ok(0);
}
pipe.read(&mut buffer[..length])
}
struct ControlledChild(Child);
impl Drop for ControlledChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captures_output_and_rejects_excess_output() {
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo hello"]);
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
assert!(result.status.success());
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo too much"]);
assert_eq!(
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
io::ErrorKind::InvalidData
);
}
#[test]
fn cancels_a_running_helper() {
let start = std::time::Instant::now();
let mut command = Command::new("powershell.exe");
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
let control = || {
if start.elapsed() > Duration::from_millis(150) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
assert_eq!(
run_controlled(command, &control, 1024).unwrap_err().kind(),
io::ErrorKind::Interrupted
);
assert!(start.elapsed() < Duration::from_secs(3));
}
}
@@ -1,12 +0,0 @@
use tokio::process::Command;
/// Windows authentication runs in the interactive user's GUI process.
pub trait CommandExt {
fn into_non_root(self) -> anyhow::Result<Command>;
}
impl CommandExt for Command {
fn into_non_root(self) -> anyhow::Result<Command> {
Ok(self)
}
}
@@ -1,309 +0,0 @@
//! Launch a native worker with the admitted user's primary token and environment.
use std::{
ffi::{OsStr, c_void},
io,
os::windows::{
ffi::OsStrExt,
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
},
path::Path,
ptr,
};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
Security::{ImpersonateLoggedOnUser, RevertToSelf},
System::{
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
JobObjects::*,
Threading::*,
},
};
pub struct UserProcess {
process: OwnedHandle,
job: Option<OwnedHandle>,
pid: u32,
}
struct Environment(*mut c_void);
impl Drop for Environment {
fn drop(&mut self) {
unsafe {
DestroyEnvironmentBlock(self.0);
}
}
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
let value: Vec<_> = value.encode_wide().collect();
if value.contains(&0) {
return Err(invalid("Windows process strings cannot contain NUL"));
}
Ok(value)
}
fn quote(argument: &[u16], output: &mut Vec<u16>) {
output.push(b'"' as u16);
let mut backslashes = 0;
for &character in argument {
if character == b'\\' as u16 {
backslashes += 1;
continue;
}
let count = if character == b'"' as u16 {
backslashes * 2 + 1
} else {
backslashes
};
output.extend(std::iter::repeat_n(b'\\' as u16, count));
output.push(character);
backslashes = 0;
}
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
output.push(b'"' as u16);
}
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
let mut output = Vec::new();
quote(program, &mut output);
for argument in arguments {
output.push(b' ' as u16);
quote(&wide(OsStr::new(argument))?, &mut output);
}
output.push(0);
if output.len() > 32767 {
return Err(invalid("Windows worker command line is too long"));
}
Ok(output)
}
fn key(entry: &[u16]) -> &[u16] {
let end = entry
.iter()
.enumerate()
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
.map(|(index, _)| index)
.unwrap_or(entry.len());
&entry[..end]
}
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
// Environment names follow Windows' ordinal, case-insensitive ordering.
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
.cmp(&CSTR_EQUAL)
}
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
let mut pointer = ptr::null_mut();
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
return Err(io::Error::last_os_error());
}
let environment = Environment(pointer);
let mut entries = Vec::new();
unsafe {
let mut current = environment.0.cast::<u16>();
while *current != 0 {
let mut length = 0;
while *current.add(length) != 0 {
length += 1;
}
entries.push(std::slice::from_raw_parts(current, length).to_vec());
current = current.add(length + 1);
}
}
for (name, value) in variables {
if name.is_empty() || name.contains('=') {
return Err(invalid("Invalid worker environment name"));
}
let name = wide(OsStr::new(name))?;
let value = wide(OsStr::new(value))?;
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
let mut entry = name;
entry.push(b'=' as u16);
entry.extend(value);
entries.push(entry);
}
entries.sort_by(|left, right| compare(key(left), key(right)));
let mut block = Vec::new();
for entry in entries {
block.extend(entry);
block.push(0);
}
if block.is_empty() {
block.push(0);
}
block.push(0);
Ok(block)
}
impl UserProcess {
/// No service handles or service environment are inherited. The user token
/// determines the Windows session, including an existing interactive desktop.
pub fn launch(
token: BorrowedHandle<'_>,
program: &Path,
arguments: &[String],
variables: &[(&str, &str)],
) -> io::Result<Self> {
if !program.is_absolute() {
return Err(invalid("Windows worker executable must be absolute"));
}
let mut executable = wide(program.as_os_str())?;
let mut command = command_line(&executable, arguments)?;
executable.push(0);
let mut environment = user_environment(token, variables)?;
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
let mut directory = wide(directory.as_os_str())?;
directory.push(0);
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
if job.is_null() {
return Err(io::Error::last_os_error());
}
let job = unsafe { OwnedHandle::from_raw_handle(job) };
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
..Default::default()
},
..Default::default()
};
if unsafe {
SetInformationJobObject(
job.as_raw_handle(),
JobObjectExtendedLimitInformation,
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
std::mem::size_of_val(&limits) as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
let startup = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
lpDesktop: desktop.as_mut_ptr(),
..Default::default()
};
let mut information = PROCESS_INFORMATION::default();
// Read/execute the requested image as its user, as Unix exec-after-setuid
// does. The service's filesystem access must not authorize a private image.
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
return Err(io::Error::last_os_error());
}
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
let revert = Revert;
let created = unsafe {
CreateProcessAsUserW(
token.as_raw_handle(),
executable.as_ptr(),
command.as_mut_ptr(),
ptr::null(),
ptr::null(),
0,
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
environment.as_mut_ptr().cast(),
directory.as_ptr(),
&startup,
&mut information,
)
};
let error = (created == 0).then(io::Error::last_os_error);
drop(revert);
if let Some(error) = error {
return Err(error);
}
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
let error = io::Error::last_os_error();
// The suspended child is not owned by the job on this failure path.
unsafe {
TerminateProcess(process.as_raw_handle(), 1);
WaitForSingleObject(process.as_raw_handle(), 5000);
}
return Err(error);
}
let child = Self {
process,
job: Some(job),
pid: information.dwProcessId,
};
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
Ok(child)
}
pub fn id(&self) -> u32 {
self.pid
}
pub fn has_exited(&self) -> io::Result<bool> {
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
WAIT_OBJECT_0 => Ok(true),
WAIT_TIMEOUT => Ok(false),
_ => Err(io::Error::last_os_error()),
}
}
pub fn stop(&mut self) -> io::Result<()> {
if self.job.take().is_none() {
return Ok(());
}
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
WAIT_OBJECT_0 => Ok(()),
WAIT_TIMEOUT => Err(io::Error::new(
io::ErrorKind::TimedOut,
"Windows worker did not terminate",
)),
_ => Err(io::Error::last_os_error()),
}
}
}
impl Drop for UserProcess {
fn drop(&mut self) {
if let Err(error) = self.stop() {
log::warn!("Could not stop Windows worker: {error}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
#[test]
fn command_line_round_trips_through_windows_parser() {
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
let arguments = [
"proxy-worker",
"",
"space value",
"quoted\"value",
"two\\\\\"quotes",
"trailing\\",
"雪",
"&|<>",
]
.map(String::from);
let command = command_line(&program, &arguments).unwrap();
let mut count = 0;
unsafe {
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
assert!(!parsed.is_null());
let result = std::slice::from_raw_parts(parsed, count as usize)
.iter()
.map(|&value| {
let mut length = 0;
while *value.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
})
.collect::<Vec<_>>();
LocalFree(parsed.cast());
assert_eq!(result[0], String::from_utf16_lossy(&program));
assert_eq!(result[1..], arguments);
}
}
}
-2
View File
@@ -424,8 +424,6 @@ pub struct UpdateLogLevelRequest(pub String);
#[derive(Debug, Deserialize, Serialize)]
pub enum WsRequest {
SetTunnelStatisticsEnabled { enabled: bool },
SetWindowsPatchInterest { enabled: bool },
RefreshWindowsPatches { after: Option<u64> },
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StopNonTunnelAttachment { connection_id: uuid::Uuid },
@@ -187,28 +187,19 @@ mod tests {
#[test]
fn credential_round_trips_a_validated_device_anchor() {
use crate::device_anchor::AnchorSource;
for (source, wire_source) in [
(AnchorSource::UnixMac, 1),
(AnchorSource::UnixRandom, 2),
(AnchorSource::MacosIokit, 3),
(AnchorSource::WindowsSmbios, 4),
] {
let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source,
};
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap()
.with_device_anchor(anchor.clone())
.unwrap();
let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], wire_source);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor));
}
let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source: crate::device_anchor::AnchorSource::UnixMac,
};
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap()
.with_device_anchor(anchor.clone())
.unwrap();
let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], 1);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor));
}
#[test]
@@ -218,7 +209,7 @@ mod tests {
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
for source in [0, u8::MAX] {
for source in [0, 4] {
payload["device_anchor"] = serde_json::json!({
"hardware_id": hardware_id,
"source": source
@@ -55,8 +55,6 @@ pub enum ServiceResult {
offset: usize,
xml: String,
complete: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
windows_updates: Option<crate::hip::WindowsUpdateStatus>,
},
HipApprovalStatus(HipApprovalStatus),
NoSubmittedHipReport,
@@ -11,8 +11,6 @@ pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult}
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
pub const MAX_CREDENTIAL_FRAME: usize = 512;
/// First request read before a Windows service captures its pipe client's token.
pub const WINDOWS_ADMISSION_REQUEST: [u8; 4] = *b"GPC1";
pub const MAX_PRELUDE: usize = 256;
pub const MAX_PRODUCT_VERSION: usize = 64;
pub const HIP_PROTOCOL_VERSION: u16 = 1;
@@ -29,11 +29,6 @@ use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as platform;
mod binding;
use super::detection;
pub mod native;
@@ -480,7 +475,6 @@ fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow
})
}
#[cfg(unix)]
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
let output = CollectorCommands::new(control)
.run(name, args)?
@@ -172,7 +172,6 @@ mod tests {
);
}
#[cfg(unix)]
#[tokio::test]
async fn cancellation_kills_and_joins_the_running_resolver_process() {
let file = tempfile::NamedTempFile::new().unwrap();
@@ -1,148 +0,0 @@
//! Windows network identity from IP Helper and adapter DNS configuration.
use super::*;
use std::os::windows::io::AsRawSocket;
use windows_sys::Win32::{
NetworkManagement::IpHelper::{
DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1, FreeInterfaceDnsSettings, FreeMibTable,
GetInterfaceDnsSettings, GetIpForwardTable2,
},
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, IP_UNICAST_IF, IPPROTO_IP, IPPROTO_IPV6, IPV6_UNICAST_IF, SOCKADDR_INET,
SOCKET_ERROR, WSAGetLastError, setsockopt,
},
};
pub(super) fn scope_resolver_socket(
socket: &tokio::net::UdpSocket,
interface: &Interface,
endpoint: SocketAddr,
) -> anyhow::Result<()> {
ensure!(interface.index != 0, "Resolver interface index is missing");
// IP_UNICAST_IF uses network byte order; IPV6_UNICAST_IF uses host byte order.
let (level, option, index) = if endpoint.is_ipv4() {
(IPPROTO_IP, IP_UNICAST_IF, interface.index.to_be())
} else {
(IPPROTO_IPV6, IPV6_UNICAST_IF, interface.index)
};
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
level,
option,
(&index as *const u32).cast(),
std::mem::size_of::<u32>() as i32,
)
};
if result == SOCKET_ERROR {
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }).into());
}
Ok(())
}
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
control.check()?;
let mut table = std::ptr::null_mut();
let status = unsafe { GetIpForwardTable2(AF_UNSPEC, &mut table) };
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32).into());
}
let interfaces = netdev::get_interfaces();
let result = unsafe {
let rows = std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize);
rows
.iter()
.filter_map(|row| {
let destination = address(&row.DestinationPrefix.Prefix)?;
let gateway = address(&row.NextHop)?;
let interface = interfaces
.iter()
.find(|interface| interface.index == row.InterfaceIndex)?;
Some(RouteContext {
destination: format!("{destination}/{}", row.DestinationPrefix.PrefixLength),
gateway: gateway.to_string(),
interface: interface.name.clone(),
table: "main".into(),
metric: row.Metric.to_string(),
})
})
.collect()
};
unsafe {
FreeMibTable(table.cast());
}
control.check()?;
Ok(result)
}
unsafe fn address(address: &SOCKADDR_INET) -> Option<IpAddr> {
unsafe {
match address.si_family {
AF_INET => Some(std::net::Ipv4Addr::from(address.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()),
AF_INET6 => Some(std::net::Ipv6Addr::from(address.Ipv6.sin6_addr.u.Byte).into()),
_ => None,
}
}
}
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
control.check()?;
let mut resolvers = netdev::get_interfaces()
.into_iter()
.filter(|interface| !interface.dns_servers.is_empty())
.map(|interface| {
Ok(ResolverContext {
interface: Some(interface.name.clone()),
servers: interface.dns_servers.iter().map(ToString::to_string).collect(),
domains: resolver_domains(&interface.name)?,
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
resolvers.sort();
control.check()?;
Ok(resolvers)
}
fn resolver_domains(interface: &str) -> anyhow::Result<Vec<String>> {
let id = uuid::Uuid::parse_str(interface.trim_matches(['{', '}']))?;
let (data1, data2, data3, data4) = id.as_fields();
let guid = windows_sys::core::GUID {
data1,
data2,
data3,
data4: *data4,
};
let mut settings = DNS_INTERFACE_SETTINGS {
Version: DNS_INTERFACE_SETTINGS_VERSION1,
..Default::default()
};
let status = unsafe { GetInterfaceDnsSettings(guid, &mut settings) };
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32).into());
}
let mut domains = Vec::new();
for pointer in [settings.Domain, settings.SearchList] {
if pointer.is_null() {
continue;
}
let text = unsafe {
let mut length = 0;
while *pointer.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
};
for domain in text
.split(|ch: char| ch == ',' || ch.is_whitespace())
.filter(|domain| !domain.is_empty())
{
let domain = domain.to_ascii_lowercase();
if !domains.contains(&domain) {
domains.push(domain);
}
}
}
unsafe {
FreeInterfaceDnsSettings(&mut settings);
}
Ok(domains)
}
@@ -45,7 +45,7 @@ fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) ->
Ok(builder.interface(binding.interface()))
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))]
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
if let std::net::SocketAddr::V6(source) = binding.source() {
anyhow::ensure!(
@@ -164,7 +164,6 @@ async fn post(
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
})?;
crate::utils::log_response_xml(&format!("/ssl-vpn/{endpoint}"), status, &body);
parse_response(&body)
}
@@ -204,7 +204,6 @@ impl Signer for ClientSigner {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "openssl-tests")]
use openssl::{
hash::MessageDigest,
pkey::PKey,
@@ -221,7 +220,6 @@ mod tests {
.unwrap()
}
#[cfg(feature = "openssl-tests")]
fn native_key(bytes: &[u8]) -> ClientKey {
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
.unwrap()
@@ -229,7 +227,6 @@ mod tests {
ClientKey::load(&key).unwrap()
}
#[cfg(feature = "openssl-tests")]
#[test]
fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() {
let bytes = fixture("rsa-pkcs8.pem");
@@ -258,7 +255,6 @@ mod tests {
assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none());
}
#[cfg(feature = "openssl-tests")]
#[test]
fn p256_signatures_verify_with_an_independent_backend() {
let bytes = fixture("ec-pkcs8.pem");
@@ -285,7 +281,6 @@ mod tests {
}
}
#[cfg(feature = "openssl-tests")]
#[test]
fn a_key_remains_usable_when_shared_clients_sign_concurrently() {
let key = native_key(&fixture("rsa-pkcs8.pem"));
+2 -2
View File
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};
use common::paths::service_lock_file;
use common::constants::GP_SERVICE_LOCK_FILE;
use thiserror::Error;
use tokio::fs;
@@ -109,7 +109,7 @@ impl LockInfo {
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
gpservice_lock_info_at(service_lock_file()).await
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
}
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more