From 43c20d0976c394c30053e3c180e111c19c416f5a Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Thu, 19 Nov 2026 01:40:22 +0800 Subject: [PATCH 1/2] release: prepare GP Connect 3.5.0 with Windows support --- .github/workflows/build.yaml | 2 +- Cargo.lock | 119 ++++- Cargo.toml | 2 +- README.md | 23 +- apps/gpauth/Cargo.toml | 2 - apps/gpauth/build.rs | 3 + apps/gpauth/icons/windows/icon.ico | Bin 0 -> 47963 bytes apps/gpauth/src/cli.rs | 12 +- apps/gpauth/tauri.windows.conf.json | 5 + apps/gpauth/tests/windows_callback.rs | 29 ++ apps/gpclient/src/connect/flow_tests.rs | 28 +- apps/gpclient/src/connect/internal.rs | 19 +- apps/gpservice/Cargo.toml | 14 +- apps/gpservice/src/cli.rs | 13 +- apps/gpservice/src/cli/windows.rs | 12 + apps/gpservice/src/desktop_client.rs | 7 +- apps/gpservice/src/device_anchor.rs | 2 +- apps/gpservice/src/gui_installation.rs | 359 ++++++++++++++ apps/gpservice/src/hip_preview.rs | 44 +- apps/gpservice/src/hip_source.rs | 92 ++-- apps/gpservice/src/hip_source/unix.rs | 37 ++ apps/gpservice/src/hip_source/windows.rs | 3 + apps/gpservice/src/main.rs | 33 +- apps/gpservice/src/request_dispatcher.rs | 414 ++-------------- apps/gpservice/src/session_registry.rs | 36 ++ apps/gpservice/src/vpn_script/mod.rs | 8 +- apps/gpservice/src/vpn_script/windows.rs | 24 + apps/gpservice/src/vpn_task.rs | 13 +- apps/gpservice/src/vpn_task/non_tunnel.rs | 11 +- apps/gpservice/src/vpn_task/preparation.rs | 19 +- apps/gpservice/src/vpn_task/runtime.rs | 37 +- apps/gpservice/src/vpn_task/script_tun.rs | 270 ++++++----- .../src/vpn_task/script_tun/tests.rs | 63 ++- .../gpservice/src/vpn_task/script_tun/unix.rs | 44 ++ .../src/vpn_task/script_tun/windows.rs | 69 +++ apps/gpservice/src/windows_patches.rs | 159 ++++++ .../src/windows_service/admission.rs | 92 ++++ apps/gpservice/src/windows_service/logging.rs | 72 +++ apps/gpservice/src/windows_service/mod.rs | 159 ++++++ apps/gpservice/src/ws_connection.rs | 48 ++ apps/gpservice/src/ws_server.rs | 16 + changelog.md | 22 + crates/auth/Cargo.toml | 18 +- crates/auth/src/callback.rs | 69 +-- crates/auth/src/callback/protocol.rs | 73 +++ crates/auth/src/callback/windows.rs | 170 +++++++ crates/auth/src/lib.rs | 1 + crates/auth/src/webview.rs | 7 +- crates/auth/src/webview/auth_messenger.rs | 4 +- crates/auth/src/webview/recovery.rs | 3 +- crates/auth/src/webview/tls.rs | 4 + crates/auth/src/webview/webview_auth.rs | 68 ++- crates/auth/src/webview/windows.rs | 380 +++++++++++++++ crates/auth/src/webview/windows/controls.rs | 391 +++++++++++++++ crates/auth/src/webview/windows/tls.rs | 128 +++++ crates/browser-launcher/Cargo.toml | 13 +- crates/browser-launcher/src/lib.rs | 7 +- .../browser-launcher/src/platform/windows.rs | 35 ++ crates/common/build.rs | 15 +- crates/common/src/binary_paths.rs | 2 +- crates/common/src/constants.rs | 1 - crates/common/src/lib.rs | 1 + crates/common/src/paths.rs | 32 ++ crates/gp-xml/Cargo.toml | 11 + crates/gp-xml/src/lib.rs | 172 +++++++ crates/gpapi/Cargo.toml | 41 +- crates/gpapi/README.md | 16 + crates/gpapi/src/device_anchor/mod.rs | 18 +- crates/gpapi/src/error/server_tls.rs | 12 +- crates/gpapi/src/gateway/login.rs | 5 +- crates/gpapi/src/gateway/session.rs | 15 +- crates/gpapi/src/gui.rs | 46 +- crates/gpapi/src/hip.rs | 24 + crates/gpapi/src/lib.rs | 3 + crates/gpapi/src/logger.rs | 14 + crates/gpapi/src/logger/windows.rs | 98 ++++ crates/gpapi/src/os_profile/desktop/mod.rs | 9 +- crates/gpapi/src/os_profile/desktop/tests.rs | 87 +++- .../gpapi/src/os_profile/desktop/windows.rs | 85 +++- crates/gpapi/src/os_profile/profile.rs | 3 +- crates/gpapi/src/os_profile/tests.rs | 12 +- crates/gpapi/src/portal/config.rs | 14 +- crates/gpapi/src/portal/prelogin.rs | 6 +- crates/gpapi/src/process/auth_launcher.rs | 156 +++++- crates/gpapi/src/process/desktop_child.rs | 22 +- crates/gpapi/src/process/desktop_launcher.rs | 6 +- .../gpapi/src/process/gui_helper_launcher.rs | 1 + crates/gpapi/src/process/gui_launcher.rs | 72 ++- crates/gpapi/src/process/mod.rs | 25 +- .../gpapi/src/process/rendering_recovery.rs | 104 +++- .../gpapi/src/process/windows/collection.rs | 42 ++ .../src/process/windows/command_runner.rs | 198 ++++++++ .../src/process/windows/command_traits.rs | 12 + .../gpapi/src/process/windows/user_process.rs | 309 ++++++++++++ crates/gpapi/src/service/request.rs | 2 + .../gpapi/src/service/transport/credential.rs | 37 +- crates/gpapi/src/service/transport/message.rs | 2 + crates/gpapi/src/service/transport/mod.rs | 2 + .../gpapi/src/session/desktop/network/mod.rs | 6 + .../src/session/desktop/network/native.rs | 1 + .../src/session/desktop/network/windows.rs | 148 ++++++ crates/gpapi/src/session/transport/binding.rs | 2 +- crates/gpapi/src/session/transport/mod.rs | 1 + .../gpapi/src/utils/certificate/native_key.rs | 5 + crates/gpapi/src/utils/lock_file.rs | 4 +- crates/gpapi/src/utils/mod.rs | 42 +- crates/gpapi/src/utils/request.rs | 2 + crates/gpapi/src/utils/response_log.rs | 59 +++ crates/gpapi/src/utils/shutdown_signal.rs | 3 + crates/gpapi/src/windows.rs | 176 +++++++ crates/gpapi/src/windows/pipes.rs | 202 ++++++++ .../gpapi/tests/fixtures/portal-response.xml | 23 + crates/gpapi/tests/identity_encoding.rs | 19 +- crates/gpapi/tests/response_logging.rs | 123 +++++ crates/gpapi/tests/windows_identity.rs | 87 ++++ crates/gphip/Cargo.toml | 8 +- crates/gphip/examples/windows_preview.rs | 12 + crates/gphip/src/domain_macos.rs | 53 ++ crates/gphip/src/domain_unix.rs | 120 +++++ crates/gphip/src/lib.rs | 384 +++++++++++++-- crates/gphip/src/windows.rs | 96 ++++ crates/gphip/src/windows_report.rs | 323 +++++++++++++ crates/gphip/templates/hip_report.xml | 106 +--- crates/gphip/templates/windows_emulation.xml | 77 +++ crates/gpvpnc/Cargo.toml | 18 +- crates/gpvpnc/src/lib.rs | 5 + crates/gpvpnc/src/windows/configuration.rs | 249 ++++++++++ crates/gpvpnc/src/windows/dns-policy.ps1 | 18 + crates/gpvpnc/src/windows/dns.rs | 178 +++++++ crates/gpvpnc/src/windows/ip_helper.rs | 317 ++++++++++++ crates/gpvpnc/src/windows/mod.rs | 64 +++ crates/gpvpnc/src/windows/recovery.rs | 70 +++ crates/gpvpnc/tests/windows_network.rs | 454 ++++++++++++++++++ crates/openconnect/Cargo.toml | 4 + crates/openconnect/build.rs | 7 + crates/openconnect/build/windows.rs | 31 ++ crates/openconnect/deps/openconnect | 2 +- crates/openconnect/src/ffi/gateway.rs | 16 +- crates/openconnect/src/ffi/mod.rs | 69 ++- crates/openconnect/src/ffi/vpn.c | 107 +++-- crates/openconnect/src/ffi/vpn.h | 28 +- crates/openconnect/src/vpn.rs | 71 ++- .../openconnect/tests/windows_packet_pipe.c | 169 +++++++ flake.nix | 2 - nix/gui-package.nix | 4 +- packaging/apk/APKBUILD.in | 2 - .../globalprotect-openconnect-git/PKGBUILD | 2 +- packaging/bsd/freebsd/MANIFEST.in | 4 - packaging/deb/control.in | 2 - packaging/pkgbuild/PKGBUILD.in | 2 +- .../rpm/globalprotect-openconnect.spec.in | 6 - packaging/windows/README.md | 99 ++++ packaging/windows/installer.nsi | 127 +++++ packaging/windows/licenses/file-rotate.txt | 21 + packaging/windows/machine-install.ps1 | 437 +++++++++++++++++ packaging/windows/sidebar.bmp | Bin 0 -> 154542 bytes scripts/build-openconnect-windows.ps1 | 71 +++ scripts/build-openconnect-windows.sh | 30 ++ .../generate-windows-installer-artwork.ps1 | 33 ++ scripts/install-windows.ps1 | 6 + scripts/sign-windows.ps1 | 24 + scripts/test-openconnect-windows.ps1 | 7 + scripts/test-openconnect-windows.sh | 17 + scripts/test-private-desktop.sh | 4 +- scripts/test-windows-installer.ps1 | 21 +- scripts/test-windows-signature.ps1 | 14 + scripts/tests/test_windows_update_feed.py | 1 + scripts/tests/windows-webview-resize.ps1 | 91 ++++ scripts/tests/windows-webview-server.py | 76 +++ scripts/tests/windows-webview.ps1 | 193 ++++++++ scripts/uninstall-windows.ps1 | 5 + scripts/windows-update-feed.py | 1 + 172 files changed, 9629 insertions(+), 1171 deletions(-) create mode 100644 apps/gpauth/icons/windows/icon.ico create mode 100644 apps/gpauth/tauri.windows.conf.json create mode 100644 apps/gpauth/tests/windows_callback.rs create mode 100644 apps/gpservice/src/cli/windows.rs create mode 100644 apps/gpservice/src/gui_installation.rs create mode 100644 apps/gpservice/src/hip_source/unix.rs create mode 100644 apps/gpservice/src/hip_source/windows.rs create mode 100644 apps/gpservice/src/vpn_script/windows.rs create mode 100644 apps/gpservice/src/vpn_task/script_tun/unix.rs create mode 100644 apps/gpservice/src/vpn_task/script_tun/windows.rs create mode 100644 apps/gpservice/src/windows_patches.rs create mode 100644 apps/gpservice/src/windows_service/admission.rs create mode 100644 apps/gpservice/src/windows_service/logging.rs create mode 100644 apps/gpservice/src/windows_service/mod.rs create mode 100644 crates/auth/src/callback/protocol.rs create mode 100644 crates/auth/src/callback/windows.rs create mode 100644 crates/auth/src/webview/windows.rs create mode 100644 crates/auth/src/webview/windows/controls.rs create mode 100644 crates/auth/src/webview/windows/tls.rs create mode 100644 crates/browser-launcher/src/platform/windows.rs create mode 100644 crates/common/src/paths.rs create mode 100644 crates/gp-xml/Cargo.toml create mode 100644 crates/gp-xml/src/lib.rs create mode 100644 crates/gpapi/README.md create mode 100644 crates/gpapi/src/logger/windows.rs create mode 100644 crates/gpapi/src/process/windows/collection.rs create mode 100644 crates/gpapi/src/process/windows/command_runner.rs create mode 100644 crates/gpapi/src/process/windows/command_traits.rs create mode 100644 crates/gpapi/src/process/windows/user_process.rs create mode 100644 crates/gpapi/src/session/desktop/network/windows.rs create mode 100644 crates/gpapi/src/utils/response_log.rs create mode 100644 crates/gpapi/src/windows.rs create mode 100644 crates/gpapi/src/windows/pipes.rs create mode 100644 crates/gpapi/tests/fixtures/portal-response.xml create mode 100644 crates/gpapi/tests/response_logging.rs create mode 100644 crates/gpapi/tests/windows_identity.rs create mode 100644 crates/gphip/examples/windows_preview.rs create mode 100644 crates/gphip/src/domain_macos.rs create mode 100644 crates/gphip/src/domain_unix.rs create mode 100644 crates/gphip/src/windows.rs create mode 100644 crates/gphip/src/windows_report.rs create mode 100644 crates/gphip/templates/windows_emulation.xml create mode 100644 crates/gpvpnc/src/windows/configuration.rs create mode 100644 crates/gpvpnc/src/windows/dns-policy.ps1 create mode 100644 crates/gpvpnc/src/windows/dns.rs create mode 100644 crates/gpvpnc/src/windows/ip_helper.rs create mode 100644 crates/gpvpnc/src/windows/mod.rs create mode 100644 crates/gpvpnc/src/windows/recovery.rs create mode 100644 crates/gpvpnc/tests/windows_network.rs create mode 100644 crates/openconnect/build/windows.rs create mode 100644 crates/openconnect/tests/windows_packet_pipe.c create mode 100644 packaging/windows/README.md create mode 100644 packaging/windows/installer.nsi create mode 100644 packaging/windows/licenses/file-rotate.txt create mode 100644 packaging/windows/machine-install.ps1 create mode 100644 packaging/windows/sidebar.bmp create mode 100644 scripts/build-openconnect-windows.ps1 create mode 100644 scripts/build-openconnect-windows.sh create mode 100644 scripts/generate-windows-installer-artwork.ps1 create mode 100644 scripts/install-windows.ps1 create mode 100644 scripts/sign-windows.ps1 create mode 100644 scripts/test-openconnect-windows.ps1 create mode 100644 scripts/test-openconnect-windows.sh create mode 100644 scripts/test-windows-signature.ps1 create mode 100644 scripts/tests/windows-webview-resize.ps1 create mode 100644 scripts/tests/windows-webview-server.py create mode 100644 scripts/tests/windows-webview.ps1 create mode 100644 scripts/uninstall-windows.ps1 diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index b632bc1..fb51363 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -163,7 +163,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 + cargo test --workspace --locked --features gpapi/openssl-tests # Exercise only the paths that require an actual root process. sudo -E env PATH="$PATH" PKEXEC_UID="$(id -u)" cargo test --locked -p gpapi \ diff --git a/Cargo.lock b/Cargo.lock index 9a65147..4135727 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -292,11 +292,13 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "auth" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "block2", "browser-launcher", + "common", + "dunce", "gpapi", "gtk", "html-escape", @@ -307,6 +309,7 @@ dependencies = [ "objc2-security", "objc2-web-kit", "regex", + "serde_json", "tauri", "tempfile", "tiny_http", @@ -316,6 +319,10 @@ dependencies = [ "uuid", "uzers", "webkit2gtk", + "webview2-com", + "windows", + "windows-sys 0.61.2", + "winreg 0.55.0", ] [[package]] @@ -547,13 +554,14 @@ dependencies = [ [[package]] name = "browser-launcher" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "log", "open", "webbrowser", "which", + "winreg 0.55.0", ] [[package]] @@ -911,7 +919,7 @@ dependencies = [ [[package]] name = "common" -version = "3.4.0" +version = "3.5.0" dependencies = [ "tempfile", ] @@ -1551,7 +1559,7 @@ dependencies = [ "rustc_version", "toml 1.1.8+spec-1.1.0", "vswhom", - "winreg", + "winreg 0.56.0", ] [[package]] @@ -1655,6 +1663,16 @@ 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" @@ -2113,9 +2131,17 @@ dependencies = [ "system-deps", ] +[[package]] +name = "gp-xml" +version = "3.5.0" +dependencies = [ + "url", + "xmltree", +] + [[package]] name = "gpapi" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "base64 0.23.1", @@ -2129,7 +2155,9 @@ dependencies = [ "directories", "dns-lookup", "env_logger", + "file-rotate", "getrandom 0.4.3", + "gp-xml", "gtk", "humantime", "libloading 0.9.0", @@ -2169,6 +2197,7 @@ dependencies = [ "uuid", "uzers", "whoami", + "windows-sys 0.61.2", "x509-cert", "xmltree", "zeroize", @@ -2176,7 +2205,7 @@ dependencies = [ [[package]] name = "gpauth" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "auth", @@ -2184,7 +2213,6 @@ dependencies = [ "common", "compile-time", "gpapi", - "home", "log", "serde_json", "tauri", @@ -2195,7 +2223,7 @@ dependencies = [ [[package]] name = "gpclient" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "clap", @@ -2226,7 +2254,7 @@ dependencies = [ [[package]] name = "gpgui-helper" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "clap", @@ -2247,24 +2275,26 @@ dependencies = [ [[package]] name = "gphip" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "askama", "chrono", "gpapi", + "log", "netdev", "serde", "serde_json", "serde_urlencoded", "uuid", "uzers", + "windows", "xmltree", ] [[package]] name = "gpservice" -version = "3.4.0" +version = "3.5.0" dependencies = [ "anyhow", "axum", @@ -2273,6 +2303,7 @@ dependencies = [ "common", "compile-time", "env_logger", + "file-rotate", "futures", "getrandom 0.4.3", "gpapi", @@ -2293,13 +2324,15 @@ dependencies = [ "tokio-tungstenite 0.30.0", "tokio-util", "uuid", + "windows-service", + "windows-sys 0.61.2", "xz2", "zeroize", ] [[package]] name = "gptunnel" -version = "3.4.0" +version = "3.5.0" dependencies = [ "gpapi", "log", @@ -2311,9 +2344,17 @@ dependencies = [ [[package]] name = "gpvpnc" -version = "3.4.0" +version = "3.5.0" dependencies = [ + "base64 0.23.1", + "ipnet", "log", + "serde", + "serde_json", + "tempfile", + "uuid", + "windows-sys 0.61.2", + "winreg 0.56.0", ] [[package]] @@ -2431,15 +2472,6 @@ 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" @@ -2815,6 +2847,9 @@ name = "ipnet" version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +dependencies = [ + "serde", +] [[package]] name = "is-docker" @@ -3825,16 +3860,18 @@ dependencies = [ [[package]] name = "openconnect" -version = "3.4.0" +version = "3.5.0" dependencies = [ "autotools", "cc", "fs_extra", + "gp-xml", "is_executable", "libc", "log", "pkg-config", "tempfile", + "windows-sys 0.61.2", ] [[package]] @@ -6730,6 +6767,12 @@ 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" @@ -6880,6 +6923,17 @@ 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" @@ -6907,6 +6961,15 @@ 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" @@ -7073,6 +7136,16 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index 2d2128e..21f2664 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ members = [ [workspace.package] rust-version = "1.91" -version = "3.4.0" +version = "3.5.0" authors = ["Kevin Yue "] homepage = "https://github.com/yuezk/GlobalProtect-openconnect" edition = "2024" diff --git a/README.md b/README.md index 9ff76ab..b4f49d4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # GlobalProtect-openconnect -A GlobalProtect VPN client built on OpenConnect. It provides command-line tools (`gpclient`) and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD. +A GlobalProtect VPN client built on OpenConnect. GP Connect runs on Windows, macOS, Linux, FreeBSD, and OpenBSD. Command-line tools (`gpclient`) are available on macOS, Linux, and BSD. > **Disclaimer**: GP Connect is an independent third-party client for GlobalProtect VPN networks. It is not affiliated with or endorsed by Palo Alto Networks, Inc. @@ -21,6 +21,7 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools - [Command-Line Interface](#command-line-interface) - [Graphical User Interface](#graphical-user-interface) - [Installation](#installation) + - [Windows](#windows) - [macOS](#macos) - [Debian / Ubuntu](#debian--ubuntu) - [Arch Linux / Manjaro](#arch-linux--manjaro) @@ -40,8 +41,8 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools ## Features -- **Multi-Platform** – macOS (Apple silicon), Linux, FreeBSD, and OpenBSD -- **Dual Interfaces** – Fast terminal CLI (`gpclient`) and desktop GUI (**GP Connect**) +- **Multi-Platform** – Windows (x64 and ARM64), macOS (Apple silicon), Linux, FreeBSD, and OpenBSD +- **Dual Interfaces** – Desktop GUI (**GP Connect**) and terminal CLI (`gpclient`, on macOS, Linux, and BSD) - **Native Shell on Linux** – Ultra-low-memory native desktop GUI alongside the webview interface - **Flexible Routing** – Full System VPN tunnel or local SOCKS5 proxy mode - **Modern Authentication** – SAML / SSO, MFA, FIDO2 (YubiKey), client certificates, and external browser login @@ -53,7 +54,7 @@ A GlobalProtect VPN client built on OpenConnect. It provides command-line tools ### Command-Line Interface -The open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation: +On macOS, Linux, and BSD, the open-source `gpclient` CLI handles authentication, connection lifecycle, and HIP generation: ```bash # Connect to a portal server @@ -79,6 +80,7 @@ Run `gpclient --help` or `gpclient --help` to view all available comma ### Graphical User Interface +- **Windows**: Open **GP Connect** from the Start menu. - **macOS**: Open **GP Connect** from Applications. - **Linux / BSD**: Launch GP Connect from your application menu or run: ```bash @@ -90,6 +92,19 @@ Run `gpclient --help` or `gpclient --help` to view all available comma ## Installation +### Windows + +Download the matching EXE installer from [GitHub Releases](https://github.com/yuezk/GlobalProtect-openconnect/releases/latest): + +- **x64**: Windows 10 version 2004 (build 19041) or later. +- **ARM64**: Windows 11. + +Run the installer and confirm installation. It installs GP Connect and its background VPN service for all users; administrator access is required. Open GP Connect from the Start menu as your normal user. + +The installer and application executables are signed by **Tangramly, LLC**. Embedded sign-in uses Microsoft Edge WebView2 Runtime. You can also use your system browser from Settings. + +GP Connect checks for updates in the app. Uninstall it from Windows Settings; your app settings are kept. The Windows package contains the desktop app and service, without the `gpclient` command-line tool. + ### macOS Requires Apple silicon and macOS 13+. Includes both GP Connect and the `gpclient` CLI. diff --git a/apps/gpauth/Cargo.toml b/apps/gpauth/Cargo.toml index f92edb5..1a11b4c 100644 --- a/apps/gpauth/Cargo.toml +++ b/apps/gpauth/Cargo.toml @@ -23,8 +23,6 @@ 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 } diff --git a/apps/gpauth/build.rs b/apps/gpauth/build.rs index 6b1dc12..a9849cd 100644 --- a/apps/gpauth/build.rs +++ b/apps/gpauth/build.rs @@ -16,6 +16,9 @@ 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() } diff --git a/apps/gpauth/icons/windows/icon.ico b/apps/gpauth/icons/windows/icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..7724e9f8f850b1c6363c175e884b0aaa7846b96b GIT binary patch literal 47963 zcmbrlXH=70)Gqo4Fcbr*hy+4Y5L5&LYCtIg*@}n~-4-mAKu|zJ6Qx5UD9ENNDj-d_ z3M$e>>5$L@NE1;Bz4sD&O}Q($zj5vv}ygusWwCTITo8$5GI+#vu5k8+C~8wlc6HTlc%vNvpo%KJ+3 z`U~1T$7?pSt}*?tDIv?bEC0WnV?@e}v)L({NA}IGdluaBO$*g=`jx$4(Yv|HncM$j zv#Pdu^0}tZxz208rL+m$WP%Q9+PH5*kMzXeNVmw`x%wSj zx(hSRB(J=p7_JvENDbaCG1D-z27{{p{Lw3ws)R4@Hwk5;=jLrJHMSAHES@s*W4}CHJK%gEH+1 z1+E@MF-O}@EDV>O(^+lxoGoUHT1}==_^gUcH(LV7N+N1o0_NVI?i?R9>D_n{I*(Cb z#HaZ7?T-ox)AF59Ovv<=UH$USd(`uX$;xKC-sp1QV$0--C6hPGPpkQLhRZ|;HKO%t z47~}L@-g+@XD|U zzt9kBywc=fKXlQ3b(b*F0*sSYXJE_=bu*nn^-jI|s?9E+;pDys!qwHetD-4&zvtGU z*sSgrRd=lvWBBh#cHNt|^M~rMkbL*BiKUrww+fZYuPWB0@m||d{d(E((I;(nec1WKoVm9i!$&nEBc)MQ$8h-W z!Z`Q9sKflmuUYGioNh(uU2Vkyx{0QE^6hU zNee2}M^ias4R(ojj&{9a<-v{)=Lk=c(T4eN?Q(KEH@sn`zuGx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=+5iG`amCjy!^y7M7e@fBhCsd|> z08)%eL=D&dHVTDw}UrBGdqW)wj-AQ;13b-o-b0H zUC(>db=+4x$9@?>Pi>boEhkF+WN*(DgC|dWtuW1nk6#=Ee@p-e;Tqsux+-WuRZv`J zfipp4tsu0j4C1C}Oa^gfaAEcXm-XVr6SAs3r7FtfKn6wZi}6B}xHsM@_{k1m>chAB zdi=dWP(tGXTNF*FAb+_8Jhv)Dx1dKd!3s zBR~cZqP>WlZ5^lWK7jvVlzx)1>Oyg8tA}O1=fCAS{*54LylOWAPi=)$8BTiW>6xtZ zH0Y^j@{ST8PJ7aI+Mm1uo-qN8T6;kHlR;b=gkFQ9X23n27StM$0FVN-2%=SJ62hs| zmrD7`nTHis2U3vcR8_eQwZVgEong{3P9q{YbSUYE2!1@(1;~BWB?2*&6L9{P>v*q+ zVX){s-YfRj#_Jo^JCzpTH2}P=!uvKi-C{@;0DYpo7bkr`(088pW8jYo;AoJ6U$0Qq z48oE{MRfpf0xvie389#CS``As?zXyv7mm)YLet_jt;)N{(YsFXu~q4Eiwv9Ah%rq;q7B!~$Yy*C|#9 zF(I@o1Rw<;Nx>CA#-t#goFoP!Omb)=9-Ni*;w*kBDRh=GWj2aHXC*Gthmv@K3WBN< z>zG=Ci&TTa?+ieL^8F3?PGq8ofwu^ob&KM!v#rI|#kUp_3E&u=k07*qoM6N<$g2v5c{{R30 literal 0 HcmV?d00001 diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index 104b0d1..c5dc36b 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -1,8 +1,8 @@ -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] use auth::forward_auth_callback; use auth::{BrowserAuthenticator, auth_prelogin}; use clap::Parser; -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] use clap::Subcommand; #[cfg(feature = "webview-auth")] use gpapi::auth::AuthWindowTheme; @@ -49,7 +49,7 @@ See 'gpauth -h' for more information. " )] struct Cli { - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[command(subcommand)] command: Option, @@ -134,7 +134,7 @@ struct Cli { verbose: InfoLevelVerbosity, } -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[derive(Subcommand)] enum CliCommand { #[command(hide = true)] @@ -272,7 +272,7 @@ fn init_logger(cli: &Cli) { pub async fn run() { let cli = Cli::parse(); - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] if let Some(CliCommand::AuthCallback { callback }) = &cli.command { if let Err(err) = forward_auth_callback(callback).await { eprintln!("Failed to forward authentication callback: {err}"); @@ -382,7 +382,7 @@ mod tests { } #[test] - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] fn callback_arguments_parse_separately() { let cli = Cli::try_parse_from([ "gpauth", diff --git a/apps/gpauth/tauri.windows.conf.json b/apps/gpauth/tauri.windows.conf.json new file mode 100644 index 0000000..8ddc650 --- /dev/null +++ b/apps/gpauth/tauri.windows.conf.json @@ -0,0 +1,5 @@ +{ + "bundle": { + "icon": ["icons/windows/icon.ico"] + } +} diff --git a/apps/gpauth/tests/windows_callback.rs b/apps/gpauth/tests/windows_callback.rs new file mode 100644 index 0000000..2c152c6 --- /dev/null +++ b/apps/gpauth/tests/windows_callback.rs @@ -0,0 +1,29 @@ +#![cfg(windows)] + +use auth::AuthCallbackReceiver; +use std::{process::Stdio, time::Duration}; + +#[tokio::test] +async fn callback_command_forwards_between_processes() { + let receiver = AuthCallbackReceiver::bind().unwrap(); + let child = tokio::process::Command::new(env!("CARGO_BIN_EXE_gpauth")) + .args([ + "auth-callback", + "globalprotectcallback:cas-as=1&un=windows-fixture&token=callback-command-test", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let (data, output) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(receiver.receive(), child.wait_with_output()) + }) + .await + .expect("callback executable did not complete"); + let output = output.unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let data = data.unwrap(); + assert_eq!(data.username(), "windows-fixture"); + assert_eq!(data.token(), Some("callback-command-test")); +} diff --git a/apps/gpclient/src/connect/flow_tests.rs b/apps/gpclient/src/connect/flow_tests.rs index 2852e5a..b3253f3 100644 --- a/apps/gpclient/src/connect/flow_tests.rs +++ b/apps/gpclient/src/connect/flow_tests.rs @@ -174,15 +174,21 @@ async fn unreachable_gateway_keeps_cached_cookie() { #[tokio::test] async fn gateway_closing_without_response_keeps_cached_cookie() { - closed_connection_keeps_cached_cookie(false).await; + closed_connection_keeps_cached_cookie(false, false).await; } #[tokio::test] async fn portal_closing_without_response_keeps_cached_cookie() { - closed_connection_keeps_cached_cookie(true).await; + closed_connection_keeps_cached_cookie(true, false).await; } -async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) { +#[tokio::test] +async fn partial_responses_keep_cached_cookie() { + closed_connection_keeps_cached_cookie(false, true).await; + closed_connection_keeps_cached_cookie(true, true).await; +} + +async fn closed_connection_keeps_cached_cookie(portal_discovery: bool, partial_body: 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 { @@ -203,8 +209,14 @@ async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) { .unwrap(); } let (mut stream, _) = listener.accept().await.unwrap(); - // Read the complete request, then close without sending HTTP headers. - read_request(&mut stream).await + let request = read_request(&mut stream).await; + if partial_body { + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n") + .await + .unwrap(); + } + request }) .await .expect("Connection-closing fixture timed out") @@ -248,7 +260,11 @@ async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) { let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else { panic!("Expected a network error, got {error:?}"); }; - assert!(network.is_request()); + if partial_body { + assert!(network.is_body() || network.is_decode()); + } else { + assert!(network.is_request()); + } assert!(!network.is_connect()); assert!(!network.is_timeout()); assert!(cache.exists(), "an unanswered request must not delete the cookie cache"); diff --git a/apps/gpclient/src/connect/internal.rs b/apps/gpclient/src/connect/internal.rs index 8e0e9a0..f928d0c 100644 --- a/apps/gpclient/src/connect/internal.rs +++ b/apps/gpclient/src/connect/internal.rs @@ -128,15 +128,18 @@ impl ConnectHandler<'_> { produce_report: Arc::new(move |request, control| { control.check()?; if matches!(source.as_ref(), openconnect::HipSource::Disabled) { - return gphip::generate_identity_report(&gphip::ReportInput { - profile: profile.clone(), - context: gphip::ReportContext::Connected { - cookie: request.cookie.clone(), - client_ip: request.client_ip.clone(), - client_ipv6: request.client_ipv6.clone(), - md5: request.md5.clone(), + return gphip::generate_identity_report( + &gphip::ReportInput { + profile: profile.clone(), + context: gphip::ReportContext::Connected { + cookie: request.cookie.clone(), + client_ip: request.client_ip.clone(), + client_ipv6: request.client_ipv6.clone(), + md5: request.md5.clone(), + }, }, - }) + control, + ) .map_err(std::io::Error::other); } source.collect( diff --git a/apps/gpservice/Cargo.toml b/apps/gpservice/Cargo.toml index 4832808..6a9c5db 100644 --- a/apps/gpservice/Cargo.toml +++ b/apps/gpservice/Cargo.toml @@ -30,14 +30,24 @@ 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(target_os = "macos")'.dependencies] +[target.'cfg(any(target_os = "macos", windows))'.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"] } diff --git a/apps/gpservice/src/cli.rs b/apps/gpservice/src/cli.rs index a5573c9..551d28d 100644 --- a/apps/gpservice/src/cli.rs +++ b/apps/gpservice/src/cli.rs @@ -6,7 +6,7 @@ use std::time::Duration; use anyhow::{Context, bail}; use clap::Parser; -use common::constants::GP_SERVICE_LOCK_FILE; +use common::paths::service_lock_file; use gpapi::clap::InfoLevelVerbosity; use gpapi::logger; #[cfg(debug_assertions)] @@ -25,14 +25,7 @@ use crate::{ request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer, }; -const VERSION: &str = concat!( - env!("CARGO_PKG_VERSION"), - " (", - env!("GPSERVICE_GIT_COMMIT"), - " ", - compile_time::date_str!(), - ")" -); +use crate::VERSION; #[cfg(target_os = "macos")] struct RedactingMacosLogger { @@ -271,7 +264,7 @@ impl Cli { return Ok(dev_service_lock_file_path(socket)); } - Ok(PathBuf::from(GP_SERVICE_LOCK_FILE)) + Ok(service_lock_file()) } fn init_logger(&self) -> Arc { diff --git a/apps/gpservice/src/cli/windows.rs b/apps/gpservice/src/cli/windows.rs new file mode 100644 index 0000000..ae150dd --- /dev/null +++ b/apps/gpservice/src/cli/windows.rs @@ -0,0 +1,12 @@ +use clap::Parser; +use gpapi::clap::InfoLevelVerbosity; +#[derive(Parser)] +#[command(version = crate::VERSION)] +struct Cli { + #[command(flatten)] + verbose: InfoLevelVerbosity, +} +pub fn run() -> anyhow::Result<()> { + let cli = Cli::parse(); + crate::windows_service::dispatch(cli.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info)) +} diff --git a/apps/gpservice/src/desktop_client.rs b/apps/gpservice/src/desktop_client.rs index 47b357c..e9a85ea 100644 --- a/apps/gpservice/src/desktop_client.rs +++ b/apps/gpservice/src/desktop_client.rs @@ -75,7 +75,7 @@ impl DesktopClient { loop { match self.read_control().await? { Some(DESKTOP_GUI_INSTALLER) => { - self.write_all(&[u8::from(crate::request_dispatcher::gui_installer().is_some())]).await?; + self.write_all(&[u8::from(crate::gui_installation::installer().is_some())]).await?; } Some(DESKTOP_SWITCH_BEGIN) => { ensure!(pending.is_none(), "A GUI switch is already pending"); @@ -299,10 +299,7 @@ mod tests { let mut reader = reader; let mut capability = [0]; reader.read_exact(&mut capability).unwrap(); - assert_eq!( - capability[0], - u8::from(crate::request_dispatcher::gui_installer().is_some()) - ); + assert_eq!(capability[0], u8::from(crate::gui_installation::installer().is_some())); reader }) .await diff --git a/apps/gpservice/src/device_anchor.rs b/apps/gpservice/src/device_anchor.rs index ed907aa..2da5bec 100644 --- a/apps/gpservice/src/device_anchor.rs +++ b/apps/gpservice/src/device_anchor.rs @@ -366,7 +366,7 @@ mod tests { r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"# ); - for source in [0, 4] { + for source in [0, u8::MAX] { let json = serde_json::json!({ "version": 1, "anchor": { diff --git a/apps/gpservice/src/gui_installation.rs b/apps/gpservice/src/gui_installation.rs new file mode 100644 index 0000000..eb327d6 --- /dev/null +++ b/apps/gpservice/src/gui_installation.rs @@ -0,0 +1,359 @@ +use gpapi::utils::checksum::verify_checksum; +use std::{ + fs::{self, File, OpenOptions, Permissions}, + io::{BufReader, Read, Write}, + os::unix::fs::{OpenOptionsExt, PermissionsExt}, + path::Path, +}; +use tar::Archive; +use tempfile::NamedTempFile; +use xz2::read::XzDecoder; +const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024; +const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024; +const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024; +#[derive(Debug)] +pub(crate) enum InstallError { + Checksum(anyhow::Error), + Install(anyhow::Error), +} + +pub(crate) fn installer() -> Option { + std::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 { + 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( + archive: &mut Archive, + dir: &Path, + binary_name: &str, +) -> Result { + 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 { + 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"))); + } + } +} diff --git a/apps/gpservice/src/hip_preview.rs b/apps/gpservice/src/hip_preview.rs index 3f98408..85f9960 100644 --- a/apps/gpservice/src/hip_preview.rs +++ b/apps/gpservice/src/hip_preview.rs @@ -85,7 +85,7 @@ impl HipPreviews { }) .await; let result = match generated { - Ok(Ok(xml)) => preview_result(®istry, session_id, xml), + Ok(Ok(report)) => preview_result(®istry, session_id, report), Ok(Err(error)) => { log::warn!("HIP preview failed: {error:#}"); ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed") @@ -132,17 +132,20 @@ impl HipPreviews { } } -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, - }) - }); +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, + }) + }); result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable")) } @@ -152,7 +155,7 @@ fn generate( desktop_uid: Option, identity: HostIdentity, cancellation: CancellationToken, -) -> anyhow::Result { +) -> anyhow::Result { ensure!(request.client_version.len() <= 64, "Invalid HIP client version"); ensure!( request.host_id.as_ref().is_none_or(|id| id.len() <= 256), @@ -188,7 +191,15 @@ fn generate( }; let xml = match &request.source { HipSource::Disabled => bail!("HIP is disabled"), - HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?, + HipSource::Generated => { + return gphip::generate_report_details( + &gphip::ReportInput { + profile, + context: gphip::ReportContext::Preview, + }, + &check, + ); + } HipSource::Edited { .. } => { let xml = edited_report.context("Edited HIP report is unavailable")?; crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)? @@ -204,7 +215,10 @@ fn generate( } }; check()?; - Ok(xml) + Ok(gpapi::hip::HipReport { + xml, + windows_updates: None, + }) } #[cfg(test)] diff --git a/apps/gpservice/src/hip_source.rs b/apps/gpservice/src/hip_source.rs index a0afb9b..8a35dc4 100644 --- a/apps/gpservice/src/hip_source.rs +++ b/apps/gpservice/src/hip_source.rs @@ -1,4 +1,4 @@ -use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc}; +use std::{io, sync::Arc}; use anyhow::{Context, ensure}; use gpapi::{ @@ -6,7 +6,17 @@ use gpapi::{ os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder}, }; use gphip::{ReportContext, ReportInput}; -use openconnect::{HipRequest, HipScript, HipScriptEnvironment}; +use openconnect::HipRequest; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +use openconnect::HipScript; +#[cfg(unix)] +#[path = "hip_source/unix.rs"] +mod scripts; +#[cfg(windows)] +#[path = "hip_source/windows.rs"] +mod scripts; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +use scripts::script_environment; pub(crate) struct HipExecution { pub source: openconnect::HipSource, @@ -36,7 +46,7 @@ impl HipApproval { pub(crate) fn resolve( source: &HipSource, desktop_uid: Option, - brokered_macos: bool, + restricted_desktop: bool, edited_report: Option>, profile: Option, ) -> anyhow::Result { @@ -63,22 +73,11 @@ pub(crate) fn resolve( } HipSource::UserScript { path } => { approval = None; - 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) + ensure_custom_available(restricted_desktop)?; + scripts::user_script(path, desktop_uid)? } HipSource::ApprovedRootScript { approval_id } => { - ensure_custom_available(brokered_macos)?; + ensure_custom_available(restricted_desktop)?; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] { let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?; @@ -113,10 +112,10 @@ pub(crate) fn resolve( }) } -fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> { +fn ensure_custom_available(restricted_desktop: bool) -> anyhow::Result<()> { ensure!( - !cfg!(target_os = "macos") && !brokered_macos, - "Custom HIP scripts are unavailable on macOS" + !cfg!(target_os = "macos") && !restricted_desktop, + "Custom HIP scripts are unavailable on this platform" ); Ok(()) } @@ -149,27 +148,6 @@ pub(crate) fn generate( } } -pub(crate) fn script_environment(uid: u32) -> anyhow::Result { - 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, @@ -180,19 +158,22 @@ pub(crate) fn profile( control: &dyn gpapi::collection::CollectionControl, ) -> io::Result { let identity = gpapi::os_profile::desktop::identity_from_parts( - hostname.unwrap_or_else(|| identity.computer().into()), - host_id.unwrap_or_else(|| identity.host_id().into()), + hostname.as_deref().unwrap_or(identity.computer()).into(), + host_id.as_deref().unwrap_or(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, None, control) + gpapi::os_profile::desktop::collect_profile_with_control(builder, host_id.as_deref(), control) } fn generation_error(error: anyhow::Error) -> io::Error { @@ -257,6 +238,29 @@ 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()); diff --git a/apps/gpservice/src/hip_source/unix.rs b/apps/gpservice/src/hip_source/unix.rs new file mode 100644 index 0000000..bb23492 --- /dev/null +++ b/apps/gpservice/src/hip_source/unix.rs @@ -0,0 +1,37 @@ +use anyhow::{Context, ensure}; +use openconnect::{HipScript, HipScriptEnvironment}; +use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf}; +pub(super) fn user_script(path: &str, desktop_uid: Option) -> anyhow::Result { + 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 { + 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, + }) +} diff --git a/apps/gpservice/src/hip_source/windows.rs b/apps/gpservice/src/hip_source/windows.rs new file mode 100644 index 0000000..1b57525 --- /dev/null +++ b/apps/gpservice/src/hip_source/windows.rs @@ -0,0 +1,3 @@ +pub(super) fn user_script(_path: &str, _desktop_uid: Option) -> anyhow::Result { + anyhow::bail!("Custom HIP scripts are unavailable on Windows") +} diff --git a/apps/gpservice/src/main.rs b/apps/gpservice/src/main.rs index 5a86bde..afcdd59 100644 --- a/apps/gpservice/src/main.rs +++ b/apps/gpservice/src/main.rs @@ -1,11 +1,15 @@ +#[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(debug_assertions)] +#[cfg(all(debug_assertions, unix))] 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; @@ -13,14 +17,41 @@ 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 + } + } +} diff --git a/apps/gpservice/src/request_dispatcher.rs b/apps/gpservice/src/request_dispatcher.rs index 7043f10..5adaafb 100644 --- a/apps/gpservice/src/request_dispatcher.rs +++ b/apps/gpservice/src/request_dispatcher.rs @@ -1,27 +1,15 @@ -use std::{ - fs::{self, File, OpenOptions, Permissions}, - io::{BufReader, Read, Write}, - os::unix::fs::{OpenOptionsExt, PermissionsExt}, - path::Path, - sync::{Arc, atomic::AtomicBool}, -}; +use std::sync::{Arc, atomic::AtomicBool}; use gpapi::{ service::{ request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest}, transport::{ServiceErrorCode, ServiceResult}, }, - utils::{checksum::verify_checksum, redact::Redaction}, + utils::redact::Redaction, }; use log::{info, warn}; -use tar::Archive; -use tempfile::NamedTempFile; +#[cfg(unix)] 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, @@ -75,12 +63,17 @@ pub struct RequestDispatcher { lifecycle: crate::vpn_task::LifecycleHandle, gui_restart_requested: Arc, redaction: Arc, + #[cfg(unix)] install_lock: Mutex<()>, gui_management_enabled: bool, - externally_brokered: bool, + restricted_desktop: bool, } impl RequestDispatcher { + #[cfg(windows)] + pub(crate) fn patch_checks(&self) -> Arc { + self.lifecycle.patch_checks.clone() + } pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver { self.lifecycle.subscribe_tunnel() } @@ -89,15 +82,16 @@ impl RequestDispatcher { gui_restart_requested: Arc, redaction: Arc, gui_management_enabled: bool, - externally_brokered: bool, + restricted_desktop: bool, ) -> Self { Self { lifecycle, gui_restart_requested, redaction, + #[cfg(unix)] install_lock: Mutex::new(()), gui_management_enabled, - externally_brokered, + restricted_desktop, } } @@ -202,7 +196,7 @@ impl RequestDispatcher { edited_report, } => { let prepared = - crate::vpn_task::prepare_connection(*request, self.externally_brokered, preparation.cancellation()).await; + crate::vpn_task::prepare_connection(*request, self.restricted_desktop, preparation.cancellation()).await; return match prepared { Ok(connection) => preparation.commit(connection, desktop_uid, edited_report), Err(error) => { @@ -272,31 +266,34 @@ impl RequestDispatcher { | WsRequest::GetHipApprovalStatus { .. } | WsRequest::ReadHipPreviewChunk(_) | WsRequest::GetLastSubmittedHipReport - | WsRequest::SetTunnelStatisticsEnabled { .. } => { + | WsRequest::SetTunnelStatisticsEnabled { .. } + | WsRequest::SetWindowsPatchInterest { .. } + | WsRequest::RefreshWindowsPatches { .. } => { unreachable!("session-bound request was already dispatched") } } } fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> { - if !self.externally_brokered { + if !self.restricted_desktop { return Ok(()); } if request.args().vpnc_script().is_some() { - return Err("macOS does not support custom VPN scripts"); + return Err("Custom VPN scripts are unavailable on this platform"); } if matches!( request.args().hip_source(), gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. } ) { - return Err("macOS does not support custom HIP scripts"); + return Err("Custom HIP scripts are unavailable on this platform"); } if request.args().certificate().is_some() || request.args().sslkey().is_some() { - return Err("macOS client identity must be provided as protected data, not root-readable paths"); + return Err("Client identity must be provided as certificate data"); } Ok(()) } + #[cfg(unix)] async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult { if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") { return ServiceResult::rejected( @@ -308,14 +305,17 @@ impl RequestDispatcher { let path = request.path; let checksum = request.checksum; let target = request.variant.update_target(); - let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await; + let installed = tokio::task::spawn_blocking(move || { + crate::gui_installation::install(std::path::Path::new(&path), &checksum, &target) + }) + .await; match installed { Ok(Ok(())) => ServiceResult::Accepted, - Ok(Err(GuiInstallError::Checksum(err))) => { + Ok(Err(crate::gui_installation::InstallError::Checksum(err))) => { warn!("Failed to verify GUI update checksum: {err}"); ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed") } - Ok(Err(GuiInstallError::Install(err))) => { + Ok(Err(crate::gui_installation::InstallError::Install(err))) => { warn!("Failed to install GUI update: {err}"); ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed") } @@ -325,335 +325,20 @@ impl RequestDispatcher { } } } -} - -#[derive(Debug)] -enum GuiInstallError { - Checksum(anyhow::Error), - Install(anyhow::Error), -} - -pub(crate) fn gui_installer() -> Option { - 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}" - ))) - }; + #[cfg(windows)] + async fn update_gui(&self, _request: UpdateGuiRequest) -> ServiceResult { + ServiceResult::rejected( + ServiceErrorCode::InvalidRequest, + "Use the Windows installer to update GP Connect", + ) } - - 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 { - 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( - archive: &mut Archive, - dir: &Path, - binary_name: &str, -) -> Result { - 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 crate::vpn_task::test_connect_request as test_request; - use std::{io::Cursor, os::unix::fs::PermissionsExt}; - - use gpapi::{ - gateway::Gateway, - service::transport::{ServiceErrorCode, ServiceResult}, - }; - use tar::{Builder, EntryType, Header}; - use xz2::write::XzEncoder; - use super::*; - - fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec { - 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"); - } - + use crate::vpn_task::test_connect_request as test_request; + use gpapi::gateway::Gateway; #[tokio::test] async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() { let dispatcher = RequestDispatcher::new( @@ -700,7 +385,7 @@ mod tests { let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string())); assert_eq!( dispatcher.validate_connect_request(&custom), - Err("macOS does not support custom VPN scripts") + Err("Custom VPN scripts are unavailable on this platform") ); } @@ -709,32 +394,7 @@ mod tests { }); assert_eq!( dispatcher.validate_connect_request(&custom), - Err("macOS does not support custom HIP scripts") + Err("Custom HIP scripts are unavailable on this platform") ); } - #[test] - #[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"] - fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() { - let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap(); - let archive = compressed_gui_archive(&binary); - let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap(); - let temporary = tempfile::tempdir().unwrap(); - let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| temporary.path().to_owned()); - std::fs::create_dir_all(&output).unwrap(); - std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap(); - let target = output.join("gpclient/gpgui"); - for upgrade in [false, true] { - if upgrade { - std::fs::write(&target, b"old GUI").unwrap(); - } - install_gui_at(archive.path(), &checksum, &target).unwrap(); - assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1); - assert_eq!(std::fs::read(&target).unwrap(), binary); - let result = std::process::Command::new(&target).arg("--version").output().unwrap(); - assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); - assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION"))); - } - } } diff --git a/apps/gpservice/src/session_registry.rs b/apps/gpservice/src/session_registry.rs index 8169a64..33f493b 100644 --- a/apps/gpservice/src/session_registry.rs +++ b/apps/gpservice/src/session_registry.rs @@ -62,6 +62,8 @@ enum SessionStatus { } struct SessionRecord { + #[cfg(windows)] + windows_identity: Option>, non_tunnel: Option, closed_attachment: Option, secret: Zeroizing<[u8; 32]>, @@ -255,6 +257,8 @@ impl SessionRegistry { sessions.insert( credential.session_id(), SessionRecord { + #[cfg(windows)] + windows_identity: None, non_tunnel: None, closed_attachment: None, secret: Zeroizing::new(*credential.secret()), @@ -273,6 +277,38 @@ impl SessionRegistry { Ok(credential) } + #[cfg(windows)] + pub(crate) fn issue_windows( + &self, + product_version: &str, + identity: Arc, + ) -> Result, 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, 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 { diff --git a/apps/gpservice/src/vpn_script/mod.rs b/apps/gpservice/src/vpn_script/mod.rs index 5097dc8..c568015 100644 --- a/apps/gpservice/src/vpn_script/mod.rs +++ b/apps/gpservice/src/vpn_script/mod.rs @@ -1,6 +1,9 @@ #[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; @@ -8,7 +11,8 @@ mod platform; target_os = "linux", target_os = "freebsd", target_os = "openbsd", - target_os = "macos" + target_os = "macos", + windows )))] #[path = "default.rs"] mod platform; @@ -16,3 +20,5 @@ mod platform; mod selection; pub(crate) use platform::builder; +#[cfg(windows)] +pub(crate) use platform::recover_network; diff --git a/apps/gpservice/src/vpn_script/windows.rs b/apps/gpservice/src/vpn_script/windows.rs new file mode 100644 index 0000000..b6cd005 --- /dev/null +++ b/apps/gpservice/src/vpn_script/windows.rs @@ -0,0 +1,24 @@ +use gpapi::service::request::ConnectArgs; +use openconnect::{Vpn, VpnBuilder}; +use std::sync::Mutex; +const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery"; + +pub(crate) fn recover_network() -> std::io::Result<()> { + gpvpnc::windows::recover(RECOVERY_KEY) +} + +pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result { + 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) + }), + ) +} diff --git a/apps/gpservice/src/vpn_task.rs b/apps/gpservice/src/vpn_task.rs index 04aa3b9..8709b14 100644 --- a/apps/gpservice/src/vpn_task.rs +++ b/apps/gpservice/src/vpn_task.rs @@ -31,6 +31,8 @@ mod script_tun; #[derive(Clone)] pub(crate) struct LifecycleHandle { + #[cfg(windows)] + pub(crate) patch_checks: Arc, events: mpsc::Sender, admissions: Arc>, tunnel: watch::Sender, @@ -126,6 +128,7 @@ 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"); @@ -447,7 +450,7 @@ pub(crate) struct VpnTask { events: mpsc::Receiver, lifecycle: LifecycleHandle, vpn_state_tx: watch::Sender, - brokered_macos: bool, + restricted_desktop: bool, registry: Arc, active: Option, cancel_token: CancellationToken, @@ -456,11 +459,13 @@ pub(crate) struct VpnTask { impl VpnTask { pub fn new( vpn_state_tx: watch::Sender, - brokered_macos: bool, + restricted_desktop: bool, registry: Arc, ) -> (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, @@ -470,7 +475,7 @@ impl VpnTask { events, lifecycle: lifecycle.clone(), vpn_state_tx, - brokered_macos, + restricted_desktop, registry, active: None, cancel_token: CancellationToken::new(), @@ -617,7 +622,7 @@ impl VpnTask { desktop_uid, edited_report, session_id, - brokered_macos: self.brokered_macos, + restricted_desktop: self.restricted_desktop, registry: self.registry.clone(), lifecycle: self.lifecycle.clone(), }, diff --git a/apps/gpservice/src/vpn_task/non_tunnel.rs b/apps/gpservice/src/vpn_task/non_tunnel.rs index aa3bcb6..a012019 100644 --- a/apps/gpservice/src/vpn_task/non_tunnel.rs +++ b/apps/gpservice/src/vpn_task/non_tunnel.rs @@ -66,10 +66,13 @@ pub(super) async fn run( md5: request.md5.clone(), }; if !posture_enabled { - return gphip::generate_identity_report(&gphip::ReportInput { - profile: profile.clone(), - context, - }) + return gphip::generate_identity_report( + &gphip::ReportInput { + profile: profile.clone(), + context, + }, + control, + ) .map_err(std::io::Error::other); } source.collect( diff --git a/apps/gpservice/src/vpn_task/preparation.rs b/apps/gpservice/src/vpn_task/preparation.rs index 7865018..0781041 100644 --- a/apps/gpservice/src/vpn_task/preparation.rs +++ b/apps/gpservice/src/vpn_task/preparation.rs @@ -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, - brokered_macos: bool, + restricted_desktop: bool, cancellation: CancellationToken, ) -> anyhow::Result { let mode = request.args().packet_delivery().clone(); @@ -77,11 +77,16 @@ pub(crate) async fn prepare_connection( }; check()?; let args = setup_request.args(); - 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 = 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 = None; let identity_files = identity .as_ref() - .map(|identity| identity.write_files(directory)) + .map(|identity| identity.write_files(directory.as_deref())) .transpose()?; let host = args.host_identity().context("Authenticated host identity is missing")?; let profile = crate::hip_source::profile( @@ -181,8 +186,8 @@ mod tests { use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo}; #[tokio::test] - async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() { - for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] { + async fn restricted_desktop_and_non_tunnel_identity_reject_path_handoff() { + for (restricted_desktop, 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())); @@ -192,7 +197,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, brokered_macos, CancellationToken::new()) + let error = prepare_connection(request, restricted_desktop, CancellationToken::new()) .await .err() .unwrap(); diff --git a/apps/gpservice/src/vpn_task/runtime.rs b/apps/gpservice/src/vpn_task/runtime.rs index 9cd31c7..f9f13ae 100644 --- a/apps/gpservice/src/vpn_task/runtime.rs +++ b/apps/gpservice/src/vpn_task/runtime.rs @@ -20,7 +20,7 @@ pub(super) struct AttemptInput { pub desktop_uid: Option, pub edited_report: Option>, pub session_id: Option, - pub brokered_macos: bool, + pub restricted_desktop: bool, pub registry: Arc, pub lifecycle: LifecycleHandle, } @@ -31,6 +31,7 @@ struct TunnelInput { source: Arc, session_id: Option, registry: Arc, + #[cfg(unix)] desktop_uid: Option, } @@ -49,13 +50,30 @@ 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.brokered_macos; + let brokered = input.restricted_desktop; let edited = input.edited_report.clone(); let setup_cancel = cancellation.clone(); let execution = tokio::task::spawn_blocking(move || { @@ -105,6 +123,7 @@ 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(); @@ -253,12 +272,14 @@ 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"); - let (builder, script_tun) = super::script_tun::builder( - member.gateway.server(), - member.authentication.cookie(), - request, - input.desktop_uid.context("Desktop identity is unavailable")?, - )?; + #[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)?; (builder, Some(script_tun)) } }; diff --git a/apps/gpservice/src/vpn_task/script_tun.rs b/apps/gpservice/src/vpn_task/script_tun.rs index 3b8757e..845b042 100644 --- a/apps/gpservice/src/vpn_task/script_tun.rs +++ b/apps/gpservice/src/vpn_task/script_tun.rs @@ -1,40 +1,19 @@ //! 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, ScriptTunRequest, receive, send as send_message}; -use openconnect::{Vpn, VpnBuilder, tunnel::Event}; +use gpapi::script_tun::{Bootstrap, Identity, Message, receive, send as send_message}; +use openconnect::{Vpn, tunnel::Event}; use std::{sync::Arc, time::Duration}; -use tokio::{net::UnixStream, sync::mpsc, time::Instant}; +use tokio::{sync::mpsc, time::Instant}; use tokio_util::sync::CancellationToken; -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(), - }, - )) -} +#[cfg(unix)] +#[path = "script_tun/unix.rs"] +mod platform; +#[cfg(windows)] +#[path = "script_tun/windows.rs"] +mod platform; +pub(super) use platform::{PreparedScriptTun, builder}; #[derive(Debug)] pub(super) struct NetworkChanged; @@ -53,7 +32,7 @@ enum Native { pub(super) async fn run( identity: Identity, vpn: Arc, - prepared: PreparedScriptTun, + mut prepared: PreparedScriptTun, approval: &crate::hip_source::HipApproval, lifecycle: &LifecycleHandle, cancellation: CancellationToken, @@ -62,6 +41,8 @@ pub(super) async fn run( registry: Arc, 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(); @@ -77,7 +58,7 @@ pub(super) async fn run( monitor: monitor.clone(), }) .await; - if event_result.is_err() { + if event_result.is_err() || cancellation.is_cancelled() { monitor.stop().await; return Ok(()); } @@ -91,31 +72,50 @@ pub(super) async fn run( tokio::pin!(worker); let mut worker_done = false; let stop = cancellation.child_token(); - 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); + 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); + } } } + }; + stop.cancel(); + // Keep the consumer's control and packet endpoints alive until OpenConnect + // consumes cancellation and logs out. Early EOF would interrupt that logout. + vpn.disconnect(); + if !worker_done { + let _ = worker.await; } + if !supervisor_done { + let _ = supervisor.await; + } + result }; - stop.cancel(); - if !supervisor_done { - let _ = supervisor.await; - } - vpn.disconnect(); - if !worker_done { - let _ = worker.await; - } + 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:#}"); + } result } @@ -128,93 +128,113 @@ enum WorkerState { Suspending, } -// The same control loop runs against native observations in production and a -// generic socket consumer in tests; VPN ownership stays in run(). +// 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, + messages: mpsc::Receiver>, + reader: tokio::task::JoinHandle<()>, +} +impl ConsumerControl { + fn new(channel: platform::ControlStream) -> Self { + let (mut input, output) = tokio::io::split(channel); + let (messages_tx, messages) = mpsc::channel(8); + let reader = tokio::spawn(async move { + loop { + let message = receive(&mut input).await; + let failed = message.is_err(); + if messages_tx.send(message).await.is_err() || failed { + break; + } + } + }); + Self { + output, + messages, + reader, + } + } + async fn stop(&mut self) { + let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut self.output, &Message::Stop)).await; + self.reader.abort(); + let _ = (&mut self.reader).await; + } +} +impl Drop for ConsumerControl { + fn drop(&mut self) { + self.reader.abort(); + } +} + +// Production and generic-consumer tests exercise this same state machine. async fn supervise( identity: Identity, - mut prepared: PreparedScriptTun, + control: &mut ConsumerControl, + mut bootstrap: Bootstrap, mut native: mpsc::Receiver, cancellation: CancellationToken, events: mpsc::Sender, ) -> anyhow::Result<()> { let attempt = identity.attempt; - 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 ConsumerControl { output, messages, .. } = control; 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 = None; - 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; - } - 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(_) => {}, + 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; } - } - 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)); + 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)); + } + } + Native::Event(Event::Reconnecting) => { + ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN"); + online = false; + events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?; + if matches!(worker, WorkerState::Ready | WorkerState::Active) { + send(output, &Message::Suspend).await?; worker = WorkerState::Suspending; + deadline = Some(Instant::now() + Duration::from_secs(10)); + } + } + Native::Event(Event::Reconnected) => online = true, + Native::Event(_) => {}, } } - Ok(()) - }.await; - let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await; - drop(output); - reader.abort(); - let _ = reader.await; - result + 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(()) } fn observed_network( @@ -243,5 +263,5 @@ async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Messa Ok(()) } -#[cfg(test)] +#[cfg(all(test, unix))] mod tests; diff --git a/apps/gpservice/src/vpn_task/script_tun/tests.rs b/apps/gpservice/src/vpn_task/script_tun/tests.rs index 62d014d..11841c1 100644 --- a/apps/gpservice/src/vpn_task/script_tun/tests.rs +++ b/apps/gpservice/src/vpn_task/script_tun/tests.rs @@ -1,6 +1,8 @@ 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 { @@ -23,16 +25,26 @@ impl Consumer { launch_id: uuid::Uuid::new_v4(), }; let cancel = CancellationToken::new(); - let task = tokio::spawn(supervise( - identity, - PreparedScriptTun { - control, + let stopped = cancel.clone(); + let task = tokio::spawn(async move { + let mut prepared = PreparedScriptTun { + control: Some(control), bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(), - }, - observations, - cancel.clone(), - events, - )); + }; + 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 + }); Self { control: UnixStream::from_std(child).unwrap(), native, @@ -291,3 +303,36 @@ 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()); +} diff --git a/apps/gpservice/src/vpn_task/script_tun/unix.rs b/apps/gpservice/src/vpn_task/script_tun/unix.rs new file mode 100644 index 0000000..8f3d338 --- /dev/null +++ b/apps/gpservice/src/vpn_task/script_tun/unix.rs @@ -0,0 +1,44 @@ +use anyhow::{Context, ensure}; +use gpapi::script_tun::{Bootstrap, ScriptTunRequest}; +use openconnect::{Vpn, VpnBuilder}; +pub(super) type ControlStream = tokio::net::UnixStream; +pub(crate) struct PreparedScriptTun { + pub(super) control: Option, + 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 { + 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(()) + } +} diff --git a/apps/gpservice/src/vpn_task/script_tun/windows.rs b/apps/gpservice/src/vpn_task/script_tun/windows.rs new file mode 100644 index 0000000..36e1216 --- /dev/null +++ b/apps/gpservice/src/vpn_task/script_tun/windows.rs @@ -0,0 +1,69 @@ +use anyhow::{Context, ensure}; +use gpapi::{ + process::user_process::UserProcess, + script_tun::{Bootstrap, ScriptTunRequest}, + windows::PipeClientIdentity, +}; +use openconnect::{Vpn, VpnBuilder}; +use std::{os::windows::io::AsRawHandle, sync::Arc, time::Duration}; +use tokio::net::windows::named_pipe::NamedPipeServer; +use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId; +pub(super) type ControlStream = NamedPipeServer; + +pub(crate) struct PreparedScriptTun { + control: Option, + worker: UserProcess, + pub(super) bootstrap: Bootstrap, +} +pub(crate) fn builder( + server: &str, + cookie: &str, + request: &ScriptTunRequest, + owner: Arc, +) -> 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 { + 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()?) + } +} diff --git a/apps/gpservice/src/windows_patches.rs b/apps/gpservice/src/windows_patches.rs new file mode 100644 index 0000000..d53ed19 --- /dev/null +++ b/apps/gpservice/src/windows_patches.rs @@ -0,0 +1,159 @@ +//! 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, oneshot::Sender), +} + +pub(crate) struct PatchChecks { + tx: mpsc::UnboundedSender, + rx: Mutex>>, +} + +pub(crate) struct Consumer { + checks: Arc, + id: Uuid, +} +impl Drop for Consumer { + fn drop(&mut self) { + self.checks.set_interest(self.id, false); + } +} + +impl PatchChecks { + pub(crate) fn new() -> Arc { + 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) -> Consumer { + let id = Uuid::new_v4(); + self.set_interest(id, true); + Consumer { + checks: self.clone(), + id, + } + } + pub(crate) async fn refresh(&self, after: Option) -> 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::>::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, stop: CancellationToken) -> tokio::task::JoinHandle>> { + tokio::task::spawn_blocking(move || helper("--refresh-patches", after, stop)) +} +fn helper(command: &str, after: Option, stop: CancellationToken) -> anyhow::Result> { + 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)?) +} diff --git a/apps/gpservice/src/windows_service/admission.rs b/apps/gpservice/src/windows_service/admission.rs new file mode 100644 index 0000000..bcc909d --- /dev/null +++ b/apps/gpservice/src/windows_service/admission.rs @@ -0,0 +1,92 @@ +//! A credential lease binds the existing desktop session to its Windows token. +use crate::session_registry::SessionRegistry; +use anyhow::{Context, ensure}; +use gpapi::{ + service::transport::WINDOWS_ADMISSION_REQUEST, + windows::{PipeClientIdentity, create_service_admission_pipe}, +}; +use std::{sync::Arc, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::windows::named_pipe::NamedPipeServer, + task::JoinSet, +}; +use tokio_util::sync::CancellationToken; + +pub(super) struct Admission { + listener: NamedPipeServer, + registry: Arc, +} +struct Lease { + registry: Arc, + session: uuid::Uuid, +} +impl Drop for Lease { + fn drop(&mut self) { + self.registry.revoke(self.session); + } +} +impl Admission { + pub fn new(registry: Arc) -> anyhow::Result { + 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, + 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(()) +} diff --git a/apps/gpservice/src/windows_service/logging.rs b/apps/gpservice/src/windows_service/logging.rs new file mode 100644 index 0000000..f645847 --- /dev/null +++ b/apps/gpservice/src/windows_service/logging.rs @@ -0,0 +1,72 @@ +use std::{fs::OpenOptions, io, path::Path}; + +use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount}; + +const ROTATE_BYTES: usize = 5 * 1024 * 1024; +const ARCHIVE_COUNT: usize = 3; + +pub(super) fn writer(path: &Path) -> io::Result> { + // 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()); + } +} diff --git a/apps/gpservice/src/windows_service/mod.rs b/apps/gpservice/src/windows_service/mod.rs new file mode 100644 index 0000000..cdcec09 --- /dev/null +++ b/apps/gpservice/src/windows_service/mod.rs @@ -0,0 +1,159 @@ +//! Service Control Manager hosting; the GUI remains in the user's desktop session. +mod admission; +mod logging; +use crate::{ + request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer, +}; +use anyhow::{Context, ensure}; +use gpapi::{ + service::vpn_state::VpnState, + utils::{lock_file::LockFile, redact::Redaction}, +}; +use std::{ + ffi::OsString, + io::Write, + sync::{Arc, OnceLock, atomic::AtomicBool}, + time::Duration, +}; +use tokio::sync::{mpsc, watch}; +use tokio_util::sync::CancellationToken; +use windows_service::{ + define_windows_service, + service::{ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType}, + service_control_handler::{self, ServiceControlHandlerResult, ServiceStatusHandle}, + service_dispatcher, +}; +const NAME: &str = common::paths::SERVICE_NAME; +static LOG_LEVEL: OnceLock = 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) { + 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> { + 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) -> 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(()) +} diff --git a/apps/gpservice/src/ws_connection.rs b/apps/gpservice/src/ws_connection.rs index 34f81b3..c31396b 100644 --- a/apps/gpservice/src/ws_connection.rs +++ b/apps/gpservice/src/ws_connection.rs @@ -410,6 +410,48 @@ 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() { @@ -451,6 +493,7 @@ async fn handle_client_message( offset: chunk.offset, xml, complete, + windows_updates: None, }) }) .unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable")); @@ -467,6 +510,7 @@ async fn handle_client_message( offset: 0, xml, complete, + windows_updates: None, }, Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"), }, @@ -501,6 +545,10 @@ 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, diff --git a/apps/gpservice/src/ws_server.rs b/apps/gpservice/src/ws_server.rs index 8e15160..713da08 100644 --- a/apps/gpservice/src/ws_server.rs +++ b/apps/gpservice/src/ws_server.rs @@ -63,6 +63,8 @@ pub(crate) struct WsServerContext { state: Mutex, handshake_slots: Arc, pub(crate) hip_previews: crate::hip_preview::HipPreviews, + #[cfg(windows)] + pub(crate) patch_checks: Arc, } impl WsServerContext { @@ -75,6 +77,8 @@ impl WsServerContext { Self { product_version, registry, + #[cfg(windows)] + patch_checks: dispatcher.patch_checks(), dispatcher, state: Mutex::new(ServiceState { revision: 0, @@ -183,6 +187,8 @@ 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(); @@ -344,6 +350,7 @@ impl WsServer { } } + #[cfg(unix)] pub fn context(&self) -> Arc { Arc::clone(&self.ctx) } @@ -363,6 +370,12 @@ 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"); @@ -377,6 +390,9 @@ 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; } diff --git a/changelog.md b/changelog.md index 783e243..6e19284 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,27 @@ # Changelog +## 3.5.0 + +### Added + +- Added Windows x64 and ARM64 support, with signed installers, built-in browser sign-in, desktop notifications, and in-app updates. +- Added a Windows system tray flyout, native HIP reports, and background Windows Update checks. +- Added a Compatibility Graphics option on Linux for display problems. + +### Improved + +- Refined Windows settings, controls, icons, and window behavior. +- Made HIP Preview faster on Windows and polished connection details across platforms. + +### Fixed + +- Fixed Windows keyboard activation, menu dismissal, dropdown feedback, and scrollbars. +- Restored focus to GP Connect after browser sign-in on Windows. +- Improved recovery from temporary sign-in and license verification failures. +- Corrected native HIP host information on Windows, macOS, Linux, and BSD. +- Kept sensitive authentication and tunnel data out of debug logs. +- Removed unnecessary Linux and FreeBSD package dependencies. + ## 3.4.0 ### Added diff --git a/crates/auth/Cargo.toml b/crates/auth/Cargo.toml index 58bb082..91eab63 100644 --- a/crates/auth/Cargo.toml +++ b/crates/auth/Cargo.toml @@ -20,7 +20,6 @@ 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 } @@ -28,6 +27,7 @@ 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,6 +60,9 @@ webview-auth = [ "dep:tokio-util", "dep:html-escape", "dep:url", + "dep:serde_json", + "dep:webview2-com", + "dep:windows", "dep:gtk", "dep:webkit2gtk", "dep:block2", @@ -94,3 +97,16 @@ 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" } diff --git a/crates/auth/src/callback.rs b/crates/auth/src/callback.rs index 52a873f..02eb829 100644 --- a/crates/auth/src/callback.rs +++ b/crates/auth/src/callback.rs @@ -3,7 +3,6 @@ use std::{ io::ErrorKind, os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}, path::{Path, PathBuf}, - time::Duration, }; use anyhow::{Context, bail}; @@ -14,16 +13,9 @@ use tokio::{ time::timeout, }; -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; +mod protocol; +pub use protocol::validate_auth_callback; +use protocol::*; #[cfg(target_os = "macos")] mod macos; @@ -232,62 +224,9 @@ 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 { - 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::*; diff --git a/crates/auth/src/callback/protocol.rs b/crates/auth/src/callback/protocol.rs new file mode 100644 index 0000000..bef57a1 --- /dev/null +++ b/crates/auth/src/callback/protocol.rs @@ -0,0 +1,73 @@ +//! Bounded authentication callback wire format, shared by local transports. +use anyhow::bail; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +pub(super) const CALLBACK_SCHEME: &str = "globalprotectcallback"; +pub(super) const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC"; +pub(super) const PROTOCOL_VERSION: u8 = 1; +pub(super) const MAX_CALLBACK_SIZE: usize = 1024 * 1024; +pub(super) const IO_TIMEOUT: Duration = Duration::from_secs(5); + +// Acceptance acknowledges delivery, including an authentication failure. +pub(super) const STATUS_ACCEPTED: u8 = 0; +pub(super) const STATUS_INVALID_CALLBACK: u8 = 1; +pub(super) const STATUS_UNSUPPORTED_VERSION: u8 = 2; + +pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> { + if callback.len() > MAX_CALLBACK_SIZE { + bail!("Authentication callback exceeds the maximum supported size"); + } + + let Some((scheme, data)) = callback.split_once(':') else { + bail!("Authentication callback URL is invalid"); + }; + if scheme != CALLBACK_SCHEME || data.is_empty() { + bail!("Authentication callback URL is invalid"); + } + + Ok(()) +} + +pub(super) enum CallbackReadError { + UnsupportedVersion, + Invalid, + Io, +} + +pub(super) async fn read_callback( + stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin), +) -> Result { + 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(()) +} diff --git a/crates/auth/src/callback/windows.rs b/crates/auth/src/callback/windows.rs new file mode 100644 index 0000000..354b05f --- /dev/null +++ b/crates/auth/src/callback/windows.rs @@ -0,0 +1,170 @@ +//! 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 { + 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 { + 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 { + 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::()?; + 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&un=alice@example.com&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(), "alice@example.com"); + assert_eq!(data.token(), Some("test-token")); + } +} diff --git a/crates/auth/src/lib.rs b/crates/auth/src/lib.rs index 6c9d01b..310827f 100644 --- a/crates/auth/src/lib.rs +++ b/crates/auth/src/lib.rs @@ -8,6 +8,7 @@ use gpapi::{ mod browser; #[cfg(feature = "browser-auth")] +#[cfg_attr(windows, path = "callback/windows.rs")] mod callback; #[cfg(feature = "browser-auth")] diff --git a/crates/auth/src/webview.rs b/crates/auth/src/webview.rs index 24cba82..5b3c7e3 100644 --- a/crates/auth/src/webview.rs +++ b/crates/auth/src/webview.rs @@ -12,12 +12,17 @@ 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 macOS and GTK/WebKitGTK Unix targets"); +compile_error!("webview-auth is only supported on Windows, macOS and GTK/WebKitGTK Unix targets"); pub use webview_auth::{WebviewAuthenticator, apply_auth_theme}; diff --git a/crates/auth/src/webview/auth_messenger.rs b/crates/auth/src/webview/auth_messenger.rs index df952c2..483d0c6 100644 --- a/crates/auth/src/webview/auth_messenger.rs +++ b/crates/auth/src/webview/auth_messenger.rs @@ -9,7 +9,7 @@ use tokio_util::sync::CancellationToken; #[derive(Debug)] pub(crate) enum AuthDataLocation { - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] Headers, Body, } @@ -155,7 +155,7 @@ impl AuthMessenger { } } - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) { use log::warn; diff --git a/crates/auth/src/webview/recovery.rs b/crates/auth/src/webview/recovery.rs index a3db72a..9fa36a6 100644 --- a/crates/auth/src/webview/recovery.rs +++ b/crates/auth/src/webview/recovery.rs @@ -22,7 +22,7 @@ impl RecoveryStatus { Self::Hidden => "", Self::Restarting => "Restarting sign-in…", Self::Loading => "Loading sign-in…", - Self::Failed => "Couldn’t restart sign-in.", + Self::Failed => "Couldn’t load sign-in.", Self::Rejected => "Sign-in wasn’t completed.", Self::Tls { reason: TlsFailureReason::Handshake, @@ -55,6 +55,7 @@ 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) } diff --git a/crates/auth/src/webview/tls.rs b/crates/auth/src/webview/tls.rs index f96015a..0f5c6ce 100644 --- a/crates/auth/src/webview/tls.rs +++ b/crates/auth/src/webview/tls.rs @@ -2,7 +2,9 @@ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum TlsFailureReason { Expired, + #[cfg(not(windows))] NotYetValid, + #[cfg(not(windows))] Untrusted, HostnameMismatch, InvalidCertificate, @@ -17,7 +19,9 @@ 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.", diff --git a/crates/auth/src/webview/webview_auth.rs b/crates/auth/src/webview/webview_auth.rs index f97aa8a..17e0db0 100644 --- a/crates/auth/src/webview/webview_auth.rs +++ b/crates/auth/src/webview/webview_auth.rs @@ -1,6 +1,8 @@ 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::{ @@ -8,24 +10,51 @@ use gpapi::{ error::ServerTlsError, gp_params::GpParams, os_profile::{WebviewUserAgent, WebviewUserAgentTransform}, - utils::{redact::redact_uri, window::get_title_bar_height}, + utils::redact::redact_uri, }; use log::{info, warn}; #[cfg(target_os = "macos")] use tauri::Manager; -use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent}; +#[cfg(not(windows))] +use tauri::WebviewUrl; +use tauri::{AppHandle, WindowEvent}; use tokio::{sync::oneshot, time}; use 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) -> anyhow::Result { + 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 trait PlatformWebviewExt { - fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc) -> anyhow::Result<()>; +pub(super) trait PlatformWebviewExt { + fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc) -> anyhow::Result<()>; fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>; @@ -54,7 +83,7 @@ pub trait PlatformWebviewExt { } } -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] pub trait GetHeader { fn get_header(&self, key: &str) -> Option; } @@ -125,19 +154,7 @@ impl<'a> WebviewAuthenticator<'a> { pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result { let auth_messenger = Arc::new(AuthMessenger::new()); - 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()?; + let auth_window = create_auth_window(app_handle, self.window_title, native_theme(self.window_theme))?; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?; @@ -170,7 +187,7 @@ impl<'a> WebviewAuthenticator<'a> { async fn wait_for_auth( &self, - auth_window: &WebviewWindow, + auth_window: &AuthWindow, auth_messenger: Arc, ) -> anyhow::Result { let mut recovery = Recovery::default(); @@ -310,13 +327,16 @@ impl<'a> WebviewAuthenticator<'a> { async fn setup_auth_window( &self, - auth_window: &WebviewWindow, + auth_window: &AuthWindow, auth_messenger: Arc, ) -> 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()?; } @@ -361,7 +381,7 @@ impl<'a> WebviewAuthenticator<'a> { Ok(()) } - fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc) { + fn handle_not_found(&self, auth_window: &AuthWindow, auth_messenger: &Arc) { let visible = auth_window.is_visible().unwrap_or(false); if visible { return; @@ -370,7 +390,7 @@ impl<'a> WebviewAuthenticator<'a> { auth_messenger.schedule_raise_window(2); } - fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> { + fn update_recovery(&self, auth_window: &AuthWindow, status: RecoveryStatus) -> anyhow::Result<()> { if status != RecoveryStatus::Hidden { self.raise_window(auth_window); } @@ -397,7 +417,7 @@ impl<'a> WebviewAuthenticator<'a> { fn load_restarted_sign_in( &self, - auth_window: &WebviewWindow, + auth_window: &AuthWindow, messenger: &Arc, auth_request: String, ) -> anyhow::Result<()> { @@ -415,7 +435,7 @@ impl<'a> WebviewAuthenticator<'a> { Ok(()) } - fn raise_window(&self, auth_window: &WebviewWindow) { + fn raise_window(&self, auth_window: &AuthWindow) { let visible = auth_window.is_visible().unwrap_or(false); if visible { return; diff --git a/crates/auth/src/webview/windows.rs b/crates/auth/src/webview/windows.rs new file mode 100644 index 0000000..72da0d6 --- /dev/null +++ b/crates/auth/src/webview/windows.rs @@ -0,0 +1,380 @@ +//! WebView2 authentication. All COM objects and native controls stay on the UI thread. +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + rc::Rc, + sync::Arc, +}; + +use super::{ + auth_messenger::{AuthDataLocation, AuthError, AuthEvent, AuthMessenger}, + recovery::RecoveryStatus, + webview_auth::{GetHeader, PlatformWebviewExt}, +}; +use anyhow::{Context, bail}; +use gpapi::auth::SamlAuthData; +use tauri::{ + AppHandle, LogicalPosition, Webview, WebviewBuilder, WebviewUrl, Window, WindowBuilder, webview::PlatformWebview, +}; +use webview2_com::{ + ClearBrowsingDataCompletedHandler, CoTaskMemPWSTR, DOMContentLoadedEventHandler, ExecuteScriptCompletedHandler, + Microsoft::Web::WebView2::Win32::*, NavigationCompletedEventHandler, NavigationStartingEventHandler, + SourceChangedEventHandler, WebResourceResponseReceivedEventHandler, +}; +use windows::core::{BOOL, HSTRING, Interface, PWSTR}; + +#[path = "windows/controls.rs"] +mod controls; +#[path = "windows/tls.rs"] +mod tls; + +/// Windows hosts native chrome and a manually sized child webview in one window. +/// Host-owned child bounds keep the page surface below the native controls +/// throughout live resizing. +#[derive(Clone)] +pub(super) struct AuthWindow { + window: Window, + webview: Webview, +} + +impl std::ops::Deref for AuthWindow { + type Target = Window; + fn deref(&self) -> &Window { + &self.window + } +} + +impl AuthWindow { + pub(super) fn with_webview(&self, callback: impl FnOnce(PlatformWebview) + Send + 'static) -> tauri::Result<()> { + self.webview.with_webview(callback) + } +} + +impl gpapi::utils::window::WindowExt for AuthWindow { + fn raise(&self) -> anyhow::Result<()> { + self.window.show()?; + self.window.set_focus()?; + self.webview.set_focus()?; + Ok(()) + } +} + +pub(super) fn create_auth_window( + app: &AppHandle, + title: &str, + theme: Option, +) -> anyhow::Result { + 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>> = RefCell::default(); +} + +struct State { + core: ICoreWebView2, + controller: ICoreWebView2Controller, + messenger: Arc, + controls: controls::Controls, + pending: Cell>, + navigations: RefCell>, + document: RefCell<(String, u64)>, + tls: RefCell, +} + +fn text(get: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result { + 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> { + 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::(&json) { + messenger.read_from_html(&html, generation); + } + Ok(()) + })), + ) + } + } + + fn listen(self: &Rc) -> 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::()? + .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::()? + .add_WebResourceResponseReceived(&response, &mut token)?; + } + tls::install(self)?; + Ok(()) + } +} + +struct Headers(ICoreWebView2HttpResponseHeaders); +impl GetHeader for Headers { + fn get_header(&self, key: &str) -> Option { + unsafe { text(|p| self.0.GetHeader(&HSTRING::from(key), p)).ok() } + } +} + +impl PlatformWebviewExt for PlatformWebview { + fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc) -> 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 { + unsafe { + Ok(text(|p| { + self + .controller() + .CoreWebView2()? + .Settings()? + .cast::()? + .UserAgent(p) + })?) + } + } + fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> { + unsafe { + self + .controller() + .CoreWebView2()? + .Settings()? + .cast::()? + .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::()? + .Profile()? + .cast::()? + .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(()) +} diff --git a/crates/auth/src/webview/windows/controls.rs b/crates/auth/src/webview/windows/controls.rs new file mode 100644 index 0000000..142f98a --- /dev/null +++ b/crates/auth/src/webview/windows/controls.rs @@ -0,0 +1,391 @@ +//! 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, + recovery_bounds: Cell, + font: Cell>, +} + +impl Controls { + pub(super) fn new(window: &AuthWindow, controller: &ICoreWebView2Controller, key: usize) -> anyhow::Result { + // 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 { + 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::() 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, ÷r, 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 +} diff --git a/crates/auth/src/webview/windows/tls.rs b/crates/auth/src/webview/windows/tls.rs new file mode 100644 index 0000000..9d9e90b --- /dev/null +++ b/crates/auth/src/webview/windows/tls.rs @@ -0,0 +1,128 @@ +use super::super::tls::{TlsFailure, TlsFailureReason}; +use super::*; +use std::collections::HashSet; +use webview2_com::{ClearServerCertificateErrorActionsCompletedHandler, ServerCertificateErrorDetectedEventHandler}; +use windows::Win32::UI::WindowsAndMessaging::{IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_YESNO, MessageBoxW}; + +#[derive(Default)] +pub(super) struct Policy { + pub ignore_errors: bool, + approved: HashSet<(String, String)>, + pending: Option, +} +#[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) -> 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::()? + .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::() { + 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 + ); + } +} diff --git a/crates/browser-launcher/Cargo.toml b/crates/browser-launcher/Cargo.toml index ee9b036..354f324 100644 --- a/crates/browser-launcher/Cargo.toml +++ b/crates/browser-launcher/Cargo.toml @@ -10,10 +10,17 @@ 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"] +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 } diff --git a/crates/browser-launcher/src/lib.rs b/crates/browser-launcher/src/lib.rs index d6d134f..c1abb58 100644 --- a/crates/browser-launcher/src/lib.rs +++ b/crates/browser-launcher/src/lib.rs @@ -1,8 +1,11 @@ +#[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", not(target_os = "macos")))] +#[cfg(all(feature = "launcher", unix, not(target_os = "macos")))] #[path = "platform/generic.rs"] mod platform; @@ -38,7 +41,7 @@ impl<'a> Browser<'a> { } } - #[cfg(all(feature = "launcher", not(target_os = "macos")))] + #[cfg(all(feature = "launcher", unix, not(target_os = "macos")))] pub(crate) fn as_str(&self) -> &str { match self { Browser::Auto => "auto", diff --git a/crates/browser-launcher/src/platform/windows.rs b/crates/browser-launcher/src/platform/windows.rs new file mode 100644 index 0000000..5d86c9b --- /dev/null +++ b/crates/browser-launcher/src/platform/windows.rs @@ -0,0 +1,35 @@ +//! Windows browsers are resolved through their registered App Paths. +use crate::Browser; +use anyhow::{Context, bail}; +use std::path::PathBuf; +use winreg::{ + RegKey, + enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}, +}; + +pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> { + let executable = match browser { + Browser::Auto | Browser::Default => return webbrowser::open(url).context("Could not open the browser"), + Browser::Chrome => registered_browser("chrome.exe").context("Chrome is not installed")?, + Browser::Edge => registered_browser("msedge.exe").context("Edge is not installed")?, + Browser::Firefox => registered_browser("firefox.exe").context("Firefox is not installed")?, + Browser::Safari => bail!("Safari is not available on Windows"), + Browser::Other(program) => PathBuf::from(program), + }; + std::process::Command::new(executable) + .arg(url) + .spawn() + .context("Could not open the configured browser")?; + Ok(()) +} + +fn registered_browser(name: &str) -> Option { + [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) + }) +} diff --git a/crates/common/build.rs b/crates/common/build.rs index 15c3e25..7d75146 100644 --- a/crates/common/build.rs +++ b/crates/common/build.rs @@ -5,11 +5,16 @@ fn main() { let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap(); let gpgui_dir = workspace_dir.parent().unwrap().join("gpgui"); - 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"); + 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}")); println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display()); println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display()); diff --git a/crates/common/src/binary_paths.rs b/crates/common/src/binary_paths.rs index 7498a62..45b8923 100644 --- a/crates/common/src/binary_paths.rs +++ b/crates/common/src/binary_paths.rs @@ -89,7 +89,7 @@ fn sibling_binary(binary_name: &str) -> Option { fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option { let executable = executable.canonicalize().ok()?; let bin_dir = executable.parent()?; - let binary = bin_dir.join(binary_name); + let binary = bin_dir.join(format!("{binary_name}{}", std::env::consts::EXE_SUFFIX)); if is_file(&binary) { return Some(binary); } diff --git a/crates/common/src/constants.rs b/crates/common/src/constants.rs index 7f00c52..6c0b28b 100644 --- a/crates/common/src/constants.rs +++ b/crates/common/src/constants.rs @@ -2,7 +2,6 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect"; pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619"; pub const GP_CLIENT_VERSION_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")] diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 9e167ed..7209b09 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -1,2 +1,3 @@ pub mod binary_paths; pub mod constants; +pub mod paths; diff --git a/crates/common/src/paths.rs b/crates/common/src/paths.rs new file mode 100644 index 0000000..3239816 --- /dev/null +++ b/crates/common/src/paths.rs @@ -0,0 +1,32 @@ +//! Machine-wide service state shared by the daemon and desktop clients. +use std::path::PathBuf; + +pub fn service_lock_file() -> PathBuf { + #[cfg(unix)] + { + PathBuf::from("/var/run/gpservice.lock") + } + #[cfg(windows)] + { + std::env::var_os("ProgramData") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")) + .join("GP Connect") + .join("gpservice.lock") + } +} + +#[cfg(windows)] +pub const SERVICE_PIPE: &str = r"\\.\pipe\GPConnect.Service"; + +#[cfg(windows)] +pub const SERVICE_NAME: &str = "GPConnect"; + +/// Installer-owned SYSTEM/Administrators-only state, including temporary keys. +#[cfg(windows)] +pub fn service_private_dir() -> PathBuf { + service_lock_file() + .parent() + .expect("service state directory") + .join("Private") +} diff --git a/crates/gp-xml/Cargo.toml b/crates/gp-xml/Cargo.toml new file mode 100644 index 0000000..92a39bb --- /dev/null +++ b/crates/gp-xml/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "gp-xml" +edition.workspace = true +rust-version.workspace = true +version.workspace = true +license = "MIT" +description = "GlobalProtect response XML redaction for diagnostics" + +[dependencies] +url.workspace = true +xmltree.workspace = true diff --git a/crates/gp-xml/src/lib.rs b/crates/gp-xml/src/lib.rs new file mode 100644 index 0000000..9ba6697 --- /dev/null +++ b/crates/gp-xml/src/lib.rs @@ -0,0 +1,172 @@ +//! Redact GlobalProtect response bodies before writing diagnostics. +use xmltree::{Element, EmitterConfig, XMLNode}; + +const REDACTED: &str = "[redacted]"; +const MAX_XML_BYTES: usize = 1024 * 1024; + +pub fn redact_xml(body: &[u8]) -> String { + if body.len() > MAX_XML_BYTES { + return "[XML omitted: exceeds 1 MiB]".into(); + } + let Ok(text) = std::str::from_utf8(body) else { + return "[XML omitted: invalid UTF-8]".into(); + }; + if text.to_ascii_lowercase().contains(" Some(element), + _ => None, + }); + let Some(mut root) = roots.next() else { + return "[XML omitted: no document element]".into(); + }; + if roots.next().is_some() || root.name.eq_ignore_ascii_case("html") { + return "[XML omitted: unsupported response document]".into(); + } + redact_element(&mut root); + let mut output = Vec::new(); + if root + .write_with_config( + &mut output, + EmitterConfig::new() + .perform_indent(true) + .write_document_declaration(false), + ) + .is_err() + { + return "[XML omitted: serialization failed]".into(); + } + String::from_utf8(output).unwrap_or_else(|_| "[XML omitted: serialization failed]".into()) +} + +fn sensitive_name(name: &str) -> bool { + let name: String = name + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect(); + if name.ends_with("label") { + return false; + } + name.contains("cookie") + || name.contains("token") + || name.contains("password") + || name.contains("passphrase") + || name.contains("secret") + || name.starts_with("ekey") + || name.starts_with("akey") + || matches!( + name.as_str(), + "argument" + | "samlrequest" + | "samlresponse" + | "samlrequestid" + | "assertion" + | "encryptedassertion" + | "authnrequest" + | "challenge" + | "privatekey" + | "encryptionkey" + | "enckey" + | "hskey" + | "enchskey" + | "tunnelopaque" + | "nonce" + | "user" + | "username" + | "ccusername" + | "credential" + ) +} + +fn redact_element(element: &mut Element) { + let named_secret = matches!(element.name.as_str(), "field" | "param" | "property" | "setting") + && ["name", "key"] + .iter() + .any(|name| element.attributes.get(*name).is_some_and(|value| sensitive_name(value))); + let secret = sensitive_name(&element.name) || named_secret; + for (name, value) in &mut element.attributes { + if sensitive_name(name) || (secret && !(named_secret && matches!(name.as_str(), "name" | "key"))) { + *value = REDACTED.into(); + } else { + *value = redact_url(value); + } + } + if secret { + element.children = vec![XMLNode::Text(REDACTED.into())]; + return; + } + element + .children + .retain(|node| matches!(node, XMLNode::Element(_) | XMLNode::Text(_) | XMLNode::CData(_))); + for node in &mut element.children { + match node { + XMLNode::Element(child) => redact_element(child), + XMLNode::Text(value) | XMLNode::CData(value) => *value = redact_url(value), + _ => {} + } + } +} + +fn redact_url(value: &str) -> String { + let Ok(mut url) = url::Url::parse(value) else { + return value.into(); + }; + if !matches!(url.scheme(), "http" | "https") { + return value.into(); + } + if !url.username().is_empty() { + let _ = url.set_username(REDACTED); + } + if url.password().is_some() { + let _ = url.set_password(Some(REDACTED)); + } + if url.query().is_some() { + let pairs: Vec<_> = url + .query_pairs() + .map(|(name, _)| (name.into_owned(), REDACTED)) + .collect(); + url.query_pairs_mut().clear().extend_pairs(pairs); + } + if url.fragment().is_some() { + url.set_fragment(Some(REDACTED)); + } + url.to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn redacts_positional_login_arguments_and_session_keys() { + let xml = redact_xml(br#"fixture-auth-cookiefixture-user256fixture-key-c2sfixture-key-s2cfixture-auth-c2sfixture-auth-s2cfixture-hs-keyfixture-private-keyfixture-saml-responsefixture-opaque1400"#); + assert!(!xml.contains("fixture-")); + assert!(xml.contains("1400")); + Element::parse(xml.as_bytes()).unwrap(); + } + + #[test] + fn omits_unparseable_html_dtd_and_oversized_bodies_without_echoing_them() { + for body in [ + b"not XML fixture-secret".as_slice(), + b"fixture-secret", + b"fixture-secret", + b"]>&secret;", + b"fixture-secret", + b"\xfffixture-secret", + ] { + let xml = redact_xml(body); + assert!(xml.starts_with("[XML omitted:")); + assert!(!xml.contains("fixture-secret")); + } + assert_eq!( + redact_xml(&vec![b'x'; MAX_XML_BYTES + 1]), + "[XML omitted: exceeds 1 MiB]" + ); + } +} diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index ca6646b..475a0e7 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -6,7 +6,7 @@ edition.workspace = true license = "MIT" [dependencies] -nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true } +gp-xml = { path = "../gp-xml" } common = { path = "../common" } anyhow.workspace = true base64.workspace = true @@ -35,7 +35,6 @@ 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 @@ -48,6 +47,9 @@ 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 } @@ -63,8 +65,10 @@ oslog = { version = "0.2", default-features = false, optional = true } [target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies] gtk = { version = "0.18", optional = true } -[target.'cfg(target_os="linux")'.dependencies] +[target.'cfg(any(target_os="linux", target_os="freebsd", target_os="openbsd"))'.dependencies] directories = { workspace = true, optional = true } + +[target.'cfg(target_os="linux")'.dependencies] libloading = { version = "0.9", optional = true } [target.'cfg(target_os="macos")'.dependencies] @@ -78,7 +82,6 @@ cc = "1" pkg-config = "0.3" [dev-dependencies] -openssl.workspace = true libloading = "0.9" proptest.workspace = true tokio = { workspace = true, features = ["test-util"] } @@ -89,4 +92,32 @@ 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 = [] -logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"] +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"] diff --git a/crates/gpapi/README.md b/crates/gpapi/README.md new file mode 100644 index 0000000..efc4e03 --- /dev/null +++ b/crates/gpapi/README.md @@ -0,0 +1,16 @@ +# 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. diff --git a/crates/gpapi/src/device_anchor/mod.rs b/crates/gpapi/src/device_anchor/mod.rs index 89e3bed..989cc44 100644 --- a/crates/gpapi/src/device_anchor/mod.rs +++ b/crates/gpapi/src/device_anchor/mod.rs @@ -10,6 +10,7 @@ pub enum AnchorSource { UnixMac, UnixRandom, MacosIokit, + WindowsSmbios, } impl From for u8 { @@ -18,6 +19,7 @@ impl From for u8 { AnchorSource::UnixMac => 1, AnchorSource::UnixRandom => 2, AnchorSource::MacosIokit => 3, + AnchorSource::WindowsSmbios => 4, } } } @@ -41,6 +43,7 @@ impl TryFrom for AnchorSource { 1 => Ok(Self::UnixMac), 2 => Ok(Self::UnixRandom), 3 => Ok(Self::MacosIokit), + 4 => Ok(Self::WindowsSmbios), value => Err(InvalidAnchorSource(value)), } } @@ -65,6 +68,7 @@ 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()); @@ -81,7 +85,7 @@ mod tests { #[test] fn preserves_existing_hardware_ids_for_all_sources() { - let cases: [(AnchorSource, &[u8], &str); 3] = [ + let cases: [(AnchorSource, &[u8], &str); 4] = [ ( AnchorSource::UnixMac, &[0, 17, 34, 51, 68, 85], @@ -97,6 +101,11 @@ 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); @@ -124,12 +133,17 @@ 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::("4").unwrap(), + AnchorSource::WindowsSmbios + ); assert_eq!( serde_json::from_str::("1").unwrap(), AnchorSource::UnixMac ); assert!(serde_json::from_str::("0").is_err()); - assert!(serde_json::from_str::("4").is_err()); + assert!(serde_json::from_str::("5").is_err()); assert!(serde_json::from_str::(r#""unix_mac""#).is_err()); } } diff --git a/crates/gpapi/src/error/server_tls.rs b/crates/gpapi/src/error/server_tls.rs index ec13926..75e4dc8 100644 --- a/crates/gpapi/src/error/server_tls.rs +++ b/crates/gpapi/src/error/server_tls.rs @@ -109,6 +109,7 @@ 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, @@ -180,10 +181,12 @@ 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(); @@ -233,6 +236,7 @@ mod tests { (address, worker) } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() { use crate::{ @@ -254,6 +258,7 @@ mod tests { assert_eq!(tls.server, address); } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn certificate_bypass_allows_prelogin() { use crate::{ @@ -270,6 +275,7 @@ 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); @@ -303,7 +309,7 @@ mod tests { assert_eq!(classify(&error), None); } - #[cfg(feature = "desktop")] + #[cfg(all(feature = "desktop", unix))] #[test] fn rendering_recovery_retains_client_certificate_requirement() { use crate::process::rendering_recovery::{RecoveryState, RenderingCrash}; @@ -330,6 +336,7 @@ mod tests { ); } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() { use crate::{ @@ -371,6 +378,7 @@ mod tests { } } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() { use crate::{ @@ -403,6 +411,7 @@ 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::{ @@ -435,6 +444,7 @@ mod tests { } } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn imported_identity_formats_complete_mutual_tls_prelogin() { use crate::{ diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index d52661d..5c9b82c 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -202,7 +202,7 @@ async fn receive_gateway_login( let url = res.url().clone(); let http_version = res.version(); let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned(); - let res = parse_gp_response(res).await.map_err(|err| { + let res = parse_gp_response(res).await.map_err(|mut err| { // Redirect paths and query strings can contain authentication tokens. Log // only the redacted origin and whether the response is from the login path. warn!( @@ -221,6 +221,9 @@ async fn receive_gateway_login( if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) { return tls; } + if let Some(error) = err.take_body_read_error() { + return PortalError::NetworkError(error).into(); + } if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { return anyhow::anyhow!(crate::error::AuthenticationRejected); } diff --git a/crates/gpapi/src/gateway/session.rs b/crates/gpapi/src/gateway/session.rs index 21375b2..9537bf1 100644 --- a/crates/gpapi/src/gateway/session.rs +++ b/crates/gpapi/src/gateway/session.rs @@ -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, &response)?; + let status = parse_extend_session_status(&root)?; info!("Extend-session gateway response status: {}", status); @@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result anyhow::Result { +fn parse_extend_session_status(root: &Element) -> anyhow::Result { match root.attr("status") { Some(status) => Ok(status.to_string()), None => { - warn!("Malformed extend-session response body: {}", response.trim()); + warn!("Extend-session response is missing status"); bail!("Malformed extend session response") } } @@ -231,10 +231,7 @@ mod tests { fn parses_extend_session_status_attribute() { let root = Element::parse(r#""#.as_bytes()).unwrap(); - assert_eq!( - parse_extend_session_status(&root, r#""#).unwrap(), - "success" - ); + assert_eq!(parse_extend_session_status(&root).unwrap(), "success"); } #[test] @@ -242,9 +239,7 @@ mod tests { let root = Element::parse("ok".as_bytes()).unwrap(); assert_eq!( - parse_extend_session_status(&root, "ok") - .unwrap_err() - .to_string(), + parse_extend_session_status(&root).unwrap_err().to_string(), "Malformed extend session response" ); } diff --git a/crates/gpapi/src/gui.rs b/crates/gpapi/src/gui.rs index 4be36bb..44a475f 100644 --- a/crates/gpapi/src/gui.rs +++ b/crates/gpapi/src/gui.rs @@ -70,17 +70,17 @@ impl GuiVariant { } } -#[cfg(target_os = "linux")] -fn preference_path() -> anyhow::Result { +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +fn preference_path(name: &str) -> anyhow::Result { let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient") .ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?; - Ok(dirs.config_dir().join("gui")) + Ok(dirs.config_dir().join(name)) } pub fn preferred() -> anyhow::Result { #[cfg(target_os = "linux")] { - match std::fs::read_to_string(preference_path()?) { + match std::fs::read_to_string(preference_path("gui")?) { Ok(value) => match value.trim() { "gpgui" => Ok(GuiVariant::Tauri), "gpgui-nsh" => Ok(GuiVariant::Nsh), @@ -96,12 +96,46 @@ pub fn preferred() -> anyhow::Result { #[cfg(target_os = "linux")] pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> { + save_launch_preference("gui", variant.binary_name()) +} + +pub const COMPATIBILITY_GRAPHICS_SUPPORTED: bool = + cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")); + +pub const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM"; + +const COMPATIBILITY_GRAPHICS: &str = "compatibility-graphics"; + +#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] +fn preference_path(_: &str) -> anyhow::Result { + anyhow::bail!("Compatibility graphics is unavailable") +} + +pub fn compatibility_graphics_enabled() -> bool { + COMPATIBILITY_GRAPHICS_SUPPORTED && preference_path(COMPATIBILITY_GRAPHICS).is_ok_and(|path| path.is_file()) +} + +pub fn set_compatibility_graphics(enabled: bool) -> anyhow::Result<()> { + anyhow::ensure!( + COMPATIBILITY_GRAPHICS_SUPPORTED, + "Compatibility graphics is unavailable" + ); + if enabled { + return save_launch_preference(COMPATIBILITY_GRAPHICS, "enabled"); + } + match std::fs::remove_file(preference_path(COMPATIBILITY_GRAPHICS)?) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + result => result.map_err(Into::into), + } +} + +fn save_launch_preference(name: &str, value: &str) -> anyhow::Result<()> { use std::io::Write; - let path = preference_path()?; + let path = preference_path(name)?; let directory = path.parent().unwrap(); std::fs::create_dir_all(directory)?; let mut file = tempfile::NamedTempFile::new_in(directory)?; - writeln!(file, "{}", variant.binary_name())?; + writeln!(file, "{value}")?; file.persist(path)?; Ok(()) } diff --git a/crates/gpapi/src/hip.rs b/crates/gpapi/src/hip.rs index 58e00d4..173716e 100644 --- a/crates/gpapi/src/hip.rs +++ b/crates/gpapi/src/hip.rs @@ -45,3 +45,27 @@ mod tests { assert_eq!(serde_json::from_value::(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, +} + +#[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, + /// Time of the observed snapshot when its patch details were too large to include. + #[serde(skip_serializing_if = "Option::is_none")] + pub omitted_snapshot_at: Option, +} + +impl WindowsUpdateStatus { + pub fn refresh_cursor(&self) -> Option { + self.checked_at.or(self.omitted_snapshot_at) + } +} diff --git a/crates/gpapi/src/lib.rs b/crates/gpapi/src/lib.rs index e041b9e..989be29 100644 --- a/crates/gpapi/src/lib.rs +++ b/crates/gpapi/src/lib.rs @@ -31,3 +31,6 @@ pub mod clap; #[cfg(feature = "desktop")] pub mod script_tun; + +#[cfg(all(feature = "desktop", windows))] +pub mod windows; diff --git a/crates/gpapi/src/logger.rs b/crates/gpapi/src/logger.rs index c6c3f46..adba6e0 100644 --- a/crates/gpapi/src/logger.rs +++ b/crates/gpapi/src/logger.rs @@ -12,6 +12,20 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified"; type BoxedLogger = Box; static LOG_HANDLE: OnceLock>> = 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 { + #[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() { diff --git a/crates/gpapi/src/logger/windows.rs b/crates/gpapi/src/logger/windows.rs new file mode 100644 index 0000000..c4d3531 --- /dev/null +++ b/crates/gpapi/src/logger/windows.rs @@ -0,0 +1,98 @@ +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 = OnceLock::new(); + +#[derive(Clone)] +struct DiagnosticWriter(Arc>>); + +impl DiagnosticWriter { + fn open(path: &Path) -> io::Result { + 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 { + 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> { + DIAGNOSTICS + .get() + .map(|writer| Box::new(writer.clone()) as Box) +} + +#[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"); + } +} diff --git a/crates/gpapi/src/os_profile/desktop/mod.rs b/crates/gpapi/src/os_profile/desktop/mod.rs index 525cdb2..0ed88d4 100644 --- a/crates/gpapi/src/os_profile/desktop/mod.rs +++ b/crates/gpapi/src/os_profile/desktop/mod.rs @@ -173,6 +173,12 @@ 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 { @@ -181,7 +187,8 @@ pub fn collect_profile_with_control( (defaults::os_version(runtime_os), defaults::software_version(runtime_os)) }; control.check()?; - Ok(builder.build(HostSnapshot { + // The builder may carry cached hardware identity; use the resolved profile identity. + Ok(builder.host_identity(identity.clone()).build(HostSnapshot { runtime_os, identity, os_version, diff --git a/crates/gpapi/src/os_profile/desktop/tests.rs b/crates/gpapi/src/os_profile/desktop/tests.rs index 85bce65..7454a34 100644 --- a/crates/gpapi/src/os_profile/desktop/tests.rs +++ b/crates/gpapi/src/os_profile/desktop/tests.rs @@ -137,14 +137,24 @@ fn assert_mac(value: &str, separator: char) { } #[test] -fn builder_delegates_default_identity_to_host_identity() { +fn builder_preserves_supplied_hardware_fields() { let expected = collect_identity(); let profile = collect_profile( OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()), None, ); - assert_eq!(profile.host_identity(), &expected); + 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()); + } } #[test] @@ -178,3 +188,76 @@ 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()); + } +} diff --git a/crates/gpapi/src/os_profile/desktop/windows.rs b/crates/gpapi/src/os_profile/desktop/windows.rs index 3ddb825..ab22eb4 100644 --- a/crates/gpapi/src/os_profile/desktop/windows.rs +++ b/crates/gpapi/src/os_profile/desktop/windows.rs @@ -1,4 +1,7 @@ -use std::process::Command; +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 super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id}; @@ -36,6 +39,7 @@ impl RuntimeNativeHostIdentity { fn collect_windows_serial_number() -> Option { let output = Command::new("wmic") + .creation_flags(CREATE_NO_WINDOW) .args(["bios", "get", "serialnumber"]) .output() .ok()?; @@ -50,11 +54,15 @@ fn collect_windows_serial_number() -> Option { } fn windows_machine_seed() -> Option { - collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid) + collect_windows_csproduct_uuid().or_else(|| collect_windows_machine_guid().ok()) } fn collect_windows_csproduct_uuid() -> Option { - let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?; + let output = Command::new("wmic") + .creation_flags(CREATE_NO_WINDOW) + .args(["csproduct", "get", "uuid"]) + .output() + .ok()?; let stdout = String::from_utf8(output.stdout).ok()?; stdout @@ -65,24 +73,63 @@ fn collect_windows_csproduct_uuid() -> Option { .next() } -fn collect_windows_machine_guid() -> Option { - let output = Command::new("reg") - .args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"]) - .output() - .ok()?; - if !output.status.success() { - return None; +// 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 { + 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_computer_name() -> io::Result { + 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()); } - let stdout = String::from_utf8(output.stdout).ok()?; + 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; - } - - parts.last().map(str::to_string) - }) +fn collect_windows_machine_guid() -> io::Result { + let key: Vec = "SOFTWARE\\Microsoft\\Cryptography\0".encode_utf16().collect(); + let value: Vec = "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) } impl RuntimeNativeHostIdentity { diff --git a/crates/gpapi/src/os_profile/profile.rs b/crates/gpapi/src/os_profile/profile.rs index 9086928..88228a3 100644 --- a/crates/gpapi/src/os_profile/profile.rs +++ b/crates/gpapi/src/os_profile/profile.rs @@ -124,8 +124,7 @@ impl OsProfile { self.runtime_os == self.client_os } - /// Default software version string for the target OS, matching the - /// official client values. + /// Software version for the target OS profile. pub fn software_version(&self) -> &str { &self.software_version } diff --git a/crates/gpapi/src/os_profile/tests.rs b/crates/gpapi/src/os_profile/tests.rs index 6d9bb36..7a5a163 100644 --- a/crates/gpapi/src/os_profile/tests.rs +++ b/crates/gpapi/src/os_profile/tests.rs @@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() { } #[test] -fn csc_support_defaults_match_official_profiles() { +fn csc_support_defaults_match_platform_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_official_profiles() { +fn prelogin_param_location_matches_platform_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_official_profiles() { +fn external_default_browser_values_match_platform_profiles() { assert_eq!( OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) @@ -132,7 +132,7 @@ fn external_default_browser_values_match_official_profiles() { } #[test] -fn saml_password_matches_official_profiles() { +fn saml_password_matches_platform_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_official_profiles() { +fn kerberos_support_in_query_matches_platform_profiles() { assert!( !OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) @@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_official_profiles() { } #[test] -fn os_vendor_matches_official_profiles() { +fn os_vendor_matches_platform_profiles() { assert_eq!( OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index e6baa6e..7d7ddc5 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use anyhow::bail; -use log::{debug, info, warn}; +use log::{info, warn}; use reqwest::{Client, StatusCode}; use serde::Serialize; use specta::Type; @@ -207,10 +207,13 @@ pub async fn retrieve_config( } })?; - parse_gp_response(res).await.or_else(|err| { + parse_gp_response(res).await.or_else(|mut err| { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { return Err(tls); } + if let Some(error) = err.take_body_read_error() { + return Err(PortalError::NetworkError(error).into()); + } if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { return Err(anyhow::anyhow!(crate::error::AuthenticationRejected)); } @@ -232,7 +235,6 @@ 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) { @@ -247,7 +249,6 @@ 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; } @@ -280,10 +281,13 @@ async fn retrieve_csc_config( } })?; - parse_gp_response(res).await.or_else(|err| { + parse_gp_response(res).await.or_else(|mut err| { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { return Err(tls); } + if let Some(error) = err.take_body_read_error() { + return Err(PortalError::NetworkError(error).into()); + } if err.status == StatusCode::NOT_FOUND { bail!(PortalError::ConfigError("CSC config endpoint not found".to_string())); } diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index 241f577..3f61c3e 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -1,5 +1,5 @@ use anyhow::{anyhow, bail}; -use log::{debug, info, warn}; +use log::{info, warn}; use reqwest::{Client, StatusCode}; use serde::Serialize; use specta::Type; @@ -174,10 +174,8 @@ 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!("Parse response error, response: {}", res_xml); + warn!("Failed to parse prelogin response: {err}"); PortalError::PreloginError(err.to_string()) })?; diff --git a/crates/gpapi/src/process/auth_launcher.rs b/crates/gpapi/src/process/auth_launcher.rs index c5b0357..02aa81a 100644 --- a/crates/gpapi/src/process/auth_launcher.rs +++ b/crates/gpapi/src/process/auth_launcher.rs @@ -17,10 +17,17 @@ use super::{ command_traits::CommandExt, }; -use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit}; +use super::rendering_recovery::{ + AUTH_STDERR_PREFIX, GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible, + is_crash_exit, is_gbm_diagnostic, +}; 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, @@ -49,6 +56,7 @@ pub struct SamlAuthLauncher<'a> { verbose: Option<&'a str>, log_format: LogFormat, dmabuf_disabled: bool, + desktop_compatibility_graphics: bool, } impl<'a> SamlAuthLauncher<'a> { @@ -81,9 +89,15 @@ impl<'a> SamlAuthLauncher<'a> { verbose: None, log_format: LogFormat::Text, dmabuf_disabled: false, + desktop_compatibility_graphics: false, } } + pub fn desktop_compatibility_graphics(mut self) -> Self { + self.desktop_compatibility_graphics = true; + self + } + pub fn dmabuf_disabled(mut self, disabled: bool) -> Self { self.dmabuf_disabled = disabled; self @@ -197,6 +211,8 @@ 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 { @@ -236,7 +252,7 @@ impl<'a> SamlAuthLauncher<'a> { } #[cfg(feature = "webview-auth")] - { + if self.browser.is_none() { if self.hidpi { auth_cmd.arg("--hidpi"); } @@ -292,15 +308,34 @@ impl<'a> SamlAuthLauncher<'a> { if embedded && bundled && self.dmabuf_disabled { command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); } + let desktop_webview = embedded && bundled && self.desktop_compatibility_graphics; + let can_use_shared_memory = desktop_webview && allows_shared_memory_override(&command, true); + let use_shared_memory = can_use_shared_memory && crate::gui::compatibility_graphics_enabled(); + if use_shared_memory { + command.env(crate::gui::FORCE_SHARED_MEMORY, "1"); + } + let detect_gbm_failure = can_use_shared_memory && !use_shared_memory; let stdin = auth_stdin(self.browser); let cancellation = self.cancellation.clone(); let output = tokio::task::spawn_blocking(move || { + #[cfg(feature = "logger")] + let stderr = crate::logger::diagnostic_writer(); + #[cfg(not(feature = "logger"))] + let stderr: Box = Box::new(std::io::stderr()); + let mut stderr = if desktop_webview { + Box::new(std::io::LineWriter::new(AuthStderr(stderr))) + } else { + stderr + }; + let gbm_failed = std::cell::Cell::new(false); let check = || { if cancellation.is_cancelled() { Err(std::io::Error::new( std::io::ErrorKind::Interrupted, "Authentication cancelled", )) + } else if gbm_failed.get() { + Err(std::io::Error::other(GbmBufferFailure)) } else { Ok(()) } @@ -310,19 +345,31 @@ impl<'a> SamlAuthLauncher<'a> { command, &check, Some(MAX_AUTH_RESULT_BYTES), - &mut |bytes| diagnostic.push(bytes), - &mut std::io::stderr(), + &mut |bytes| { + diagnostic.push(bytes); + gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(can_recover)); + }, + &mut stderr, stdin, - )?; - Ok::<_, std::io::Error>((output.output, diagnostic.matched())) + ); + std::io::Write::flush(&mut stderr)?; + if gbm_failed.get() && !cancellation.is_cancelled() { + return Err(GbmBufferFailure.into()); + } + let output = output?; + Ok::<_, anyhow::Error>((output.output, diagnostic.matched())) }) .await?; let (output, rendering_diagnostic) = match output { Ok(output) => output, - Err(error) if error.kind() == std::io::ErrorKind::Interrupted => { + Err(error) + if error + .downcast_ref::() + .is_some_and(|error| error.kind() == std::io::ErrorKind::Interrupted) => + { return Err(crate::auth::AuthenticationCancelled.into()); } - Err(error) => return Err(error.into()), + Err(error) => return Err(error), }; if self.cancellation.is_cancelled() { @@ -332,6 +379,26 @@ impl<'a> SamlAuthLauncher<'a> { } } +// Attribute GBM failures to gpauth before forwarding them to the desktop supervisor. +struct AuthStderr(Box); + +impl std::io::Write for AuthStderr { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + for line in bytes.split_inclusive(|&byte| byte == b'\n') { + if is_gbm_diagnostic(line) { + self.0.write_all(&[AUTH_STDERR_PREFIX, line].concat())?; + } else { + self.0.write_all(line)?; + } + } + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + /// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal. fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> { match browser { @@ -366,11 +433,14 @@ 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(), @@ -389,7 +459,6 @@ 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(), @@ -409,6 +478,42 @@ 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) @@ -451,6 +556,19 @@ 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. @@ -513,11 +631,14 @@ mod tests { #[test] fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() { - use std::os::unix::process::ExitStatusExt; + #[cfg(unix)] + let status = std::process::ExitStatus::from_raw(71 << 8); + #[cfg(windows)] + let status = std::process::ExitStatus::from_raw(0xC0000005); for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] { let error = decode_auth_output( std::process::Output { - status: std::process::ExitStatus::from_raw(71 << 8), + status, stdout, stderr: Vec::new(), }, @@ -530,7 +651,6 @@ 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), @@ -544,6 +664,7 @@ 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; @@ -579,8 +700,11 @@ mod tests { std::fs::write(&custom, "custom").unwrap(); assert!(is_bundled_authenticator(&bundled, &bundled)); assert!(!is_bundled_authenticator(&custom, &bundled)); - let alias = directory.path().join("auth-alias"); - std::os::unix::fs::symlink(&bundled, &alias).unwrap(); - assert!(is_bundled_authenticator(&alias, &bundled)); + #[cfg(unix)] + { + let alias = directory.path().join("auth-alias"); + std::os::unix::fs::symlink(&bundled, &alias).unwrap(); + assert!(is_bundled_authenticator(&alias, &bundled)); + } } } diff --git a/crates/gpapi/src/process/desktop_child.rs b/crates/gpapi/src/process/desktop_child.rs index a5beb9b..88ba362 100644 --- a/crates/gpapi/src/process/desktop_child.rs +++ b/crates/gpapi/src/process/desktop_child.rs @@ -1,10 +1,14 @@ use super::{ command_runner::{ChildInput, run_observed}, - rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit}, + rendering_recovery::{ + GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible_with_inheritance, + is_crash_exit, + }, }; use crate::service::transport::SessionCredential; use anyhow::Context; use std::{ + cell::Cell, collections::HashMap, fs::OpenOptions, path::PathBuf, @@ -19,8 +23,10 @@ pub(super) async fn launch_desktop_child( envs: Option<&HashMap>, credential: &SessionCredential, cancellation: &CancellationToken, + detect_gbm_failure: bool, ) -> anyhow::Result { let retry_eligible = eligible_with_inheritance(&command, envs.is_none()); + let detect_gbm_failure = detect_gbm_failure && allows_shared_memory_override(&command, envs.is_none()); let log_file = match envs { Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from), None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from), @@ -38,12 +44,15 @@ pub(super) async fn launch_desktop_child( let cancellation = cancellation.clone(); tokio::task::spawn_blocking(move || { + let gbm_failed = Cell::new(false); let check = || { if cancellation.is_cancelled() { Err(std::io::Error::new( std::io::ErrorKind::Interrupted, "Desktop child launch cancelled", )) + } else if gbm_failed.get() { + Err(std::io::Error::other(GbmBufferFailure)) } else { Ok(()) } @@ -53,10 +62,17 @@ pub(super) async fn launch_desktop_child( command, &check, None, - &mut |bytes| diagnostic.push(bytes), + &mut |bytes| { + diagnostic.push(bytes); + gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(retry_eligible)); + }, &mut sink, ChildInput::Frame(&frame), - )?; + ); + if gbm_failed.get() && !cancellation.is_cancelled() { + return Err(GbmBufferFailure.into()); + } + let observed = observed?; let output = observed.output; if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() { return Err(RenderingCrash { status: output.status }.into()); diff --git a/crates/gpapi/src/process/desktop_launcher.rs b/crates/gpapi/src/process/desktop_launcher.rs index b7c6bc1..0668e05 100644 --- a/crates/gpapi/src/process/desktop_launcher.rs +++ b/crates/gpapi/src/process/desktop_launcher.rs @@ -170,7 +170,11 @@ impl<'a> DesktopLauncher<'a> { } match outcome { Err(error) if recovery.recover(&error) => { - warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows"); + if recovery.shared_memory() { + warn!("{error}; restarting the desktop launch with compatibility graphics"); + } else { + warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows"); + } expecting_renewal = true; input.write_all(&[DESKTOP_RENDERING_RETRY]).await?; } diff --git a/crates/gpapi/src/process/gui_helper_launcher.rs b/crates/gpapi/src/process/gui_helper_launcher.rs index 68a1361..0c969ba 100644 --- a/crates/gpapi/src/process/gui_helper_launcher.rs +++ b/crates/gpapi/src/process/gui_helper_launcher.rs @@ -79,6 +79,7 @@ impl<'a> GuiHelperLauncher<'a> { self.envs, self.credential, cancellation, + false, ) .await?; Ok(()) diff --git a/crates/gpapi/src/process/gui_launcher.rs b/crates/gpapi/src/process/gui_launcher.rs index 9baaf0e..287bcc7 100644 --- a/crates/gpapi/src/process/gui_launcher.rs +++ b/crates/gpapi/src/process/gui_launcher.rs @@ -101,6 +101,12 @@ impl<'a> GuiLauncher<'a> { if let Some(envs) = &self.envs { cmd.env_clear().envs(envs); } + if self.variant == crate::gui::GuiVariant::Tauri + && crate::gui::compatibility_graphics_enabled() + && super::rendering_recovery::allows_shared_memory_override(cmd.as_std(), self.envs.is_none()) + { + cmd.env(crate::gui::FORCE_SHARED_MEMORY, "1"); + } cmd.arg("--service-credential-on-stdin"); if self.minimized { cmd.arg("--minimized"); @@ -112,6 +118,7 @@ impl<'a> GuiLauncher<'a> { self.envs.as_ref(), &self.credential, cancellation, + self.variant == crate::gui::GuiVariant::Tauri, ) .await } @@ -207,32 +214,45 @@ impl<'a> GuiLauncher<'a> { gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?; return Ok(None); } - service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?; - pending = true; - let credential = super::desktop_launcher::read_credential(service_output).await? - .ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?; - anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch"); - let ready = gui_switch::SwitchListener::new()?; - let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect()); - envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned()); - let launcher = Self::new(self.version, Arc::new(credential), variant) - .envs(envs) - .minimized(false); - let program = match program { - Some(program) => program, - None => launcher.resolve_program(cancellation, command.theme).await?, - }; - let mut child = launcher.start_owned(program, cancellation.child_token()); - let start_result = tokio::select! { - result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => { - result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result) - }, - outcome = &mut child.task => { - return match outcome? { - Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")), - Err(error) => Err(error), - }; - } + use super::rendering_recovery::{GbmBufferFailure, RecoveryState}; + let mut recovery = RecoveryState::default(); + let mut program = program; + let (mut child, start_result) = loop { + service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?; + pending = true; + let credential = super::desktop_launcher::read_credential(service_output).await? + .ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?; + anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch"); + let ready = gui_switch::SwitchListener::new()?; + let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect()); + envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned()); + let launcher = Self::new(self.version, Arc::new(credential), variant) + .envs(envs) + .minimized(false); + let executable = match &program { + Some(program) => program.clone(), + None => launcher.resolve_program(cancellation, command.theme).await?, + }; + let mut child = launcher.start_owned(executable.clone(), cancellation.child_token()); + let start_result = tokio::select! { + result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => { + result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result) + }, + outcome = &mut child.task => { + match outcome? { + Ok(status) => return Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")), + Err(error) if error.is::() && recovery.recover(&error) => { + log::warn!("{error}; restarting the selected GUI with compatibility graphics"); + service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?; + pending = false; + program = Some(executable); + continue; + } + Err(error) => return Err(recovery.terminal(error)), + } + } + }; + break (child, start_result); }; if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) { child.cancel.cancel(); diff --git a/crates/gpapi/src/process/mod.rs b/crates/gpapi/src/process/mod.rs index d706a42..2568c76 100644 --- a/crates/gpapi/src/process/mod.rs +++ b/crates/gpapi/src/process/mod.rs @@ -1,20 +1,41 @@ +#[cfg(unix)] mod command_runner; +#[cfg(windows)] +#[path = "windows/command_runner.rs"] +mod command_runner; +#[cfg(unix)] mod command_traits; +#[cfg(windows)] +#[path = "windows/command_traits.rs"] +mod command_traits; +#[cfg(unix)] mod desktop_child; +#[cfg(unix)] mod desktop_session_env; +#[cfg(unix)] pub(crate) mod gui_helper_launcher; pub use command_traits::CommandExt; pub mod auth_launcher; +#[cfg(unix)] pub mod desktop_launcher; +#[cfg(unix)] pub mod gui_launcher; -#[cfg(any(target_os = "linux", test))] +#[cfg(any(target_os = "linux", all(test, unix)))] pub mod gui_switch; -#[cfg(any(target_os = "linux", test))] +#[cfg(any(target_os = "linux", all(test, unix)))] 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; diff --git a/crates/gpapi/src/process/rendering_recovery.rs b/crates/gpapi/src/process/rendering_recovery.rs index a7e5cd1..e523be9 100644 --- a/crates/gpapi/src/process/rendering_recovery.rs +++ b/crates/gpapi/src/process/rendering_recovery.rs @@ -1,6 +1,9 @@ use std::process::{Command, ExitStatus}; const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER"; +pub const MAIN_WEBVIEW_INITIALIZED: &str = "GP Connect main webview initialized"; +const GBM_DIAGNOSTIC: &[u8] = b"Failed to create GBM buffer"; +pub(crate) const AUTH_STDERR_PREFIX: &[u8] = b"gpauth stderr: "; const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display"; #[derive(Debug, thiserror::Error)] @@ -16,20 +19,33 @@ pub struct RecoveryFailed(#[source] anyhow::Error); #[derive(Default)] pub struct RecoveryState { first_failure: Option, + shared_memory: bool, } impl RecoveryState { pub fn dmabuf_disabled(&self) -> bool { - self.first_failure.is_some() + self.first_failure.is_some() && !self.shared_memory + } + + pub fn shared_memory(&self) -> bool { + self.shared_memory } pub fn recover(&mut self, error: &anyhow::Error) -> bool { - if self.first_failure.is_none() && error.downcast_ref::().is_some() { - self.first_failure = Some(error.to_string()); - true - } else { - false + if self.first_failure.is_some() { + return false; } + let gbm_failure = error.downcast_ref::().is_some(); + if !gbm_failure && error.downcast_ref::().is_none() { + return false; + } + if gbm_failure && let Err(error) = crate::gui::set_compatibility_graphics(true) { + log::warn!("Could not save compatibility graphics setting: {error:#}"); + return false; + } + self.first_failure = Some(error.to_string()); + self.shared_memory = gbm_failure; + true } pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error { @@ -49,11 +65,17 @@ 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) } @@ -64,6 +86,16 @@ pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bo && effective_env(command, DMABUF, inherits).is_none() } +pub(crate) fn allows_shared_memory_override(command: &Command, inherits: bool) -> bool { + crate::gui::COMPATIBILITY_GRAPHICS_SUPPORTED + && effective_env(command, DMABUF, inherits).is_none() + && effective_env(command, crate::gui::FORCE_SHARED_MEMORY, inherits).is_none() +} + +#[derive(Debug, thiserror::Error)] +#[error("WebKit failed to create a GBM buffer")] +pub(crate) struct GbmBufferFailure; + fn effective_env(command: &Command, key: &str, inherits: bool) -> Option { for (name, value) in command.get_envs() { if name == key { @@ -73,12 +105,21 @@ fn effective_env(command: &Command, key: &str, inherits: bool) -> Option bool { + !line.starts_with(AUTH_STDERR_PREFIX) + && line + .windows(GBM_DIAGNOSTIC.len()) + .any(|message| message == GBM_DIAGNOSTIC) +} + /// Observes diagnostic lines without retaining arbitrary application output. #[derive(Default)] pub(crate) struct StderrDiagnostic { line: Vec, overflow: bool, matched: bool, + gbm_failed: bool, + main_webview_initialized: bool, } impl StderrDiagnostic { @@ -98,6 +139,14 @@ impl StderrDiagnostic { fn check_line(&mut self) { let line = self.line.trim_ascii_end(); + if !self.overflow { + if line == MAIN_WEBVIEW_INITIALIZED.as_bytes() { + self.main_webview_initialized = true; + } + if !self.main_webview_initialized && is_gbm_diagnostic(line) { + self.gbm_failed = true; + } + } let message = line.strip_suffix(b".").unwrap_or(line); if !self.overflow && (line.starts_with(b"Gdk-Message:") @@ -111,6 +160,10 @@ impl StderrDiagnostic { } } + pub(crate) fn should_retry_gbm(&self, can_retry_wayland: bool) -> bool { + self.gbm_failed && !(can_retry_wayland && self.matched) + } + pub(crate) fn matched(&mut self) -> bool { self.check_line(); self.matched @@ -121,6 +174,43 @@ impl StderrDiagnostic { mod tests { use super::*; + #[test] + fn detects_gbm_failure_before_main_webview_initializes() { + for line in [ + b"Failed to create GBM buffer of size 280x404: Invalid argument\n".as_slice(), + b"(WebKitWebProcess:42): Warning: Failed to create GBM buffer\n", + b"gpauth: Failed to create GBM buffer\n", + ] { + let mut observer = StderrDiagnostic::default(); + for bytes in line.chunks(7) { + observer.push(bytes); + } + assert!(observer.gbm_failed); + assert!(!observer.matched()); + } + } + + #[test] + fn ignores_gbm_failure_after_startup_and_from_auth_stderr() { + let mut observer = StderrDiagnostic::default(); + observer + .push(b"gpauth stderr: (WebKitWebProcess:42): Failed to create GBM buffer of size 900x648: Invalid argument\n"); + assert!(!observer.gbm_failed); + observer.push(format!("{MAIN_WEBVIEW_INITIALIZED}\n").as_bytes()); + observer.push(b"Failed to create GBM buffer of size 840x640: Invalid argument\n"); + assert!(!observer.gbm_failed); + } + + #[test] + fn preserves_wayland_retry_when_both_diagnostics_are_observed() { + let mut observer = StderrDiagnostic::default(); + observer.push(b"Failed to create GBM buffer of size 280x404: Invalid argument\n"); + observer.push(b"Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\n"); + assert!(observer.matched()); + assert!(!observer.should_retry_gbm(true)); + assert!(observer.should_retry_gbm(false)); + } + #[test] fn recognizes_split_diagnostic_without_matching_quoted_warning() { let mut observer = StderrDiagnostic::default(); @@ -192,6 +282,7 @@ 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; @@ -213,6 +304,7 @@ 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; diff --git a/crates/gpapi/src/process/windows/collection.rs b/crates/gpapi/src/process/windows/collection.rs new file mode 100644 index 0000000..d515e9b --- /dev/null +++ b/crates/gpapi/src/process/windows/collection.rs @@ -0,0 +1,42 @@ +//! Resolve system collectors from Windows' system directory, never the working directory. +use super::command_runner::run_controlled; +use crate::collection::CollectionControl; +use std::{ + io, + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +pub struct CollectorCommands<'a> { + control: &'a dyn CollectionControl, +} +impl<'a> CollectorCommands<'a> { + pub fn new(control: &'a dyn CollectionControl) -> Self { + Self { control } + } + pub fn resolve(&self, name: &str) -> Option { + 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> { + 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> { + self.run_path(path, args) + } + pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result> { + 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), + } + } +} diff --git a/crates/gpapi/src/process/windows/command_runner.rs b/crates/gpapi/src/process/windows/command_runner.rs new file mode 100644 index 0000000..5518afb --- /dev/null +++ b/crates/gpapi/src/process/windows/command_runner.rs @@ -0,0 +1,198 @@ +//! Controlled Windows child execution. Pipe polling keeps cancellation responsive. +use crate::collection::CollectionControl; +use std::{ + io::{self, Read, Write}, + os::windows::io::AsRawHandle, + process::{Child, Command, Output, Stdio}, + thread, + time::Duration, +}; +use windows_sys::Win32::System::Pipes::PeekNamedPipe; + +pub(crate) enum ChildInput<'a> { + Null, + Terminal, + // Preserve the borrowed input type shared by callers without a Windows launcher. + #[allow(dead_code)] + Frame(&'a [u8]), +} + +#[derive(Debug)] +pub(crate) struct ObservedOutput { + pub output: Output, +} + +pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result { + 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, + observer: &mut dyn FnMut(&[u8]), + stderr_sink: &mut dyn Write, + stdin: ChildInput<'_>, +) -> io::Result { + 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 { + 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)); + } +} diff --git a/crates/gpapi/src/process/windows/command_traits.rs b/crates/gpapi/src/process/windows/command_traits.rs new file mode 100644 index 0000000..8d67d6e --- /dev/null +++ b/crates/gpapi/src/process/windows/command_traits.rs @@ -0,0 +1,12 @@ +use tokio::process::Command; + +/// Windows authentication runs in the interactive user's GUI process. +pub trait CommandExt { + fn into_non_root(self) -> anyhow::Result; +} + +impl CommandExt for Command { + fn into_non_root(self) -> anyhow::Result { + Ok(self) + } +} diff --git a/crates/gpapi/src/process/windows/user_process.rs b/crates/gpapi/src/process/windows/user_process.rs new file mode 100644 index 0000000..abe94c0 --- /dev/null +++ b/crates/gpapi/src/process/windows/user_process.rs @@ -0,0 +1,309 @@ +//! Launch a native worker with the admitted user's primary token and environment. +use std::{ + ffi::{OsStr, c_void}, + io, + os::windows::{ + ffi::OsStrExt, + io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle}, + }, + path::Path, + ptr, +}; +use windows_sys::Win32::{ + Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}, + Globalization::{CSTR_EQUAL, CompareStringOrdinal}, + Security::{ImpersonateLoggedOnUser, RevertToSelf}, + System::{ + Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock}, + JobObjects::*, + Threading::*, + }, +}; + +pub struct UserProcess { + process: OwnedHandle, + job: Option, + 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> { + 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) { + 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> { + 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> { + 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::(); + 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 { + 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 = "winsta0\\default".encode_utf16().chain(Some(0)).collect(); + let startup = STARTUPINFOW { + cb: std::mem::size_of::() 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 { + 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 = 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::>(); + LocalFree(parsed.cast()); + assert_eq!(result[0], String::from_utf16_lossy(&program)); + assert_eq!(result[1..], arguments); + } + } +} diff --git a/crates/gpapi/src/service/request.rs b/crates/gpapi/src/service/request.rs index 8f78f2b..236632b 100644 --- a/crates/gpapi/src/service/request.rs +++ b/crates/gpapi/src/service/request.rs @@ -424,6 +424,8 @@ pub struct UpdateLogLevelRequest(pub String); #[derive(Debug, Deserialize, Serialize)] pub enum WsRequest { SetTunnelStatisticsEnabled { enabled: bool }, + SetWindowsPatchInterest { enabled: bool }, + RefreshWindowsPatches { after: Option }, Connect(Box), Disconnect(DisconnectRequest), StopNonTunnelAttachment { connection_id: uuid::Uuid }, diff --git a/crates/gpapi/src/service/transport/credential.rs b/crates/gpapi/src/service/transport/credential.rs index aa11140..503b4fd 100644 --- a/crates/gpapi/src/service/transport/credential.rs +++ b/crates/gpapi/src/service/transport/credential.rs @@ -187,19 +187,28 @@ mod tests { #[test] fn credential_round_trips_a_validated_device_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)); + 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)); + } } #[test] @@ -209,7 +218,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, 4] { + for source in [0, u8::MAX] { payload["device_anchor"] = serde_json::json!({ "hardware_id": hardware_id, "source": source diff --git a/crates/gpapi/src/service/transport/message.rs b/crates/gpapi/src/service/transport/message.rs index 805e5e7..441546f 100644 --- a/crates/gpapi/src/service/transport/message.rs +++ b/crates/gpapi/src/service/transport/message.rs @@ -55,6 +55,8 @@ pub enum ServiceResult { offset: usize, xml: String, complete: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + windows_updates: Option, }, HipApprovalStatus(HipApprovalStatus), NoSubmittedHipReport, diff --git a/crates/gpapi/src/service/transport/mod.rs b/crates/gpapi/src/service/transport/mod.rs index 85870b6..9631c3b 100644 --- a/crates/gpapi/src/service/transport/mod.rs +++ b/crates/gpapi/src/service/transport/mod.rs @@ -11,6 +11,8 @@ 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; diff --git a/crates/gpapi/src/session/desktop/network/mod.rs b/crates/gpapi/src/session/desktop/network/mod.rs index 00f8ce1..73ef3d1 100644 --- a/crates/gpapi/src/session/desktop/network/mod.rs +++ b/crates/gpapi/src/session/desktop/network/mod.rs @@ -29,6 +29,11 @@ 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; @@ -475,6 +480,7 @@ fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow }) } +#[cfg(unix)] fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result { let output = CollectorCommands::new(control) .run(name, args)? diff --git a/crates/gpapi/src/session/desktop/network/native.rs b/crates/gpapi/src/session/desktop/network/native.rs index a495feb..8d5a175 100644 --- a/crates/gpapi/src/session/desktop/network/native.rs +++ b/crates/gpapi/src/session/desktop/network/native.rs @@ -172,6 +172,7 @@ mod tests { ); } + #[cfg(unix)] #[tokio::test] async fn cancellation_kills_and_joins_the_running_resolver_process() { let file = tempfile::NamedTempFile::new().unwrap(); diff --git a/crates/gpapi/src/session/desktop/network/windows.rs b/crates/gpapi/src/session/desktop/network/windows.rs new file mode 100644 index 0000000..7863d8a --- /dev/null +++ b/crates/gpapi/src/session/desktop/network/windows.rs @@ -0,0 +1,148 @@ +//! Windows network identity from IP Helper and adapter DNS configuration. +use super::*; +use std::os::windows::io::AsRawSocket; +use windows_sys::Win32::{ + NetworkManagement::IpHelper::{ + DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1, FreeInterfaceDnsSettings, FreeMibTable, + GetInterfaceDnsSettings, GetIpForwardTable2, + }, + Networking::WinSock::{ + AF_INET, AF_INET6, AF_UNSPEC, IP_UNICAST_IF, IPPROTO_IP, IPPROTO_IPV6, IPV6_UNICAST_IF, SOCKADDR_INET, + SOCKET_ERROR, WSAGetLastError, setsockopt, + }, +}; + +pub(super) fn scope_resolver_socket( + socket: &tokio::net::UdpSocket, + interface: &Interface, + endpoint: SocketAddr, +) -> anyhow::Result<()> { + ensure!(interface.index != 0, "Resolver interface index is missing"); + // IP_UNICAST_IF uses network byte order; IPV6_UNICAST_IF uses host byte order. + let (level, option, index) = if endpoint.is_ipv4() { + (IPPROTO_IP, IP_UNICAST_IF, interface.index.to_be()) + } else { + (IPPROTO_IPV6, IPV6_UNICAST_IF, interface.index) + }; + let result = unsafe { + setsockopt( + socket.as_raw_socket() as usize, + level, + option, + (&index as *const u32).cast(), + std::mem::size_of::() 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> { + 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 { + 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> { + 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::>>()?; + resolvers.sort(); + control.check()?; + Ok(resolvers) +} + +fn resolver_domains(interface: &str) -> anyhow::Result> { + 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) +} diff --git a/crates/gpapi/src/session/transport/binding.rs b/crates/gpapi/src/session/transport/binding.rs index 349acfe..9b3c0fa 100644 --- a/crates/gpapi/src/session/transport/binding.rs +++ b/crates/gpapi/src/session/transport/binding.rs @@ -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"))] +#[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))] fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result { if let std::net::SocketAddr::V6(source) = binding.source() { anyhow::ensure!( diff --git a/crates/gpapi/src/session/transport/mod.rs b/crates/gpapi/src/session/transport/mod.rs index 67c23ae..7baeafd 100644 --- a/crates/gpapi/src/session/transport/mod.rs +++ b/crates/gpapi/src/session/transport/mod.rs @@ -164,6 +164,7 @@ 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) } diff --git a/crates/gpapi/src/utils/certificate/native_key.rs b/crates/gpapi/src/utils/certificate/native_key.rs index 802bcfa..71e2dc0 100644 --- a/crates/gpapi/src/utils/certificate/native_key.rs +++ b/crates/gpapi/src/utils/certificate/native_key.rs @@ -204,6 +204,7 @@ impl Signer for ClientSigner { #[cfg(test)] mod tests { use super::*; + #[cfg(feature = "openssl-tests")] use openssl::{ hash::MessageDigest, pkey::PKey, @@ -220,6 +221,7 @@ 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() @@ -227,6 +229,7 @@ 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"); @@ -255,6 +258,7 @@ 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"); @@ -281,6 +285,7 @@ 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")); diff --git a/crates/gpapi/src/utils/lock_file.rs b/crates/gpapi/src/utils/lock_file.rs index f199af3..7c5f00d 100644 --- a/crates/gpapi/src/utils/lock_file.rs +++ b/crates/gpapi/src/utils/lock_file.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -use common::constants::GP_SERVICE_LOCK_FILE; +use common::paths::service_lock_file; use thiserror::Error; use tokio::fs; @@ -109,7 +109,7 @@ impl LockInfo { } pub async fn gpservice_lock_info() -> Result { - gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await + gpservice_lock_info_at(service_lock_file()).await } pub async fn gpservice_lock_info_at(path: impl AsRef) -> Result { diff --git a/crates/gpapi/src/utils/mod.rs b/crates/gpapi/src/utils/mod.rs index c33a57d..2556261 100644 --- a/crates/gpapi/src/utils/mod.rs +++ b/crates/gpapi/src/utils/mod.rs @@ -13,6 +13,8 @@ mod identity_encoding; #[cfg(feature = "desktop")] pub mod lock_file; pub mod redact; +mod response_log; +pub(crate) use response_log::log_response_xml; pub mod request; #[cfg(feature = "tauri")] pub mod window; @@ -53,16 +55,23 @@ pub fn remove_url_scheme(s: &str) -> String { } #[derive(Error, Debug)] -#[error("GP response error: reason={reason}, status={status}, body={body}")] +#[error("GP response error: reason={reason}, status={status}")] pub struct GpError { pub status: StatusCode, pub reason: String, - body: String, #[source] source: Option, } impl GpError { + pub(crate) fn take_body_read_error(&mut self) -> Option { + if self.is_status_error() { + None + } else { + self.source.take() + } + } + pub fn is_status_error(&self) -> bool { self.status.is_client_error() || self.status.is_server_error() } @@ -79,16 +88,20 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result return Err(parse_gp_error(res).await); } - res.text().await.map_err(|err| { + let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned()); + let body = res.text().await.map_err(|err| { warn!("Failed to read response: {}", err); GpError { status, reason: "failed to read response".to_string(), - body: "".to_string(), source: Some(err), } - }) + })?; + if let Some(path) = path { + log_response_xml(&path, status, body.as_bytes()); + } + Ok(body) } async fn parse_gp_error(res: Response) -> GpError { @@ -99,15 +112,16 @@ async fn parse_gp_error(res: Response) -> GpError { .map_or_else(|| "", |v| v.to_str().unwrap_or("")) .to_string(); - let (body, source) = match res.text().await { - Ok(body) => (if body.is_empty() { "".to_string() } else { body }, None), - Err(error) => ("".to_string(), Some(error)), + let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned()); + let source = match res.text().await { + Ok(body) => { + if let Some(path) = path { + log_response_xml(&path, status, body.as_bytes()); + } + None + } + Err(error) => Some(error), }; - GpError { - status, - reason, - body, - source, - } + GpError { status, reason, source } } diff --git a/crates/gpapi/src/utils/request.rs b/crates/gpapi/src/utils/request.rs index 97cc05f..a345a41 100644 --- a/crates/gpapi/src/utils/request.rs +++ b/crates/gpapi/src/utils/request.rs @@ -266,6 +266,7 @@ mod tests { #[test] fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() { + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; let identity = ClientIdentity::from_data( Zeroizing::new(CERTIFICATE.to_vec()), @@ -280,6 +281,7 @@ mod tests { let path = files.certificate().to_owned(); assert!(path.ends_with(".p12")); assert!(files.key().is_none()); + #[cfg(unix)] assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); drop(files); assert!(!Path::new(&path).exists()); diff --git a/crates/gpapi/src/utils/response_log.rs b/crates/gpapi/src/utils/response_log.rs new file mode 100644 index 0000000..8a724b2 --- /dev/null +++ b/crates/gpapi/src/utils/response_log.rs @@ -0,0 +1,59 @@ +use gp_xml::redact_xml; +use reqwest::StatusCode; + +pub(crate) fn log_response_xml(path: &str, status: StatusCode, body: &[u8]) { + if !log::log_enabled!(log::Level::Debug) { + return; + } + // Redirect paths can themselves contain authentication tokens. + let endpoint = match path { + "/global-protect/prelogin.esp" + | "/ssl-vpn/prelogin.esp" + | "/global-protect/getconfig.esp" + | "/global-protect/getconfig_csc.esp" + | "/ssl-vpn/login.esp" + | "/ssl-vpn/getconfig.esp" + | "/ssl-vpn/agentmessage.esp" + | "/ssl-vpn/hipreportcheck.esp" + | "/ssl-vpn/hipreport.esp" + | "/ssl-vpn/logout.esp" => path, + _ => "[response endpoint]", + }; + // Individual XML lines remain readable in macOS unified logs with limited record sizes. + for line in redact_xml(body).lines() { + log::debug!("{endpoint} response XML (HTTP {}): {line}", status.as_u16()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use xmltree::Element; + + #[test] + fn preserves_policy_checks_and_redacts_authentication_material() { + let input = include_str!("../../tests/fixtures/portal-response.xml"); + let xml = redact_xml(input.as_bytes()); + let root = Element::parse(xml.as_bytes()).unwrap(); + assert!(xml.contains("custom-checks") && xml.contains("HipID") && xml.contains("NV Domain")); + assert!(xml.contains("Corp.Example.test")); + assert!(xml.contains("com.1password.1password") && xml.contains("Version")); + for secret in [ + "fixture-user-cookie", + "fixture-prelogon-cookie", + "fixture-csc-cookie", + "fixture-username", + "fixture-saml", + "fixture-attribute-token", + "fixture-property-password", + "fixture-cookie-name", + "fixture-query-token", + "fixture-url-password", + "fixture-comment", + "fixture-pi", + ] { + assert!(!xml.contains(secret), "secret retained: {secret}"); + } + assert_eq!(root.name, "policy"); + } +} diff --git a/crates/gpapi/src/utils/shutdown_signal.rs b/crates/gpapi/src/utils/shutdown_signal.rs index 1f1f1fc..863ef34 100644 --- a/crates/gpapi/src/utils/shutdown_signal.rs +++ b/crates/gpapi/src/utils/shutdown_signal.rs @@ -13,6 +13,9 @@ pub async fn shutdown_signal() { .await; }; + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, diff --git a/crates/gpapi/src/windows.rs b/crates/gpapi/src/windows.rs new file mode 100644 index 0000000..f7d1681 --- /dev/null +++ b/crates/gpapi/src/windows.rs @@ -0,0 +1,176 @@ +//! Windows user identity and private local IPC. +use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle}; +use std::{io, ptr}; +mod pipes; +pub use pipes::{PacketPipe, connect_service_admission, connect_service_worker, create_service_admission_pipe}; +use tokio::net::windows::named_pipe::NamedPipeServer; +use windows_sys::Win32::{ + Foundation::{CloseHandle, LocalFree}, + Security::{Authorization::ConvertSidToStringSidW, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser}, + System::Threading::{GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION}, +}; + +pub fn current_user_sid() -> io::Result { + unsafe { + let mut token = ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + return Err(io::Error::last_os_error()); + } + let result = token_user_sid(token); + CloseHandle(token); + result + } +} + +/// An authenticated pipe client's primary token, retained for its user-session worker. +/// Windows user identity is a SID and token; it is never represented as a Unix UID. +pub struct PipeClientIdentity { + sid: String, + token: OwnedHandle, +} + +impl PipeClientIdentity { + pub fn sid(&self) -> &str { + &self.sid + } + + pub fn primary_token(&self) -> BorrowedHandle<'_> { + self.token.as_handle() + } + + /// Call after reading the client's admission request. Impersonation stays on + /// this thread and ends before returning; no asynchronous work can run in it. + pub fn from_pipe(pipe: &NamedPipeServer) -> io::Result { + use windows_sys::Win32::{ + Security::{ + DuplicateTokenEx, RevertToSelf, SecurityImpersonation, TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TokenPrimary, + }, + System::{ + Pipes::ImpersonateNamedPipeClient, + Threading::{GetCurrentThread, OpenThreadToken}, + }, + }; + struct Revert; + impl Drop for Revert { + fn drop(&mut self) { + // Continuing a service thread as its client would corrupt its privilege + // boundary. Windows documents terminating if RevertToSelf fails. + if unsafe { RevertToSelf() } == 0 { + std::process::abort(); + } + } + } + unsafe { + if ImpersonateNamedPipeClient(pipe.as_raw_handle()) == 0 { + return Err(io::Error::last_os_error()); + } + let _revert = Revert; + let mut token = ptr::null_mut(); + if OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, 1, &mut token) == 0 { + return Err(io::Error::last_os_error()); + } + let token = OwnedHandle::from_raw_handle(token); + let sid = token_user_sid(token.as_raw_handle())?; + let mut primary = ptr::null_mut(); + if DuplicateTokenEx( + token.as_raw_handle(), + TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY, + ptr::null(), + SecurityImpersonation, + TokenPrimary, + &mut primary, + ) == 0 + { + return Err(io::Error::last_os_error()); + } + Ok(Self { + sid, + token: OwnedHandle::from_raw_handle(primary), + }) + } + } +} + +/// Resolve a local IPC peer from its OS process token. +pub fn process_user_sid(pid: u32) -> io::Result { + unsafe { + let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if process.is_null() { + return Err(io::Error::last_os_error()); + } + let mut token = ptr::null_mut(); + if OpenProcessToken(process, TOKEN_QUERY, &mut token) == 0 { + let error = io::Error::last_os_error(); + CloseHandle(process); + return Err(error); + } + CloseHandle(process); + let result = token_user_sid(token); + CloseHandle(token); + result + } +} + +unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result { + unsafe { + let mut length = 0; + GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut length); + // TOKEN_USER contains pointers; retain pointer alignment in its backing allocation. + let mut buffer = vec![0usize; (length as usize).div_ceil(std::mem::size_of::())]; + if GetTokenInformation(token, TokenUser, buffer.as_mut_ptr().cast(), length, &mut length) == 0 { + return Err(io::Error::last_os_error()); + } + let user = &*buffer.as_ptr().cast::(); + let mut text = ptr::null_mut(); + if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 { + return Err(io::Error::last_os_error()); + } + let mut length = 0; + while *text.add(length) != 0 { + length += 1; + } + let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, length)); + LocalFree(text.cast()); + Ok(sid) + } +} + +/// Only the owning user and SYSTEM can access authentication callbacks. +pub fn create_user_pipe(name: &str, first_instance: bool) -> io::Result { + pipes::user_pipe(¤t_user_sid()?, name, first_instance) +} + +/// Query a registered service without requiring access to its SYSTEM process token. +pub fn service_process_id(name: &str) -> io::Result { + use windows_sys::Win32::System::Services::*; + let name: Vec = name.encode_utf16().chain(Some(0)).collect(); + unsafe { + let manager = OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT); + if manager.is_null() { + return Err(io::Error::last_os_error()); + } + let service = OpenServiceW(manager, name.as_ptr(), SERVICE_QUERY_STATUS); + if service.is_null() { + let error = io::Error::last_os_error(); + CloseServiceHandle(manager); + return Err(error); + } + let mut status = SERVICE_STATUS_PROCESS::default(); + let mut length = 0; + let success = QueryServiceStatusEx( + service, + SC_STATUS_PROCESS_INFO, + (&mut status as *mut SERVICE_STATUS_PROCESS).cast(), + std::mem::size_of_val(&status) as u32, + &mut length, + ); + let result = if success == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(status.dwProcessId) + }; + CloseServiceHandle(service); + CloseServiceHandle(manager); + result + } +} diff --git a/crates/gpapi/src/windows/pipes.rs b/crates/gpapi/src/windows/pipes.rs new file mode 100644 index 0000000..ef54c20 --- /dev/null +++ b/crates/gpapi/src/windows/pipes.rs @@ -0,0 +1,202 @@ +//! Local service admission and worker pipes with explicit user access. +use super::PipeClientIdentity; +use std::{ + fs::OpenOptions, + io, + os::windows::{ + fs::OpenOptionsExt, + io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle}, + }, + ptr, + time::Duration, +}; +use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer, ServerOptions}; +use windows_sys::Win32::{ + Foundation::{ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0, WAIT_TIMEOUT}, + Security::{Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, SECURITY_ATTRIBUTES}, + Storage::FileSystem::*, + System::{ + IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED}, + Pipes::*, + Threading::{CreateEventW, WaitForSingleObject}, + }, +}; + +// Generic write also grants FILE_CREATE_PIPE_INSTANCE. Clients receive only +// data/metadata access; creating another instance remains SYSTEM-only. +const CLIENT_ACCESS: u32 = FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES; +fn wide(value: &str) -> Vec { + value.encode_utf16().chain(Some(0)).collect() +} +fn with_security(sddl: &str, operation: impl FnOnce(&SECURITY_ATTRIBUTES) -> io::Result) -> io::Result { + struct Descriptor(*mut std::ffi::c_void); + impl Drop for Descriptor { + fn drop(&mut self) { + unsafe { + LocalFree(self.0); + } + } + } + let mut pointer = ptr::null_mut(); + if unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW(wide(sddl).as_ptr(), 1, &mut pointer, ptr::null_mut()) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let descriptor = Descriptor(pointer); + operation(&SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor.0, + bInheritHandle: 0, + }) +} +fn server(sddl: &str, name: &str, first: bool) -> io::Result { + with_security(sddl, |attributes| unsafe { + ServerOptions::new() + .first_pipe_instance(first) + .reject_remote_clients(true) + .create_with_security_attributes_raw(name, (attributes as *const SECURITY_ATTRIBUTES).cast_mut().cast()) + }) +} +pub(super) fn user_pipe(sid: &str, name: &str, first: bool) -> io::Result { + server(&format!("D:P(A;;GA;;;SY)(A;;GA;;;{sid})"), name, first) +} +pub fn create_service_admission_pipe(first: bool) -> io::Result { + server( + &format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;AU)"), + common::paths::SERVICE_PIPE, + first, + ) +} +fn client(name: &str, message: bool, impersonation: bool) -> io::Result { + let file = OpenOptions::new() + .read(true) + .write(true) + .access_mode(CLIENT_ACCESS) + .custom_flags(FILE_FLAG_OVERLAPPED) + .security_qos_flags(if impersonation { + SECURITY_IMPERSONATION + } else { + SECURITY_IDENTIFICATION + }) + .open(name)?; + let pipe = unsafe { NamedPipeClient::from_raw_handle(file.into_raw_handle()) }?; + let mut pid = 0; + if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut pid) } == 0 { + return Err(io::Error::last_os_error()); + } + if pid == 0 || pid != super::service_process_id(common::paths::SERVICE_NAME)? { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Pipe does not belong to the registered VPN service", + )); + } + if message { + let mode = PIPE_READMODE_MESSAGE; + if unsafe { SetNamedPipeHandleState(pipe.as_raw_handle(), &mode, ptr::null(), ptr::null()) } == 0 { + return Err(io::Error::last_os_error()); + } + } + Ok(pipe) +} +/// Verify the service before the first request permits it to impersonate this user. +pub fn connect_service_admission() -> io::Result { + client(common::paths::SERVICE_PIPE, false, true) +} +pub fn connect_service_worker(name: &str, message: bool) -> io::Result { + client(name, message, false) +} + +impl PipeClientIdentity { + pub fn create_control_pipe(&self, name: &str) -> io::Result { + server( + &format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()), + name, + true, + ) + } + pub fn create_packet_pipe(&self, name: &str) -> io::Result { + let name = wide(name); + with_security( + &format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()), + |attributes| { + let handle = unsafe { + CreateNamedPipeW( + name.as_ptr(), + PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS, + 1, + 256 * 1024, + 256 * 1024, + 0, + attributes, + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(io::Error::last_os_error()); + } + Ok(PacketPipe(unsafe { OwnedHandle::from_raw_handle(handle) })) + }, + ) + } +} +/// Raw Win32 overlapped I/O, deliberately never registered with Tokio/Mio IOCP. +pub struct PacketPipe(OwnedHandle); +impl PacketPipe { + pub fn connect(&mut self, expected_pid: u32, timeout: Duration) -> io::Result<()> { + let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) }; + if event.is_null() { + return Err(io::Error::last_os_error()); + } + let event = unsafe { OwnedHandle::from_raw_handle(event) }; + let mut overlap = OVERLAPPED { + hEvent: event.as_raw_handle(), + ..Default::default() + }; + if unsafe { ConnectNamedPipe(self.0.as_raw_handle(), &mut overlap) } == 0 { + let error = io::Error::last_os_error(); + match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_PIPE_CONNECTED) => {} + Some(ERROR_IO_PENDING) => { + let status = unsafe { + WaitForSingleObject( + event.as_raw_handle(), + timeout.as_millis().min(u32::MAX as u128 - 1) as u32, + ) + }; + let mut bytes = 0; + if status != WAIT_OBJECT_0 { + // Complete cancellation before OVERLAPPED/event storage is released. + unsafe { + CancelIoEx(self.0.as_raw_handle(), &overlap); + GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 1); + } + if status == WAIT_TIMEOUT { + return Err(io::Error::new(io::ErrorKind::TimedOut, "Packet worker did not connect")); + } + return Err(io::Error::last_os_error()); + } + if unsafe { GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 0) } == 0 { + return Err(io::Error::last_os_error()); + } + } + _ => return Err(error), + } + } + let mut pid = 0; + if unsafe { GetNamedPipeClientProcessId(self.0.as_raw_handle(), &mut pid) } == 0 { + return Err(io::Error::last_os_error()); + } + if pid != expected_pid { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Unexpected packet pipe client", + )); + } + Ok(()) + } + pub fn into_handle(self) -> OwnedHandle { + self.0 + } +} diff --git a/crates/gpapi/tests/fixtures/portal-response.xml b/crates/gpapi/tests/fixtures/portal-response.xml new file mode 100644 index 0000000..b2f16f3 --- /dev/null +++ b/crates/gpapi/tests/fixtures/portal-response.xml @@ -0,0 +1,23 @@ + + + + + fixture-user-cookie + + fixture-csc-cookie + fixture-username + fixture-saml + + + + + + 3600 + yes + + HipIDVersion + DomainNV Domain + + + Corp.Example.test + diff --git a/crates/gpapi/tests/identity_encoding.rs b/crates/gpapi/tests/identity_encoding.rs index 1f76146..0ce6f4d 100644 --- a/crates/gpapi/tests/identity_encoding.rs +++ b/crates/gpapi/tests/identity_encoding.rs @@ -93,12 +93,19 @@ fn traditional_encrypted_pem_preserves_password_errors() { let result = load(&certificate, &key, password); if password == Some(PASSWORD) { let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}")); - let actual = openssl::pkey::PKey::private_key_from_pem(identity.key_data().unwrap()).unwrap(); - let expected = openssl::pkey::PKey::private_key_from_pem(&bytes(&format!("{algorithm}-pkcs8.pem"))).unwrap(); - assert!( - actual.public_eq(&expected), - "{key:?}: imported key differs from the fixture" - ); + let public_key = |pem: &[u8]| { + let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(pem)) + .unwrap() + .unwrap(); + rustls::crypto::ring::sign::any_supported_type(&key) + .unwrap() + .public_key() + .unwrap() + .into_owned() + }; + let actual = public_key(identity.key_data().unwrap()); + let expected = public_key(&bytes(&format!("{algorithm}-pkcs8.pem"))); + assert!(actual == expected, "{key:?}: imported key differs from the fixture"); assert!(identity.key_password().is_none()); } else { let error = result.unwrap_err(); diff --git a/crates/gpapi/tests/response_logging.rs b/crates/gpapi/tests/response_logging.rs new file mode 100644 index 0000000..130db0d --- /dev/null +++ b/crates/gpapi/tests/response_logging.rs @@ -0,0 +1,123 @@ +use std::sync::Mutex; + +use gpapi::utils::parse_gp_response; +use log::{LevelFilter, Log, Metadata, Record}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; + +struct Capture(Mutex>); +static LOGS: Capture = Capture(Mutex::new(Vec::new())); +impl Log for Capture { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + fn log(&self, record: &Record<'_>) { + if record.target() == "gpapi::utils::response_log" { + self.0.lock().unwrap().push(record.args().to_string()); + } + } + fn flush(&self) {} +} + +async fn response(path: &str, status: &str, body: &str) -> reqwest::Response { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let data = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 4096]; + socket.read(&mut request).await.unwrap(); + socket.write_all(data.as_bytes()).await.unwrap(); + }); + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .get(format!("http://{address}{path}")) + .send() + .await + .unwrap() +} + +#[tokio::test] +async fn logs_redacted_xml_at_debug_without_changing_responses_or_exposing_error_bodies() { + rustls::crypto::ring::default_provider().install_default().unwrap(); + log::set_logger(&LOGS).unwrap(); + log::set_max_level(LevelFilter::Debug); + let portal = include_str!("fixtures/portal-response.xml"); + for path in [ + "/global-protect/getconfig.esp", + "/global-protect/getconfig_csc.esp", + "/global-protect/prelogin.esp", + "/ssl-vpn/login.esp", + ] { + let result = parse_gp_response(response(path, "200 OK", portal).await).await.unwrap(); + assert_eq!(result, portal); + } + let logs = LOGS.0.lock().unwrap().join("\n"); + assert!(logs.contains("getconfig.esp response XML")); + assert!(logs.contains("getconfig_csc.esp response XML")); + assert!(logs.contains("prelogin.esp response XML")); + assert!(logs.contains("login.esp response XML")); + assert!(logs.contains("custom-checks") && logs.contains("HipID")); + for secret in [ + "fixture-user-cookie", + "fixture-prelogon-cookie", + "fixture-csc-cookie", + "fixture-username", + "fixture-saml", + "fixture-attribute-token", + "fixture-property-password", + "fixture-cookie-name", + "fixture-query-token", + "fixture-url-password", + "fixture-comment", + "fixture-pi", + ] { + assert!(!logs.contains(secret), "logged secret: {secret}"); + } + + let error = parse_gp_response(response("/global-protect/getconfig.esp", "403 Forbidden", portal).await) + .await + .unwrap_err(); + assert_eq!(error.status, reqwest::StatusCode::FORBIDDEN); + assert!(!format!("{error:?} {error}").contains("fixture-")); + assert!(LOGS.0.lock().unwrap().iter().any(|line| line.contains("HTTP 403"))); + + let error = parse_gp_response( + response( + "/global-protect/getconfig.esp", + "500 Internal Server Error", + "fixture-error-secret", + ) + .await, + ) + .await + .unwrap_err(); + assert!(!format!("{error:?} {error}").contains("fixture-error-secret")); + assert!(!LOGS.0.lock().unwrap().join("\n").contains("fixture-error-secret")); + + LOGS.0.lock().unwrap().clear(); + let body = "fixture-login-cookie"; + parse_gp_response(response("/redirect/fixture-path-token?token=fixture-query-token", "200 OK", body).await) + .await + .unwrap(); + let logs = LOGS.0.lock().unwrap().join("\n"); + assert!(logs.contains("[response endpoint]")); + assert!(!logs.contains("fixture-")); + + LOGS.0.lock().unwrap().clear(); + log::set_max_level(LevelFilter::Info); + assert_eq!( + parse_gp_response(response("/global-protect/getconfig.esp", "200 OK", portal).await) + .await + .unwrap(), + portal + ); + assert!(LOGS.0.lock().unwrap().is_empty()); +} diff --git a/crates/gpapi/tests/windows_identity.rs b/crates/gpapi/tests/windows_identity.rs new file mode 100644 index 0000000..8be2d03 --- /dev/null +++ b/crates/gpapi/tests/windows_identity.rs @@ -0,0 +1,87 @@ +#![cfg(windows)] + +use gpapi::windows::{PipeClientIdentity, create_user_pipe, current_user_sid}; +use std::{io, os::windows::io::AsRawHandle, ptr, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::windows::named_pipe::ClientOptions, +}; +use windows_sys::Win32::{ + Foundation::{CloseHandle, ERROR_NO_TOKEN}, + Security::{GetTokenInformation, TOKEN_QUERY, TOKEN_TYPE, TokenPrimary, TokenType}, + Storage::FileSystem::{SECURITY_IDENTIFICATION, SECURITY_IMPERSONATION}, + System::Threading::{GetCurrentThread, OpenThreadToken}, +}; + +fn assert_reverted() { + let mut token = ptr::null_mut(); + let success = unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) }; + if success != 0 { + unsafe { + CloseHandle(token); + } + panic!("The service thread still impersonates its client"); + } + assert_eq!(io::Error::last_os_error().raw_os_error(), Some(ERROR_NO_TOKEN as i32)); +} + +async fn admission(qos: u32) -> io::Result { + let path = format!(r"\\.\pipe\GPConnect.IdentityTest.{}", uuid::Uuid::new_v4()); + let mut pipe = create_user_pipe(&path, true)?; + let client = tokio::spawn(async move { + let mut pipe = ClientOptions::new().security_qos_flags(qos).open(path).unwrap(); + pipe.write_all(b"admit").await.unwrap(); + let mut response = [0]; + pipe.read_exact(&mut response).await.unwrap(); + // Confirm delivery before the server disconnects its Windows pipe. + pipe.write_all(b"ack").await.unwrap(); + }); + pipe.connect().await?; + let mut request = [0; 5]; + pipe.read_exact(&mut request).await?; + assert_eq!(&request, b"admit"); + let identity = PipeClientIdentity::from_pipe(&pipe); + assert_reverted(); + pipe.write_all(&[1]).await?; + let mut ack = [0; 3]; + pipe.read_exact(&mut ack).await?; + assert_eq!(&ack, b"ack"); + client.await.unwrap(); + identity +} + +#[tokio::test] +async fn captures_primary_token_and_reverts_before_returning() { + let identity = tokio::time::timeout(Duration::from_secs(5), admission(SECURITY_IMPERSONATION)) + .await + .unwrap() + .unwrap(); + assert_eq!(identity.sid(), current_user_sid().unwrap()); + let mut kind: TOKEN_TYPE = 0; + let mut length = 0; + assert_ne!( + unsafe { + GetTokenInformation( + identity.primary_token().as_raw_handle(), + TokenType, + (&mut kind as *mut TOKEN_TYPE).cast(), + std::mem::size_of_val(&kind) as u32, + &mut length, + ) + }, + 0 + ); + assert_eq!(kind, TokenPrimary); + assert_reverted(); +} + +#[tokio::test] +async fn identification_only_client_cannot_supply_a_worker_token() { + assert!( + tokio::time::timeout(Duration::from_secs(5), admission(SECURITY_IDENTIFICATION)) + .await + .unwrap() + .is_err() + ); + assert_reverted(); +} diff --git a/crates/gphip/Cargo.toml b/crates/gphip/Cargo.toml index eeb2538..fa7419f 100644 --- a/crates/gphip/Cargo.toml +++ b/crates/gphip/Cargo.toml @@ -15,5 +15,11 @@ serde.workspace = true serde_json.workspace = true serde_urlencoded.workspace = true uuid = { workspace = true, features = ["v5"] } -uzers.workspace = true xmltree.workspace = true + +[target.'cfg(unix)'.dependencies] +uzers.workspace = true + +[target.'cfg(windows)'.dependencies] +windows = { version = "0.62", features = ["Win32_Networking_ActiveDirectory", "Win32_System_SystemInformation"] } +log.workspace = true diff --git a/crates/gphip/examples/windows_preview.rs b/crates/gphip/examples/windows_preview.rs new file mode 100644 index 0000000..6955b5f --- /dev/null +++ b/crates/gphip/examples/windows_preview.rs @@ -0,0 +1,12 @@ +//! Generate native Windows posture on Windows, or a Windows emulation preview elsewhere. +use gpapi::os_profile::{ClientOs, OsProfile}; +use gphip::{ReportContext, ReportInput}; + +fn main() -> anyhow::Result<()> { + let input = ReportInput { + profile: gpapi::os_profile::desktop::collect_profile(OsProfile::builder(ClientOs::Windows), None), + context: ReportContext::Preview, + }; + println!("{}", gphip::generate_report(&input)?); + Ok(()) +} diff --git a/crates/gphip/src/domain_macos.rs b/crates/gphip/src/domain_macos.rs new file mode 100644 index 0000000..f99b49c --- /dev/null +++ b/crates/gphip/src/domain_macos.rs @@ -0,0 +1,53 @@ +//! Native macOS Active Directory domain collection. +use gpapi::process::collection::CollectorCommands; +use std::{io, path::Path}; + +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + let Some(output) = commands.run_executable(Path::new("/usr/sbin/dsconfigad"), &["-show"])? else { + return Ok(String::new()); + }; + let text = String::from_utf8(output.stdout).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + // A nonzero exit status does not invalidate a reported domain. + Ok(parse_domain(&text)) +} + +fn parse_domain(output: &str) -> String { + output + .lines() + .find_map(|line| { + let (label, value) = line.split_once('=')?; + (label.trim() == "Active Directory Domain").then(|| value.trim().to_owned()) + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_ad_domain_without_using_other_domain_fields() { + assert_eq!( + parse_domain( + "Forest = forest.test\nActive Directory Domain = Corp.Example.test \t\r\nComputer Account = HOST$\n" + ), + "Corp.Example.test" + ); + assert_eq!( + parse_domain("Active Directory Domain = first.test\nActive Directory Domain = second.test\n"), + "first.test" + ); + } + + #[test] + fn unbound_or_empty_domain_stays_empty() { + for output in [ + "", + "Not bound to Active Directory\n", + "Forest = forest.test\n", + "Active Directory Domain = \t\n", + ] { + assert_eq!(parse_domain(output), ""); + } + } +} diff --git a/crates/gphip/src/domain_unix.rs b/crates/gphip/src/domain_unix.rs new file mode 100644 index 0000000..90ce326 --- /dev/null +++ b/crates/gphip/src/domain_unix.rs @@ -0,0 +1,120 @@ +//! Native Linux and BSD computer-domain collection. +use std::io; + +#[cfg(unix)] +use gpapi::process::collection::CollectorCommands; + +#[cfg(target_os = "linux")] +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + linux_domain(|program, args| read(commands, program, args)) +} + +#[cfg(target_os = "freebsd")] +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + read(commands, "hostname", &["-d"]) +} + +#[cfg(target_os = "openbsd")] +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + read(commands, "hostname", &[]).map(|hostname| hostname_domain(&hostname)) +} + +#[cfg(unix)] +fn read(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result { + let Some(output) = commands.run(program, args)? else { + return Ok(String::new()); + }; + let text = String::from_utf8(output.stdout).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + // A nonzero exit status does not invalidate a reported domain. + Ok(first_line(&text)) +} + +#[cfg(any(target_os = "linux", test))] +fn linux_domain(mut read: impl FnMut(&str, &[&str]) -> io::Result) -> io::Result { + let realm = read("realm", &["list", "--name-only"])?; + if !realm.is_empty() { + return Ok(realm); + } + read("dnsdomainname", &[]) +} + +fn first_line(output: &str) -> String { + output.lines().next().unwrap_or_default().trim().to_owned() +} + +#[cfg(any(target_os = "openbsd", test))] +fn hostname_domain(hostname: &str) -> String { + hostname + .split_once('.') + .map(|(_, domain)| domain) + .unwrap_or_default() + .to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(unix)] + #[test] + fn uses_first_stdout_line_even_with_nonzero_exit() { + let budget = gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(5)); + let commands = CollectorCommands::new(&budget); + let domain = read( + &commands, + "sh", + &["-c", "printf ' Corp.Example.test \\nsecond.test\\n'; exit 7"], + ) + .unwrap(); + assert_eq!(domain, "Corp.Example.test"); + } + + #[test] + fn linux_prefers_realm_and_only_queries_dns_when_empty() { + let realm = linux_domain(|program, args| { + assert_eq!(program, "realm"); + assert_eq!(args, ["list", "--name-only"]); + Ok("Corp.Example.test".into()) + }) + .unwrap(); + assert_eq!(realm, "Corp.Example.test"); + + let mut calls = Vec::new(); + let dns = linux_domain(|program, _| { + calls.push(program.to_string()); + if program == "realm" { + Ok(String::new()) + } else { + Ok("dns.example.test".into()) + } + }) + .unwrap(); + assert_eq!(calls, ["realm", "dnsdomainname"]); + assert_eq!(dns, "dns.example.test"); + assert_eq!(linux_domain(|_, _| Ok(String::new())).unwrap(), ""); + } + + #[test] + fn interrupted_collection_does_not_continue_to_dns() { + let result = linux_domain(|program, _| { + assert_eq!(program, "realm"); + Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")) + }); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Interrupted); + } + + #[test] + fn reads_only_first_line_and_preserves_domain_case() { + assert_eq!(first_line(" Corp.Example.test \r\nsecond.test\n"), "Corp.Example.test"); + assert_eq!(first_line("\nsecond.test\n"), ""); + assert_eq!(first_line(""), ""); + } + + #[test] + fn openbsd_uses_hostname_suffix_without_inventing_a_domain() { + assert_eq!(hostname_domain("host.Corp.Example.test"), "Corp.Example.test"); + assert_eq!(hostname_domain("host"), ""); + assert_eq!(hostname_domain("host."), ""); + assert_eq!(hostname_domain(""), ""); + } +} diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs index 06a2910..333b489 100644 --- a/crates/gphip/src/lib.rs +++ b/crates/gphip/src/lib.rs @@ -9,11 +9,20 @@ use gpapi::collection::{CollectionBudget, CollectionControl}; use gpapi::process::collection::CollectorCommands; use xmltree::Element; +#[cfg(target_os = "macos")] +mod domain_macos; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))] +mod domain_unix; #[cfg(target_os = "macos")] mod sentinel_macos; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] mod sentinel_unix; +#[cfg(windows)] +mod windows; +#[cfg(any(windows, test))] +mod windows_report; + pub const MAX_EDITED_REPORT_BYTES: usize = 48 * 1024; /// Validate an edited report before it is stored or used as a submission body. @@ -98,9 +107,9 @@ pub fn refresh_edited_report_with_control( control.check()?; let mut edited = validate_edited_report(edited_xml)?; let cookie_params = cookie_params(input); - let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity(); + let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity(control)?; control.check()?; - let domain = format!("{}.internal", identity.domain); + let domain = &identity.domain; let generate_time = get_current_time_components().0; for (name, value) in [ ("md5-sum", input.context.md5()), @@ -201,6 +210,27 @@ impl ReportContext { } } +/// Return a computer domain only for native profiles with a platform-specific source. +fn native_domain(profile: &OsProfile, control: &dyn CollectionControl) -> io::Result> { + control.check()?; + if !profile.is_native() { + return Ok(None); + } + #[cfg(windows)] + if profile.client_os() == ClientOs::Windows { + return windows::domain().map(Some); + } + #[cfg(target_os = "macos")] + if profile.client_os() == ClientOs::Mac { + return domain_macos::collect(&CollectorCommands::new(control)).map(Some); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + if profile.client_os() == ClientOs::Linux { + return domain_unix::collect(&CollectorCommands::new(control)).map(Some); + } + Ok(None) +} + /// Inputs collected by the caller for one HIP report. pub struct ReportInput { pub profile: OsProfile, @@ -214,14 +244,17 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result { } /// Identity-only maintenance report. This deliberately does not enumerate the -/// machine or execute posture collectors; addresses come from the session owner. -pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result { +/// interfaces or execute posture collectors; addresses come from the session owner. +/// Native profiles read the computer domain, consistent with generated and refreshed reports. +pub fn generate_identity_report(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result { let params = cookie_params(input); + let domain = + native_domain(&input.profile, control)?.unwrap_or_else(|| params.get("domain").cloned().unwrap_or_default()); let mut report = Element::new("hip-report"); for (name, value) in [ ("md5-sum", input.context.md5()), ("user-name", report_user_name(input, ¶ms)), - ("domain", params.get("domain").map(String::as_str).unwrap_or_default()), + ("domain", domain.as_str()), ("host-name", input.profile.computer()), ("host-id", input.profile.host_id()), ("ip-address", input.context.client_ip().unwrap_or_default()), @@ -241,10 +274,18 @@ pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result { } pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result { + Ok(generate_report_details(input, control)?.xml) +} + +pub fn generate_report_details( + input: &ReportInput, + control: &dyn CollectionControl, +) -> anyhow::Result { control.check()?; let cookie_params = cookie_params(input); let (generate_time, day, month, year) = get_current_time_components(); let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?; + let windows_updates = host_info.windows_updates.clone(); let template = HipReportTemplate { client_version: input.profile.client_version(), generate_time, @@ -255,9 +296,9 @@ pub fn generate_report_with_control(input: &ReportInput, control: &dyn Collectio host_info, md5: input.context.md5(), }; - let report = format_xml(&template.render()?)?; + let xml = format_xml(&template.render()?)?; control.check()?; - Ok(report) + Ok(gpapi::hip::HipReport { xml, windows_updates }) } fn cookie_params(input: &ReportInput) -> HashMap { @@ -338,6 +379,8 @@ struct HostInfo { clamav: Option, sentinel: Option, ufw: Option, + windows_categories: Option, + windows_updates: Option, } impl HostInfo { @@ -425,16 +468,6 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Domain belongs to the runtime user/session, not the simulated OS, so - /// it is sourced from the auth cookie when available. - fn get_domain(&self) -> String { - self - .cookie_params - .get("domain") - .map(|s| s.to_string()) - .unwrap_or_default() - } - /// Collect network interface information with fallback fn collect_network_interface(&self) -> NetworkInterface { match netdev::get_default_interface() { @@ -452,28 +485,28 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Single entry point for collecting host info — dispatches per-OS - /// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`. - fn collect_identity(&self) -> HostInfo { + fn collect_identity(&self, control: &dyn CollectionControl) -> io::Result { let runtime_iface = self.collect_network_interface(); let primary = self.adapt_primary_interface(&runtime_iface); let mut interfaces = vec![primary.clone()]; interfaces.extend(self.extra_interfaces(&primary)); - HostInfo { + Ok(HostInfo { os_vendor: self.profile.os_vendor().to_string(), os_version: self.profile.os_version().to_string(), host_id: self.profile.host_id().to_string(), host_name: self.profile.computer().to_string(), software_version: self.profile.software_version().to_string(), - domain: self.domain_for_profile(), + domain: self.domain_for_profile(control)?, network_interfaces: interfaces, defender: None, clamav: None, sentinel: None, ufw: None, - } + windows_categories: None, + windows_updates: None, + }) } /// Build the primary network interface with OS-appropriate naming and @@ -496,9 +529,12 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Additional interfaces appended after the primary. Only Windows - /// emits the software loopback interface in HIP reports. + /// Native Windows enumerates loopback adapters; Windows emulation retains its synthetic interface. fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec { + #[cfg(windows)] + if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() { + return windows::loopback_interfaces(); + } match self.profile.client_os() { ClientOs::Windows => vec![NetworkInterface { name: derive_windows_network_name(self.profile.host_id(), primary), @@ -511,20 +547,31 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Linux HIP reports omit the domain field; macOS/Windows include it - /// from the auth cookie. - fn domain_for_profile(&self) -> String { - match self.profile.client_os() { - ClientOs::Linux => String::new(), - ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => self.get_domain(), + fn domain_for_profile(&self, control: &dyn CollectionControl) -> io::Result { + if let Some(domain) = native_domain(self.profile, control)? { + return Ok(domain); } + let domain = match self.profile.client_os() { + ClientOs::Linux => "", + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => { + self.cookie_params.get("domain").map(String::as_str).unwrap_or_default() + } + }; + Ok(format!("{domain}.internal")) } fn collect(&self, control: &dyn CollectionControl) -> io::Result { control.check()?; - let mut info = self.collect_identity(); + let mut info = self.collect_identity(control)?; control.check()?; let commands = CollectorCommands::new(control); + #[cfg(windows)] + if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() { + let report = windows::collect(&commands, control)?; + info.windows_updates = Some(report.update_status()); + info.windows_categories = Some(report.render()?); + } + if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() { info.defender = detect_microsoft_defender(&commands)?; info.clamav = detect_clamav(&commands)?; @@ -570,11 +617,14 @@ fn detect_ufw(commands: &CollectorCommands<'_>) -> io::Result> { let Some(ufw) = commands.resolve("ufw") else { return Ok(None); }; + #[cfg(unix)] let output = if uzers::get_effective_uid() == 0 { commands.run_path(&ufw, &["status"])? } else { commands.run("sudo", &["-n", &ufw.to_string_lossy(), "status"])? }; + #[cfg(windows)] + let output = commands.run_path(&ufw, &["status"])?; let Some(output) = output.filter(|output| output.status.success()) else { return Ok(None); }; @@ -668,16 +718,20 @@ fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> } } -/// MAC address formatting per target OS. Windows uses hyphen separators; -/// Linux and macOS preserve the colon-separated form returned by the -/// platform. +/// Native Windows uses uppercase hex and hyphens. Windows emulation retains its +/// existing casing; other profiles preserve the platform's MAC representation. fn format_mac_for(profile: &OsProfile, mac: Option) -> Option { match profile.client_os() { - ClientOs::Windows => mac.map(|m| m.replace(':', "-")), + ClientOs::Windows if profile.is_native() => mac.map(format_native_windows_mac), + ClientOs::Windows => mac.map(|value| value.replace(':', "-")), ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => mac, } } +fn format_native_windows_mac(mac: String) -> String { + mac.replace(':', "-").to_ascii_uppercase() +} + // ============================================================================ // Utility Functions // ============================================================================ @@ -756,6 +810,17 @@ mod tests { gpapi::os_profile::desktop::collect_profile(OsProfileBuilder::new(client_os), None) } + #[test] + fn cancelled_identity_report_stops_before_domain_collection() { + let input = make_input(make_profile(ClientOs::Linux)); + let cancelled = || Err(io::Error::from(io::ErrorKind::Interrupted)); + let error = generate_identity_report(&input, &cancelled).unwrap_err(); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + io::ErrorKind::Interrupted + ); + } + #[test] fn identity_report_contains_session_identity_without_posture() { for os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] { @@ -766,7 +831,7 @@ mod tests { client_ipv6: Some("2001:db8::7".into()), md5: "identity-token".into(), }; - let xml = generate_identity_report(&input).unwrap(); + let xml = generate_identity_report(&input, &|| Ok(())).unwrap(); let root = Element::parse(xml.as_bytes()).unwrap(); assert_eq!( unique_child(&root, "user-name").unwrap().get_text().unwrap(), @@ -793,13 +858,39 @@ mod tests { } } + #[test] + fn native_windows_mac_casing_does_not_change_emulation_or_other_platforms() { + for (runtime_os, client_os, expected) in [ + (ClientOs::Windows, ClientOs::Windows, "AA-BB-CC-DD-EE-FF"), + (ClientOs::Mac, ClientOs::Windows, "aa-bb-cc-dd-ee-ff"), + (ClientOs::Linux, ClientOs::Windows, "aa-bb-cc-dd-ee-ff"), + (ClientOs::Mac, ClientOs::Mac, "aa:bb:cc:dd:ee:ff"), + (ClientOs::Linux, ClientOs::Linux, "aa:bb:cc:dd:ee:ff"), + ] { + let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot { + runtime_os, + identity: gpapi::os_profile::HostIdentity::application("host".into(), "id".into()), + os_version: "OS".into(), + software_version: "version".into(), + }); + assert_eq!( + format_mac_for(&profile, Some("aa:bb:cc:dd:ee:ff".into())).as_deref(), + Some(expected) + ); + assert_eq!(format_mac_for(&profile, Some(String::new())).as_deref(), Some("")); + assert_eq!(format_mac_for(&profile, None), None); + } + } + #[test] fn host_info_os_vendor_is_linux_for_linux_profile() { let input = make_input(make_profile(ClientOs::Linux)); let profile = make_profile(ClientOs::Linux); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.os_vendor, "Linux"); } @@ -810,7 +901,9 @@ mod tests { let profile = make_profile(ClientOs::Mac); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.os_vendor, "Apple"); } @@ -821,7 +914,9 @@ mod tests { let profile = make_profile(ClientOs::Windows); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.os_vendor, "Microsoft"); } @@ -832,7 +927,9 @@ mod tests { let profile = make_profile(ClientOs::Linux); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.host_id, profile.host_id()); } @@ -846,7 +943,9 @@ mod tests { let profile = make_profile(client_os); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.host_id, profile.host_id()); } @@ -867,11 +966,206 @@ mod tests { validate_edited_report(&report).unwrap(); } + #[test] + fn emulated_windows_uses_v4_categories_and_preserves_template_posture() { + use gpapi::os_profile::HostSnapshot; + let identity = gpapi::os_profile::desktop::identity_from_parts( + "emulated-device".into(), + "emulated-id".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ); + let profile = OsProfileBuilder::new(ClientOs::Windows).build(HostSnapshot { + runtime_os: ClientOs::Mac, + identity, + os_version: "macOS".into(), + software_version: "15.0".into(), + }); + assert!(!profile.is_native()); + let mut input = make_input(profile); + input.context = ReportContext::Connected { + cookie: "domain=emulated-domain".into(), + client_ip: None, + client_ipv6: None, + md5: "test-digest".into(), + }; + let report = generate_report(&input).unwrap(); + let root = validate_edited_report(&report).unwrap(); + assert_eq!( + unique_child(&root, "domain").unwrap().get_text().unwrap(), + "emulated-domain.internal" + ); + assert!(report.contains("emulated-domain.internal")); + let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap(); + assert_eq!( + unique_child(&identity, "domain").unwrap().get_text().unwrap(), + "emulated-domain" + ); + let categories = unique_child(&root, "categories").unwrap(); + let names = categories + .children + .iter() + .filter_map(xmltree::XMLNode::as_element) + .filter_map(|entry| entry.attributes.get("name").map(String::as_str)) + .collect::>(); + assert_eq!( + names, + [ + "host-info", + "anti-malware", + "disk-backup", + "disk-encryption", + "firewall", + "patch-management", + "data-loss-prevention" + ] + ); + assert!(report.contains("McAfee VirusScan Enterprise")); + assert!(report.contains("McAfee ePolicy Orchestrator Agent")); + assert_eq!(report.matches("prodType=\"3\"").count(), 2); + assert!(report.contains("C:\\")); + assert!(report.contains("encrypted")); + assert!(report.contains("")); + } + + #[test] + fn emulated_unix_domains_keep_existing_cookie_and_suffix_behavior() { + for client_os in [ClientOs::Mac, ClientOs::Linux] { + let expected_domain = if client_os == ClientOs::Linux { + ".internal" + } else { + "emulated-domain.internal" + }; + let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot { + runtime_os: ClientOs::Windows, + identity: gpapi::os_profile::HostIdentity::from_parts( + "host".into(), + "id".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ), + os_version: "Windows".into(), + software_version: "11".into(), + }); + assert!(!profile.is_native()); + let mut input = make_input(profile); + input.context = ReportContext::Connected { + cookie: "domain=emulated-domain".into(), + client_ip: None, + client_ipv6: None, + md5: "test-digest".into(), + }; + let xml = generate_report(&input).unwrap(); + let generated = validate_edited_report(&xml).unwrap(); + let refreshed = validate_edited_report(&refresh_edited_report(&xml, &input).unwrap()).unwrap(); + for report in [generated, refreshed] { + assert_eq!( + unique_child(&report, "domain").unwrap().get_text().unwrap(), + expected_domain + ); + assert_eq!( + unique_child(host_info(&report).unwrap(), "domain") + .unwrap() + .get_text() + .unwrap(), + expected_domain + ); + } + let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap(); + assert_eq!( + unique_child(&identity, "domain").unwrap().get_text().unwrap(), + "emulated-domain" + ); + } + } + + #[test] + fn native_domain_is_shared_by_generated_edited_and_identity_reports() { + let client_os = if cfg!(windows) { + ClientOs::Windows + } else if cfg!(target_os = "macos") { + ClientOs::Mac + } else { + ClientOs::Linux + }; + let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot { + runtime_os: client_os, + identity: gpapi::os_profile::HostIdentity::from_parts( + "host".into(), + "id".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ), + os_version: "Windows".into(), + software_version: "11".into(), + }); + let mut input = make_input(profile); + input.context = ReportContext::Connected { + cookie: "domain=auth-cookie-must-not-be-used.invalid".into(), + client_ip: None, + client_ipv6: None, + md5: "test-digest".into(), + }; + let expected = native_domain(&input.profile, &CollectionBudget::new(Duration::from_secs(10))) + .unwrap() + .unwrap(); + let params = cookie_params(&input); + let mut host_info = HostInfoCollector::new(&input.profile, &input, ¶ms) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); + // Render the identity path without executing the product collectors. + if client_os == ClientOs::Windows { + host_info.windows_categories = Some(windows_report::WindowsReport::default().render().unwrap()); + } + let (generate_time, day, month, year) = get_current_time_components(); + let xml = HipReportTemplate { + client_version: input.profile.client_version(), + generate_time, + day, + month, + year, + user_name: "test-user", + host_info, + md5: "test-digest", + } + .render() + .unwrap(); + let generated = validate_edited_report(&xml).unwrap(); + let mut stale = generated.clone(); + set_field(&mut stale, "domain", "stale.internal").unwrap(); + set_field(host_info_mut(&mut stale).unwrap(), "domain", "stale.internal").unwrap(); + let refreshed = refresh_edited_report(&write_xml(&stale).unwrap(), &input).unwrap(); + let refreshed = validate_edited_report(&refreshed).unwrap(); + let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap(); + for report in [&generated, &refreshed, &identity] { + assert_eq!( + unique_child(report, "domain") + .unwrap() + .get_text() + .unwrap_or_default() + .as_ref(), + expected + ); + } + for mut report in [generated, refreshed] { + assert_eq!( + unique_child(host_info_mut(&mut report).unwrap(), "domain") + .unwrap() + .get_text() + .unwrap_or_default() + .as_ref(), + expected + ); + } + } + #[test] fn mac_report_renders_detected_sentinel_products() { let input = make_input(make_profile(ClientOs::Mac)); let cookie_params = HashMap::new(); - let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity(); + let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); host_info.sentinel = Some(SentinelInfo { version: "25.3.4.8365".to_string(), real_time_protection: true, @@ -902,7 +1196,9 @@ mod tests { fn linux_report_renders_detected_sentinel_antimalware() { let input = make_input(make_profile(ClientOs::Linux)); let cookie_params = HashMap::new(); - let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity(); + let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); host_info.sentinel = Some(SentinelInfo { version: "25.2.2.14".to_string(), real_time_protection: true, diff --git a/crates/gphip/src/windows.rs b/crates/gphip/src/windows.rs new file mode 100644 index 0000000..e53649f --- /dev/null +++ b/crates/gphip/src/windows.rs @@ -0,0 +1,96 @@ +//! Public JSON adapter and native Windows host identity. +use super::windows_report::WindowsReport; +use gpapi::{collection::CollectionControl, process::collection::CollectorCommands}; +use std::io; + +pub(super) fn collect(commands: &CollectorCommands<'_>, control: &dyn CollectionControl) -> io::Result { + let executable = std::env::current_exe()?; + let helper = executable + .parent() + .ok_or_else(|| io::Error::other("Application directory is unavailable"))? + .join("gp-posture.exe"); + let output = commands + .run_executable(&helper, &[])? + .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Windows posture helper is not installed"))?; + if !output.status.success() { + return Err(io::Error::other("Windows posture collection failed")); + } + let report: WindowsReport = serde_json::from_slice(&output.stdout).map_err(io::Error::other)?; + for category in &report.unavailable { + log::warn!("Windows HIP data unavailable: {category}"); + } + control.check()?; + Ok(report) +} + +/// Windows supplies the loopback adapter's real ID through GetAdaptersAddresses (via netdev). +pub(super) fn loopback_interfaces() -> Vec { + netdev::get_interfaces() + .into_iter() + .filter(|interface| interface.is_loopback()) + .map(|interface| { + super::NetworkInterface::new(interface.name.clone(), interface.description.unwrap_or(interface.name)) + .with_mac(Some( + interface + .mac_addr + .map(|mac| super::format_native_windows_mac(mac.address())) + .unwrap_or_default(), + )) + .with_ipv4(interface.ipv4.first().map(|ip| ip.addr().to_string())) + .with_ipv6(interface.ipv6.first().map(|ip| ip.addr().to_string())) + }) + .collect() +} + +/// Primary DNS domain, or physical DNS domain if the primary query fails. +pub(super) fn domain() -> io::Result { + use windows::Win32::{ + Networking::ActiveDirectory::{ + DSROLE_PRIMARY_DOMAIN_INFO_BASIC, DsRoleFreeMemory, DsRoleGetPrimaryDomainInformation, + DsRolePrimaryDomainInfoBasic, + }, + System::SystemInformation::{ComputerNamePhysicalDnsDomain, GetComputerNameExW}, + }; + use windows::core::PWSTR; + + let mut buffer = std::ptr::null_mut(); + // SAFETY: a null server selects this computer; Windows allocates and owns the returned structure. + let status = unsafe { DsRoleGetPrimaryDomainInformation(None, DsRolePrimaryDomainInfoBasic, &mut buffer) }; + if status == 0 && !buffer.is_null() { + // SAFETY: the requested information level returns this structure. Copy the string before freeing its allocation. + let result = unsafe { copy_domain_name((*buffer.cast::()).DomainNameDns) }; + unsafe { DsRoleFreeMemory(buffer.cast()) }; + return result; + } + + let mut name = [0u16; 257]; + let mut size = name.len() as u32; + // SAFETY: the writable UTF-16 buffer and its character count remain valid for the call. + unsafe { GetComputerNameExW(ComputerNamePhysicalDnsDomain, Some(PWSTR(name.as_mut_ptr())), &mut size) } + .map_err(io::Error::other)?; + String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} + +// SAFETY: a non-null name must point to a live NUL-terminated UTF-16 string. +unsafe fn copy_domain_name(name: windows::core::PWSTR) -> io::Result { + if name.is_null() { + // A successful primary-domain query with no DNS name is an empty domain, including workgroup hosts. + return Ok(String::new()); + } + unsafe { name.to_string() }.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::core::PWSTR; + #[test] + fn primary_domain_preserves_dns_name_and_empty_workgroup_domain() { + let mut name: Vec = "Lab.Example.test\0".encode_utf16().collect(); + assert_eq!( + unsafe { copy_domain_name(PWSTR(name.as_mut_ptr())) }.unwrap(), + "Lab.Example.test" + ); + assert_eq!(unsafe { copy_domain_name(PWSTR::null()) }.unwrap(), ""); + } +} diff --git a/crates/gphip/src/windows_report.rs b/crates/gphip/src/windows_report.rs new file mode 100644 index 0000000..00579c5 --- /dev/null +++ b/crates/gphip/src/windows_report.rs @@ -0,0 +1,323 @@ +//! Windows posture facts and their HIP v4 representation. +use serde::Deserialize; +use xmltree::{Element, XMLNode}; + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct WindowsReport { + pub anti_malware: Vec, + pub disk_backup: Vec, + pub disk_encryption: Vec, + pub firewall: Vec, + pub patch_management: Vec, + pub missing_patches: Option>, + pub patches_checked_at: Option, + pub unavailable: Vec, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct Product { + pub name: String, + pub vendor: String, + pub version: String, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct AntiMalware { + pub product: Product, + pub enabled: Option, + pub definition_version: Option, + pub engine_version: Option, + pub definition_date: Option, + pub last_scan: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct Backup { + pub product: Product, + pub last_backup: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct Encryption { + pub product: Product, + pub drives: Vec, +} + +#[derive(Deserialize)] +pub(super) struct Drive { + pub name: String, + pub conversion_status: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct ProductState { + pub product: Product, + pub enabled: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct MissingPatch { + pub title: String, + pub description: String, + pub kb: String, + pub category: String, + pub vendor: String, + pub msrc_severity: Option, +} + +impl MissingPatch { + fn severity(&self) -> i32 { + match self.msrc_severity.as_deref().map(str::to_ascii_lowercase).as_deref() { + Some("critical") => 3, + Some("important") => 2, + Some("moderate") => 1, + Some("low") => 0, + _ => -1, + } + } +} + +impl WindowsReport { + pub(super) fn update_status(&self) -> gpapi::hip::WindowsUpdateStatus { + let mut status = gpapi::hip::WindowsUpdateStatus::default(); + if self.missing_patches.is_some() { + status.checked_at = self.patches_checked_at; + } else { + status.omitted_snapshot_at = self.patches_checked_at; + } + status + } + + pub fn render(&self) -> std::io::Result { + let mut categories = Vec::new(); + categories.push(category( + "anti-malware", + self.anti_malware.iter().map(|item| { + let mut info = product(&item.product); + let prod = info.get_mut_child("Prod").unwrap(); + prod.attributes.insert("prodType".into(), "3".into()); + prod.attributes.insert("osType".into(), "1".into()); + for (name, value) in [("defver", &item.definition_version), ("engver", &item.engine_version)] { + if let Some(value) = value { + prod.attributes.insert(name.into(), value.clone()); + } + } + if let Some(date) = item + .definition_date + .as_deref() + .and_then(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()) + { + use chrono::Datelike; + for (name, value) in [ + ("dateyear", date.year().to_string()), + ("datemon", date.month().to_string()), + ("dateday", date.day().to_string()), + ] { + prod.attributes.insert(name.into(), value); + } + } + field(&mut info, "real-time-protection", yes_no(item.enabled)); + field( + &mut info, + "last-full-scan-time", + item.last_scan.as_deref().unwrap_or("n/a"), + ); + info + }), + )); + categories.push(category( + "disk-backup", + self.disk_backup.iter().map(|item| { + let mut info = product(&item.product); + field( + &mut info, + "last-backup-time", + item.last_backup.as_deref().unwrap_or("n/a"), + ); + info + }), + )); + categories.push(category( + "disk-encryption", + self.disk_encryption.iter().map(|item| { + let mut info = product(&item.product); + let mut drives = Element::new("drives"); + for drive in &item.drives { + let mut entry = Element::new("entry"); + field(&mut entry, "drive-name", &drive.name); + field( + &mut entry, + "enc-state", + match drive.conversion_status { + Some(0) => "unencrypted", + Some(1) => "encrypted", + _ => "n/a", + }, + ); + drives.children.push(XMLNode::Element(entry)); + } + info.children.push(XMLNode::Element(drives)); + info + }), + )); + categories.push(category("firewall", self.firewall.iter().map(state))); + let mut patches = category("patch-management", self.patch_management.iter().map(state)); + // A failed search is not evidence that the machine has no missing updates. + if let Some(missing) = &self.missing_patches { + let mut list = Element::new("missing-patches"); + for patch in missing { + let mut entry = Element::new("entry"); + field(&mut entry, "title", &patch.title); + field(&mut entry, "description", &patch.description); + field(&mut entry, "product", ""); + field(&mut entry, "vendor", &patch.vendor); + field(&mut entry, "info-url", ""); + field(&mut entry, "kb-article-id", &patch.kb); + field(&mut entry, "security-bulletin-id", ""); + field(&mut entry, "severity", &patch.severity().to_string()); + field(&mut entry, "category", &patch.category); + field(&mut entry, "is-installed", "no"); + list.children.push(XMLNode::Element(entry)); + } + patches.children.push(XMLNode::Element(list)); + } + categories.push(patches); + let mut output = Vec::new(); + for category in categories { + category + .write_with_config( + &mut output, + xmltree::EmitterConfig::new().write_document_declaration(false), + ) + .map_err(std::io::Error::other)?; + } + String::from_utf8(output).map_err(std::io::Error::other) + } +} + +fn yes_no(enabled: Option) -> &'static str { + match enabled { + Some(true) => "yes", + Some(false) => "no", + None => "n/a", + } +} + +fn field(parent: &mut Element, name: &str, value: &str) { + let mut child = Element::new(name); + child.children.push(XMLNode::Text(value.into())); + parent.children.push(XMLNode::Element(child)); +} + +fn product(product: &Product) -> Element { + let mut info = Element::new("ProductInfo"); + let mut prod = Element::new("Prod"); + for (name, value) in [ + ("name", &product.name), + ("vendor", &product.vendor), + ("version", &product.version), + ] { + if !value.is_empty() { + prod.attributes.insert(name.into(), value.clone()); + } + } + info.children.push(XMLNode::Element(prod)); + info +} + +fn state(item: &ProductState) -> Element { + let mut info = product(&item.product); + field(&mut info, "is-enabled", yes_no(item.enabled)); + info +} + +fn category(name: &str, products: impl Iterator) -> Element { + let mut category = Element::new("entry"); + category.attributes.insert("name".into(), name.into()); + let mut list = Element::new("list"); + for product in products { + let mut entry = Element::new("entry"); + entry.children.push(XMLNode::Element(product)); + list.children.push(XMLNode::Element(entry)); + } + category.children.push(XMLNode::Element(list)); + category +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn omitted_snapshot_can_be_refreshed_without_claiming_patch_details() { + let mut report = WindowsReport::default(); + assert_eq!(report.update_status().refresh_cursor(), None); + report.patches_checked_at = Some(123); + let status = report.update_status(); + assert_eq!(status.checked_at, None); + assert_eq!(status.refresh_cursor(), Some(123)); + assert!(!report.render().unwrap().contains("missing-patches")); + report.missing_patches = Some(Vec::new()); + assert_eq!(report.update_status().checked_at, Some(123)); + assert_eq!(report.update_status().refresh_cursor(), Some(123)); + } + + #[test] + fn real_posture_preserves_unavailable_values_and_escapes_product_text() { + let report: WindowsReport = serde_json::from_str( + r#"{ + "anti_malware":[{"product":{"name":"Agent & Endpoint","version":"25.1"},"enabled":true}], + "disk_encryption":[{"product":{"name":"BitLocker"},"drives":[{"name":"C:\\","conversion_status":0}]}], + "missing_patches":null + }"#, + ) + .unwrap(); + let xml = report.render().unwrap(); + let root = Element::parse(format!("{xml}").as_bytes()).unwrap(); + assert_eq!(root.children.len(), 5); + assert!(xml.contains("Agent & Endpoint")); + assert!(xml.contains("unencrypted")); + assert!(xml.contains("n/a")); + assert!(!xml.contains("missing-patches")); + assert!(!xml.contains("McAfee")); + } + + #[test] + fn missing_patch_severity_is_unknown_without_an_observed_msrc_rating() { + for category in ["driver", "update", "security_update", "critical_update"] { + let mut patch = MissingPatch { + category: category.into(), + ..Default::default() + }; + assert_eq!(patch.severity(), -1); + patch.msrc_severity = Some("Critical".into()); + assert_eq!(patch.severity(), 3); + patch.msrc_severity = Some("Unrecognized".into()); + assert_eq!(patch.severity(), -1); + } + } + + #[test] + fn successful_update_search_distinguishes_empty_and_missing_updates() { + let mut report = WindowsReport { + missing_patches: Some(vec![]), + ..Default::default() + }; + assert!(report.render().unwrap().contains("")); + report.missing_patches = Some(vec![MissingPatch { + title: "Security update".into(), + kb: "123".into(), + ..Default::default() + }]); + let xml = report.render().unwrap(); + assert!(xml.contains("123")); + assert!(xml.contains("no")); + } +} diff --git a/crates/gphip/templates/hip_report.xml b/crates/gphip/templates/hip_report.xml index 795f546..c625a70 100644 --- a/crates/gphip/templates/hip_report.xml +++ b/crates/gphip/templates/hip_report.xml @@ -2,7 +2,7 @@ {{ md5 }} {{ user_name }} - {{ host_info.domain }}.internal + {{ host_info.domain }} {{ host_info.host_name }} {{ host_info.host_id }} {{ host_info.default_ipv4() }} @@ -14,7 +14,7 @@ {{ client_version }} {{ host_info.os_version }} {{ host_info.os_vendor }} - {{ host_info.domain }}.internal + {{ host_info.domain }} {{ host_info.host_name }} {{ host_info.host_id }} @@ -39,103 +39,11 @@ {% if host_info.os_vendor == "Microsoft" -%} - - - - - - - yes - {{ generate_time }} - - - - - - - no - n/a - - - - - - - - - - - yes - {{ generate_time }} - - - - - - - no - n/a - - - - - - - - - - - n/a - - - - - - - - - - - - - C:\\ - full - - - - - - - - - - - - - yes - - - - - - - - - - - yes - - - - - - - yes - - - - - + {% if let Some(categories) = &host_info.windows_categories -%} + {{ categories|safe }} + {% else -%} + {% include "windows_emulation.xml" %} + {% endif -%} {% elif host_info.os_vendor == "Apple" -%} diff --git a/crates/gphip/templates/windows_emulation.xml b/crates/gphip/templates/windows_emulation.xml new file mode 100644 index 0000000..dfa0827 --- /dev/null +++ b/crates/gphip/templates/windows_emulation.xml @@ -0,0 +1,77 @@ + + + + + + + yes + {{ generate_time }} + + + + + + + no + n/a + + + + + + + + + + + n/a + + + + + + + + + + + + + C:\ + encrypted + + + + + + + + + + + + + yes + + + + + + + + + + + yes + + + + + + + yes + + + + + diff --git a/crates/gpvpnc/Cargo.toml b/crates/gpvpnc/Cargo.toml index 2113cfa..1e2b9fd 100644 --- a/crates/gpvpnc/Cargo.toml +++ b/crates/gpvpnc/Cargo.toml @@ -5,5 +5,21 @@ version.workspace = true edition.workspace = true license.workspace = true -[target.'cfg(target_os = "macos")'.dependencies] +[target.'cfg(any(target_os = "macos", windows))'.dependencies] log.workspace = true + +[target.'cfg(windows)'.dependencies] +ipnet = { version = "2", features = ["serde"] } +base64.workspace = true +serde_json.workspace = true +serde.workspace = true +winreg = "0.56" +uuid = { workspace = true, features = ["v4"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Threading"] } + +[dev-dependencies] +ipnet = "2" + +[target.'cfg(windows)'.dev-dependencies] +tempfile.workspace = true +windows-sys = { version = "0.61", features = ["Win32_System_LibraryLoader"] } diff --git a/crates/gpvpnc/src/lib.rs b/crates/gpvpnc/src/lib.rs index ed50e7d..4ac09f0 100644 --- a/crates/gpvpnc/src/lib.rs +++ b/crates/gpvpnc/src/lib.rs @@ -1,2 +1,7 @@ #[cfg(target_os = "macos")] pub mod macos; +#[cfg(windows)] +pub mod windows; +#[cfg(all(test, not(windows)))] +#[path = "windows/configuration.rs"] +mod windows_configuration; diff --git a/crates/gpvpnc/src/windows/configuration.rs b/crates/gpvpnc/src/windows/configuration.rs new file mode 100644 index 0000000..629870f --- /dev/null +++ b/crates/gpvpnc/src/windows/configuration.rs @@ -0,0 +1,249 @@ +//! Convert OpenConnect's normal configuration callback into a Windows network plan. +use ipnet::IpNet; +use std::{collections::HashMap, io, net::IpAddr}; + +#[derive(Debug)] +pub(super) struct Configuration { + pub interface: u32, + pub gateway: IpAddr, + pub addresses: Vec, + pub mtu: Option, + pub includes: Vec, + pub excludes: Vec, + pub servers: Vec, + pub domains: Vec, + pub split_dns: Vec, +} + +fn invalid(message: impl Into) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message.into()) +} +impl Configuration { + pub fn parse(environment: &[(String, Option)]) -> io::Result { + let values: HashMap<_, _> = environment + .iter() + .filter_map(|(key, value)| value.as_deref().map(|value| (key.as_str(), value))) + .collect(); + let required = |key: &str| { + values + .get(key) + .copied() + .filter(|value| !value.is_empty()) + .ok_or_else(|| invalid(format!("Missing VPN configuration: {key}"))) + }; + let interface: u32 = required("TUNIDX")? + .parse() + .map_err(|_| invalid("Invalid VPN interface index"))?; + if interface == 0 { + return Err(invalid("VPN interface index is zero")); + } + let gateway = required("VPNGATEWAY")? + .parse() + .map_err(|_| invalid("Invalid VPN gateway address"))?; + let mut addresses = Vec::new(); + if let Some(address) = values.get("INTERNAL_IP4_ADDRESS") { + let prefix = values.get("INTERNAL_IP4_NETMASKLEN").copied().unwrap_or("32"); + let network: IpNet = format!("{address}/{prefix}") + .parse() + .map_err(|_| invalid("Invalid VPN IPv4 address or prefix"))?; + if !matches!(network, IpNet::V4(_)) { + return Err(invalid("VPN IPv4 address has the wrong family")); + } + addresses.push(network); + } + if let Some(address) = values.get("INTERNAL_IP6_ADDRESS") { + let prefix = values + .get("INTERNAL_IP6_NETMASK") + .and_then(|value| value.rsplit_once('/')) + .map(|(_, prefix)| prefix) + .unwrap_or("128"); + let network: IpNet = format!("{address}/{prefix}") + .parse() + .map_err(|_| invalid("Invalid VPN IPv6 address or prefix"))?; + if !matches!(network, IpNet::V6(_)) { + return Err(invalid("VPN IPv6 address has the wrong family")); + } + addresses.push(network); + } + if addresses.is_empty() { + return Err(invalid("The VPN did not assign an IP address")); + } + let mtu = values + .get("INTERNAL_IP4_MTU") + .filter(|value| !value.is_empty()) + .map(|value| value.parse::().map_err(|_| invalid("Invalid VPN MTU"))) + .transpose()? + .filter(|mtu| *mtu != 0); + let mut includes = Vec::new(); + let mut excludes = Vec::new(); + for (family, prefix) in [(4, "CISCO_SPLIT"), (6, "CISCO_IPV6_SPLIT")] { + if !addresses + .iter() + .any(|address| address.addr().is_ipv4() == (family == 4)) + { + continue; + } + let included = routes(&values, &format!("{prefix}_INC"), family)?; + if included.is_empty() { + // Preserve the physical default route, using the two more-specific halves. + let defaults: &[&str] = if family == 4 { + &["0.0.0.0/1", "128.0.0.0/1"] + } else { + &["::/1", "8000::/1"] + }; + includes.extend(defaults.iter().map(|route| route.parse::().unwrap())); + } else { + includes.extend(included); + } + excludes.extend(routes(&values, &format!("{prefix}_EXC"), family)?); + } + let mut servers = values + .get("INTERNAL_IP4_DNS") + .into_iter() + .flat_map(|text| text.split_whitespace()) + .map(|address| address.parse().map_err(|_| invalid("Invalid VPN DNS server"))) + .collect::>>()?; + let advertised_dns = !servers.is_empty(); + servers.retain(|server| { + addresses + .iter() + .any(|address| address.addr().is_ipv4() == server.is_ipv4()) + }); + if advertised_dns && servers.is_empty() { + return Err(invalid("No VPN DNS server matches an assigned address family")); + } + let domains = names(values.get("CISCO_DEF_DOMAIN").copied().unwrap_or("")); + let split_dns = names(values.get("CISCO_SPLIT_DNS").copied().unwrap_or("")); + Ok(Self { + interface, + gateway, + addresses, + mtu, + includes, + excludes, + servers, + domains, + split_dns, + }) + } +} +fn names(text: &str) -> Vec { + text + .split(|ch: char| ch == ',' || ch.is_whitespace()) + .filter(|part| !part.is_empty()) + .map(str::to_owned) + .collect() +} +fn routes(values: &HashMap<&str, &str>, key: &str, family: u8) -> io::Result> { + let count = values + .get(key) + .map(|value| { + value + .parse::() + .map_err(|_| invalid(format!("Invalid {key} count"))) + }) + .transpose()? + .unwrap_or(0); + (0..count) + .map(|index| { + let address = values + .get(format!("{key}_{index}_ADDR").as_str()) + .ok_or_else(|| invalid(format!("Missing {key} address")))?; + let prefix = values + .get(format!("{key}_{index}_MASKLEN").as_str()) + .ok_or_else(|| invalid(format!("Missing {key} prefix")))?; + let route: IpNet = format!("{address}/{prefix}") + .parse() + .map_err(|_| invalid(format!("Invalid {key} route")))?; + if route.addr().is_ipv4() != (family == 4) { + return Err(invalid(format!("Wrong {key} route family"))); + } + Ok(route.trunc()) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + fn environment(extra: &[(&str, &str)]) -> Vec<(String, Option)> { + [ + ("TUNIDX", "16"), + ("VPNGATEWAY", "198.51.100.1"), + ("INTERNAL_IP4_ADDRESS", "10.20.30.4"), + ] + .into_iter() + .chain(extra.iter().copied()) + .map(|(key, value)| (key.into(), Some(value.into()))) + .collect() + } + #[test] + fn full_tunnel_keeps_assigned_addresses_and_routes_both_families() { + let plan = Configuration::parse(&environment(&[ + ("INTERNAL_IP4_NETMASKLEN", "24"), + ("INTERNAL_IP6_ADDRESS", "fd00::4"), + ("INTERNAL_IP6_NETMASK", "fd00::4/64"), + ("INTERNAL_IP4_MTU", "1406"), + ("INTERNAL_IP4_DNS", "10.20.30.1 fd00::1"), + ])) + .unwrap(); + assert_eq!( + plan.addresses.iter().map(ToString::to_string).collect::>(), + ["10.20.30.4/24", "fd00::4/64"] + ); + assert_eq!(plan.includes.len(), 4); + assert_eq!(plan.servers.len(), 2); + assert_eq!(plan.mtu, Some(1406)); + assert_eq!(plan.interface, 16); + assert_eq!(plan.gateway.to_string(), "198.51.100.1"); + } + #[test] + fn split_routes_and_dns_preserve_gateway_configuration() { + let plan = Configuration::parse(&environment(&[ + ("CISCO_SPLIT_INC", "1"), + ("CISCO_SPLIT_INC_0_ADDR", "172.16.5.9"), + ("CISCO_SPLIT_INC_0_MASKLEN", "16"), + ("CISCO_SPLIT_EXC", "1"), + ("CISCO_SPLIT_EXC_0_ADDR", "172.16.10.0"), + ("CISCO_SPLIT_EXC_0_MASKLEN", "24"), + ("CISCO_DEF_DOMAIN", "corp.example"), + ("CISCO_SPLIT_DNS", "corp.example, internal.example"), + ])) + .unwrap(); + assert_eq!( + plan.includes.iter().map(ToString::to_string).collect::>(), + ["172.16.0.0/16"] + ); + assert_eq!(plan.excludes[0].to_string(), "172.16.10.0/24"); + assert_eq!(plan.domains, ["corp.example"]); + assert_eq!(plan.split_dns, ["corp.example", "internal.example"]); + } + #[test] + fn unassigned_address_family_does_not_install_routes_or_resolvers() { + let plan = Configuration::parse(&environment(&[ + ("CISCO_IPV6_SPLIT_INC", "1"), + ("CISCO_IPV6_SPLIT_INC_0_ADDR", "fd00::"), + ("CISCO_IPV6_SPLIT_INC_0_MASKLEN", "64"), + ("INTERNAL_IP4_DNS", "10.20.30.1 fd00::1"), + ])) + .unwrap(); + assert!(plan.includes.iter().all(|route| route.addr().is_ipv4())); + assert_eq!( + plan.servers.iter().map(ToString::to_string).collect::>(), + ["10.20.30.1"] + ); + assert!(Configuration::parse(&environment(&[("INTERNAL_IP4_DNS", "fd00::1")])).is_err()); + } + + #[test] + fn malformed_network_data_is_rejected_before_changes() { + for extra in [ + vec![("TUNIDX", "0")], + vec![("INTERNAL_IP4_NETMASKLEN", "99")], + vec![("INTERNAL_IP4_DNS", "not-an-address")], + vec![("CISCO_SPLIT_INC", "1")], + ] { + assert!(Configuration::parse(&environment(&extra)).is_err()); + } + } +} diff --git a/crates/gpvpnc/src/windows/dns-policy.ps1 b/crates/gpvpnc/src/windows/dns-policy.ps1 new file mode 100644 index 0000000..d78d4c6 --- /dev/null +++ b/crates/gpvpnc/src/windows/dns-policy.ps1 @@ -0,0 +1,18 @@ +$ErrorActionPreference = 'Stop' +$request = [Console]::In.ReadToEnd() | ConvertFrom-Json +switch ($request.operation) { + 'add' { + Add-DnsClientNrptRule -Namespace ([string[]]$request.namespaces) -NameServers ([string[]]$request.servers) -Comment $request.tag | Out-Null + } + 'remove' { + Get-DnsClientNrptRule | Where-Object { $_.Comment -eq $request.tag } | ForEach-Object { + Remove-DnsClientNrptRule -Name $_.Name -Force + } + } + 'clear-stale' { + Get-DnsClientNrptRule | Where-Object { $_.Comment -like 'GPConnect:*' } | ForEach-Object { + Remove-DnsClientNrptRule -Name $_.Name -Force + } + } + default { throw 'Invalid DNS policy operation' } +} diff --git a/crates/gpvpnc/src/windows/dns.rs b/crates/gpvpnc/src/windows/dns.rs new file mode 100644 index 0000000..729d9dd --- /dev/null +++ b/crates/gpvpnc/src/windows/dns.rs @@ -0,0 +1,178 @@ +//! Adapter DNS settings and Windows name-resolution policy scoped to this connection. +use super::configuration::Configuration; +use base64::Engine; +use serde_json::json; +use std::{ + io::{self, Write}, + os::windows::process::CommandExt, + process::{Command, Stdio}, +}; +use windows_sys::{ + Win32::{ + NetworkManagement::{IpHelper::*, Ndis::NET_LUID_LH}, + System::Threading::CREATE_NO_WINDOW, + }, + core::GUID, +}; + +struct Snapshot { + domain: String, + search: String, +} +pub(super) struct Installed { + guid: GUID, + snapshot: Option, + tag: Option, +} +fn check(status: u32) -> io::Result<()> { + if status == 0 { + Ok(()) + } else { + Err(io::Error::from_raw_os_error(status as i32)) + } +} +fn wide(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() +} +unsafe fn string(pointer: *const u16) -> String { + if pointer.is_null() { + return String::new(); + } + unsafe { + let mut length = 0; + while *pointer.add(length) != 0 { + length += 1; + } + String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length)) + } +} +impl Snapshot { + fn capture(guid: GUID) -> io::Result { + let mut settings = DNS_INTERFACE_SETTINGS { + Version: DNS_INTERFACE_SETTINGS_VERSION1, + ..Default::default() + }; + check(unsafe { GetInterfaceDnsSettings(guid, &mut settings) })?; + let snapshot = unsafe { + Self { + domain: string(settings.Domain), + search: string(settings.SearchList), + } + }; + unsafe { + FreeInterfaceDnsSettings(&mut settings); + } + Ok(snapshot) + } + fn write(&self, guid: GUID) -> io::Result<()> { + let (mut domain, mut search) = (wide(&self.domain), wide(&self.search)); + let settings = DNS_INTERFACE_SETTINGS { + Version: DNS_INTERFACE_SETTINGS_VERSION1, + Flags: (DNS_SETTING_DOMAIN | DNS_SETTING_SEARCHLIST) as u64, + Domain: domain.as_mut_ptr(), + SearchList: search.as_mut_ptr(), + ..Default::default() + }; + check(unsafe { SetInterfaceDnsSettings(guid, &settings) }) + } +} +impl Installed { + pub fn apply(configuration: &Configuration) -> io::Result { + let mut luid = NET_LUID_LH::default(); + let mut guid = GUID::default(); + check(unsafe { ConvertInterfaceIndexToLuid(configuration.interface, &mut luid) })?; + check(unsafe { ConvertInterfaceLuidToGuid(&luid, &mut guid) })?; + let mut installed = Self { + guid, + snapshot: Some(Snapshot::capture(guid)?), + tag: None, + }; + Snapshot { + domain: configuration.domains.first().cloned().unwrap_or_default(), + search: configuration.domains.join(","), + } + .write(guid)?; + // NRPT selects both IPv4 and IPv6 VPN resolvers. Split namespaces leave + // unrelated DNS on the physical network; "." covers full-tunnel DNS. + // Existing static/DHCP adapter nameserver configuration stays untouched. + if !configuration.servers.is_empty() { + let namespaces: Vec = if configuration.split_dns.is_empty() { + vec![".".into()] + } else { + configuration + .split_dns + .iter() + .map(|domain| format!(".{}", domain.trim_matches('.'))) + .collect() + }; + let tag = format!("GPConnect:{}", uuid::Uuid::new_v4()); + installed.tag = Some(tag.clone()); + policy( + json!({"operation":"add", "tag":tag, "namespaces":namespaces, "servers":configuration.servers.iter().map(ToString::to_string).collect::>()}), + )?; + } + Ok(installed) + } + pub fn restore(&mut self) -> io::Result<()> { + let mut failure = None; + if let Some(tag) = self.tag.take() { + if let Err(error) = policy(json!({"operation":"remove", "tag":tag})) { + log::warn!("Could not remove VPN DNS policy: {error}"); + failure = Some(error); + } + } + if let Some(snapshot) = self.snapshot.take() { + if let Err(error) = snapshot.write(self.guid) { + log::warn!("Could not restore VPN adapter DNS: {error}"); + if failure.is_none() { + failure = Some(error); + } + } + } + failure.map_or(Ok(()), Err) + } +} +impl Drop for Installed { + fn drop(&mut self) { + let _ = self.restore(); + } +} + +/// A crashed service cannot run Drop. Remove only GP Connect's tagged policies +/// before accepting a new connection; adapter rows disappear with Wintun itself. +pub(super) fn clear_stale_policies() -> io::Result<()> { + policy(json!({"operation":"clear-stale"})) +} +fn policy(request: serde_json::Value) -> io::Result<()> { + const SCRIPT: &str = include_str!("dns-policy.ps1"); + let encoded = base64::engine::general_purpose::STANDARD + .encode(SCRIPT.encode_utf16().flat_map(u16::to_le_bytes).collect::>()); + let root = + std::env::var_os("SystemRoot").ok_or_else(|| io::Error::other("Windows system directory is unavailable"))?; + let executable = std::path::PathBuf::from(root).join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let mut child = Command::new(executable) + .args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded]) + .creation_flags(CREATE_NO_WINDOW) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn()?; + let input = child + .stdin + .take() + .expect("stdin is piped") + .write_all(request.to_string().as_bytes()); + if let Err(error) = input { + let _ = child.kill(); + let _ = child.wait(); + return Err(error); + } + let output = child.wait_with_output()?; + if !output.status.success() { + return Err(io::Error::other(format!( + "Windows DNS policy failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ))); + } + Ok(()) +} diff --git a/crates/gpvpnc/src/windows/ip_helper.rs b/crates/gpvpnc/src/windows/ip_helper.rs new file mode 100644 index 0000000..41254a1 --- /dev/null +++ b/crates/gpvpnc/src/windows/ip_helper.rs @@ -0,0 +1,317 @@ +//! Native IP Helper changes with ownership of only the rows this connection creates. +use super::{ + configuration::Configuration, + recovery::{Journal, Route}, +}; +use ipnet::IpNet; +use std::{ + io, + net::{IpAddr, Ipv4Addr, Ipv6Addr}, + ptr, +}; +use windows_sys::Win32::{ + Foundation::{ERROR_NOT_FOUND, ERROR_OBJECT_ALREADY_EXISTS}, + NetworkManagement::IpHelper::*, + Networking::WinSock::*, +}; + +struct InstalledRoute { + row: MIB_IPFORWARD_ROW2, + record: Option, +} +pub(super) struct Installed { + routes: Vec, + journal: Journal, + addresses: Vec, + interfaces: Vec, +} +fn check(status: u32) -> io::Result<()> { + if status == 0 { + Ok(()) + } else { + Err(io::Error::from_raw_os_error(status as i32)) + } +} +fn socket_address(address: IpAddr) -> SOCKADDR_INET { + let mut result = SOCKADDR_INET::default(); + match address { + IpAddr::V4(address) => { + result.Ipv4.sin_family = AF_INET; + result.Ipv4.sin_addr.S_un.S_addr = u32::from_ne_bytes(address.octets()); + } + IpAddr::V6(address) => { + result.Ipv6.sin6_family = AF_INET6; + result.Ipv6.sin6_addr.u.Byte = address.octets(); + } + } + result +} +fn empty_address(ipv4: bool) -> SOCKADDR_INET { + socket_address(if ipv4 { + Ipv4Addr::UNSPECIFIED.into() + } else { + Ipv6Addr::UNSPECIFIED.into() + }) +} +fn route(prefix: IpNet, interface: u32) -> MIB_IPFORWARD_ROW2 { + let mut storage = std::mem::MaybeUninit::::zeroed(); + // IP Helper initializes BOOLEAN fields to 0xff. They must contain canonical + // Rust bool values before this storage can become an initialized Rust row. + let mut row = unsafe { + let pointer = storage.as_mut_ptr(); + InitializeIpForwardEntry(pointer); + std::ptr::addr_of_mut!((*pointer).Loopback).write(false); + std::ptr::addr_of_mut!((*pointer).AutoconfigureAddress).write(false); + std::ptr::addr_of_mut!((*pointer).Publish).write(false); + std::ptr::addr_of_mut!((*pointer).Immortal).write(true); + storage.assume_init() + }; + row.InterfaceIndex = interface; + row.DestinationPrefix.Prefix = socket_address(prefix.network()); + row.DestinationPrefix.PrefixLength = prefix.prefix_len(); + row.NextHop = empty_address(prefix.addr().is_ipv4()); + row.SitePrefixLength = 0; + row.Metric = 0; + row.Protocol = MIB_IPPROTO_NETMGMT; + row +} +fn physical_route(prefix: IpNet, tunnel: u32) -> io::Result { + let destination = socket_address(prefix.addr()); + let mut existing = MIB_IPFORWARD_ROW2::default(); + let mut source = SOCKADDR_INET::default(); + check(unsafe { GetBestRoute2(ptr::null(), 0, ptr::null(), &destination, 0, &mut existing, &mut source) })?; + if existing.InterfaceIndex == tunnel { + return Err(io::Error::other( + "The VPN gateway or exclusion resolves through the VPN adapter", + )); + } + let mut row = route(prefix, existing.InterfaceIndex); + row.InterfaceLuid = existing.InterfaceLuid; + row.NextHop = existing.NextHop; + row.Metric = existing.Metric; + Ok(row) +} +impl Installed { + pub fn apply(configuration: &Configuration, recovery_key: &str) -> io::Result { + // Resolve all physical paths before introducing any tunnel routes. + let gateway = IpNet::new( + configuration.gateway, + if configuration.gateway.is_ipv4() { 32 } else { 128 }, + ) + .map_err(io::Error::other)?; + let physical = std::iter::once(gateway) + .chain(configuration.excludes.iter().copied()) + .map(|prefix| physical_route(prefix, configuration.interface)) + .collect::>>()?; + let mut installed = Self { + routes: Vec::new(), + addresses: Vec::new(), + interfaces: Vec::new(), + journal: Journal::begin(recovery_key)?, + }; + for row in physical { + installed.add_route(row, true)?; + } + for family in [AF_INET, AF_INET6] { + if !configuration + .addresses + .iter() + .any(|address| address.addr().is_ipv4() == (family == AF_INET)) + { + continue; + } + let mut row = MIB_IPINTERFACE_ROW { + Family: family, + InterfaceIndex: configuration.interface, + ..Default::default() + }; + check(unsafe { GetIpInterfaceEntry(&mut row) })?; + installed.interfaces.push(row); + row.UseAutomaticMetric = false; + row.Metric = 1; + row.DadTransmits = 0; + row.RouterDiscoveryBehavior = RouterDiscoveryDisabled; + if let Some(mtu) = configuration.mtu { + row.NlMtu = mtu; + } + if family == AF_INET { + row.SitePrefixLength = 0; + } + check(unsafe { SetIpInterfaceEntry(&mut row) })?; + } + for address in &configuration.addresses { + let mut row = MIB_UNICASTIPADDRESS_ROW::default(); + unsafe { + InitializeUnicastIpAddressEntry(&mut row); + } + row.InterfaceIndex = configuration.interface; + row.Address = socket_address(address.addr()); + row.OnLinkPrefixLength = address.prefix_len(); + row.PrefixOrigin = IpPrefixOriginManual; + row.SuffixOrigin = IpSuffixOriginManual; + row.DadState = IpDadStatePreferred; + let status = unsafe { CreateUnicastIpAddressEntry(&row) }; + if status != ERROR_OBJECT_ALREADY_EXISTS { + check(status)?; + installed.addresses.push(row); + } + } + for prefix in &configuration.includes { + installed.add_route(route(*prefix, configuration.interface), false)?; + } + for server in &configuration.servers { + if *server == configuration.gateway { + continue; + } + let prefix = IpNet::new(*server, if server.is_ipv4() { 32 } else { 128 }).map_err(io::Error::other)?; + installed.add_route(route(prefix, configuration.interface), false)?; + } + Ok(installed) + } + fn add_route(&mut self, row: MIB_IPFORWARD_ROW2, physical: bool) -> io::Result<()> { + let status = unsafe { CreateIpForwardEntry2(&row) }; + if status != ERROR_OBJECT_ALREADY_EXISTS { + check(status)?; + // Retain rollback ownership even if writing the registry record fails. + self.routes.push(InstalledRoute { row, record: None }); + if physical { + let name = self.journal.record(&Route::from_row(&row)?)?; + self.routes.last_mut().expect("route was just installed").record = Some(name); + } + } + Ok(()) + } + pub fn restore(&mut self) -> io::Result<()> { + let mut failure = None; + for route in self.routes.drain(..).rev() { + match remove_owned_route(&route.row) { + Ok(()) => { + if let Some(name) = route.record { + if let Err(error) = self.journal.forget(&name) { + log::warn!("Could not clear Windows route ownership: {error}"); + if failure.is_none() { + failure = Some(error); + } + } + } + } + Err(error) => { + log::warn!("Could not remove owned Windows route: {error}"); + if failure.is_none() { + failure = Some(error); + } + } + } + } + let mut record = |status| { + if status != ERROR_NOT_FOUND && status != 0 { + let error = io::Error::from_raw_os_error(status as i32); + log::warn!("Could not restore VPN network configuration: {error}"); + if failure.is_none() { + failure = Some(error); + } + } + }; + for row in self.addresses.drain(..).rev() { + record(unsafe { DeleteUnicastIpAddressEntry(&row) }); + } + for original in self.interfaces.drain(..).rev() { + let mut current = MIB_IPINTERFACE_ROW { + Family: original.Family, + InterfaceIndex: original.InterfaceIndex, + ..Default::default() + }; + let status = unsafe { GetIpInterfaceEntry(&mut current) }; + if status != 0 { + record(status); + continue; + } + current.UseAutomaticMetric = original.UseAutomaticMetric; + current.Metric = original.Metric; + current.NlMtu = original.NlMtu; + current.DadTransmits = original.DadTransmits; + current.RouterDiscoveryBehavior = original.RouterDiscoveryBehavior; + if current.Family == AF_INET { + current.SitePrefixLength = 0; + } + record(unsafe { SetIpInterfaceEntry(&mut current) }); + } + failure.map_or(Ok(()), Err) + } +} +impl Drop for Installed { + fn drop(&mut self) { + let _ = self.restore(); + } +} + +fn address(value: &SOCKADDR_INET) -> io::Result { + unsafe { + match value.si_family { + AF_INET => Ok(Ipv4Addr::from(value.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()), + AF_INET6 => Ok(Ipv6Addr::from(value.Ipv6.sin6_addr.u.Byte).into()), + _ => Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid route address family", + )), + } + } +} +fn scope(value: &SOCKADDR_INET) -> u32 { + unsafe { + if value.si_family == AF_INET6 { + value.Ipv6.Anonymous.sin6_scope_id + } else { + 0 + } + } +} +impl Route { + fn from_row(row: &MIB_IPFORWARD_ROW2) -> io::Result { + Ok(Self { + prefix: IpNet::new( + address(&row.DestinationPrefix.Prefix)?, + row.DestinationPrefix.PrefixLength, + ) + .map_err(io::Error::other)?, + next_hop: address(&row.NextHop)?, + interface_luid: unsafe { row.InterfaceLuid.Value }, + metric: row.Metric, + prefix_scope: scope(&row.DestinationPrefix.Prefix), + next_hop_scope: scope(&row.NextHop), + }) + } + fn row(&self) -> io::Result { + if self.interface_luid == 0 || self.prefix.addr().is_ipv4() != self.next_hop.is_ipv4() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid saved Windows route", + )); + } + let mut row = route(self.prefix, 0); + row.InterfaceLuid.Value = self.interface_luid; + row.Metric = self.metric; + row.NextHop = socket_address(self.next_hop); + if self.prefix.addr().is_ipv6() { + row.DestinationPrefix.Prefix.Ipv6.Anonymous.sin6_scope_id = self.prefix_scope; + row.NextHop.Ipv6.Anonymous.sin6_scope_id = self.next_hop_scope; + } + Ok(row) + } +} +fn remove_owned_route(row: &MIB_IPFORWARD_ROW2) -> io::Result<()> { + let mut current = *row; + let status = unsafe { GetIpForwardEntry2(&mut current) }; + if status == ERROR_NOT_FOUND { + return Ok(()); + } + check(status)?; + if current.Protocol != row.Protocol || current.Metric != row.Metric { + log::warn!("Preserving a Windows route changed after VPN installation"); + return Ok(()); + } + check(unsafe { DeleteIpForwardEntry2(¤t) }) +} +pub(super) fn recover_route(saved: &Route) -> io::Result<()> { + remove_owned_route(&saved.row()?) +} diff --git a/crates/gpvpnc/src/windows/mod.rs b/crates/gpvpnc/src/windows/mod.rs new file mode 100644 index 0000000..cc243ab --- /dev/null +++ b/crates/gpvpnc/src/windows/mod.rs @@ -0,0 +1,64 @@ +//! Windows network installation driven by OpenConnect's normal configuration callback. +mod configuration; +mod dns; +mod ip_helper; +mod recovery; +use configuration::Configuration; +use std::io; + +pub struct NetworkConfigurator { + connection: Option, + recovery_key: String, +} +struct Connection { + dns: dns::Installed, + network: ip_helper::Installed, +} +impl NetworkConfigurator { + /// The owner supplies an HKLM key under its administrator-controlled namespace. + pub fn new(recovery_key: &str) -> io::Result { + recovery::Journal::begin(recovery_key)?; + Ok(Self { + connection: None, + recovery_key: recovery_key.into(), + }) + } + pub fn configure(&mut self, reason: &str, environment: &[(String, Option)]) -> io::Result<()> { + match reason { + "pre-init" | "attempt-reconnect" => Ok(()), + "connect" | "reconnect" => { + let configuration = Configuration::parse(environment)?; + self.disconnect()?; + let network = ip_helper::Installed::apply(&configuration, &self.recovery_key)?; + let dns = dns::Installed::apply(&configuration)?; + self.connection = Some(Connection { dns, network }); + Ok(()) + } + "disconnect" => self.disconnect(), + _ => Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Unknown VPN configuration reason: {reason}"), + )), + } + } + fn disconnect(&mut self) -> io::Result<()> { + if let Some(mut connection) = self.connection.take() { + let dns = connection.dns.restore(); + let network = connection.network.restore(); + dns.and(network) + } else { + Ok(()) + } + } +} + +/// Restore process-owned physical routes and DNS policy before service admission. +pub fn recover(recovery_key: &str) -> io::Result<()> { + if let Some(journal) = recovery::Journal::open(recovery_key)? { + for (name, route) in journal.routes()? { + ip_helper::recover_route(&route)?; + journal.forget(&name)?; + } + } + dns::clear_stale_policies() +} diff --git a/crates/gpvpnc/src/windows/recovery.rs b/crates/gpvpnc/src/windows/recovery.rs new file mode 100644 index 0000000..df4d816 --- /dev/null +++ b/crates/gpvpnc/src/windows/recovery.rs @@ -0,0 +1,70 @@ +//! Ownership records for physical routes, retained across process termination. +use ipnet::IpNet; +use serde::{Deserialize, Serialize}; +use std::{io, net::IpAddr}; +use winreg::{RegKey, enums::*}; + +const PREFIX: &str = "Route-"; +#[derive(Serialize, Deserialize)] +pub(super) struct Route { + pub prefix: IpNet, + pub next_hop: IpAddr, + pub interface_luid: u64, + pub metric: u32, + pub prefix_scope: u32, + pub next_hop_scope: u32, +} +pub(super) struct Journal(RegKey); +impl Journal { + pub fn begin(path: &str) -> io::Result { + let (parent, name) = path + .rsplit_once('\\') + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Recovery key must have a registry parent"))?; + let (parent, _) = RegKey::predef(HKEY_LOCAL_MACHINE).create_subkey(parent)?; + // ActiveStore routes and this volatile key share the kernel's lifetime. + // HKLM parent permissions restrict writes to SYSTEM and administrators. + let (key, _) = parent.create_subkey_with_options_flags(name, REG_OPTION_VOLATILE, KEY_READ | KEY_WRITE)?; + let journal = Self(key); + if !journal.routes()?.is_empty() { + return Err(io::Error::other( + "Recover the previous Windows network state before connecting", + )); + } + Ok(journal) + } + pub fn open(path: &str) -> io::Result> { + match RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(path, KEY_READ | KEY_WRITE) { + Ok(key) => Ok(Some(Self(key))), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } + } + pub fn routes(&self) -> io::Result> { + self + .0 + .enum_values() + .filter_map(|value| match value { + Ok((name, _)) if name.starts_with(PREFIX) => Some((|| { + let text: String = self.0.get_value(&name)?; + let route = serde_json::from_str(&text).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + Ok((name, route)) + })()), + Ok(_) => None, + Err(error) => Some(Err(error)), + }) + .collect() + } + pub fn record(&self, route: &Route) -> io::Result { + let name = format!("{PREFIX}{}", uuid::Uuid::new_v4()); + self + .0 + .set_value(&name, &serde_json::to_string(route).map_err(io::Error::other)?)?; + Ok(name) + } + pub fn forget(&self, name: &str) -> io::Result<()> { + match self.0.delete_value(name) { + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + result => result, + } + } +} diff --git a/crates/gpvpnc/tests/windows_network.rs b/crates/gpvpnc/tests/windows_network.rs new file mode 100644 index 0000000..57bfe65 --- /dev/null +++ b/crates/gpvpnc/tests/windows_network.rs @@ -0,0 +1,454 @@ +#![cfg(windows)] +//! Run as administrator with GP_TEST_WINTUN_DLL pointing to the signed Wintun DLL. +use std::{ffi::c_void, io, net::IpAddr, os::windows::ffi::OsStrExt, path::PathBuf, ptr}; +use windows_sys::{ + Win32::{ + Foundation::{FreeLibrary, HMODULE}, + NetworkManagement::Ndis::NET_LUID_LH, + System::LibraryLoader::*, + }, + core::GUID, +}; +type CloseAdapter = unsafe extern "system" fn(*mut c_void); +type EndSession = unsafe extern "system" fn(*mut c_void); +struct Library(HMODULE); +impl Drop for Library { + fn drop(&mut self) { + unsafe { + FreeLibrary(self.0); + } + } +} +struct Adapter { + handle: *mut c_void, + session: *mut c_void, + close: CloseAdapter, + end: EndSession, + index: u32, + _library: Library, +} +impl Adapter { + fn create() -> Result> { + let path = + PathBuf::from(std::env::var_os("GP_TEST_WINTUN_DLL").ok_or("GP_TEST_WINTUN_DLL is required")?).canonicalize()?; + let path: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let module = unsafe { + LoadLibraryExW( + path.as_ptr(), + ptr::null_mut(), + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return Err(io::Error::last_os_error().into()); + } + let library = Library(module); + // Wintun's public C ABI uses WINAPI and pointer-sized opaque handles. + let create: unsafe extern "system" fn(*const u16, *const u16, *const GUID) -> *mut c_void = unsafe { + std::mem::transmute( + GetProcAddress(module, c"WintunCreateAdapter".as_ptr().cast()).ok_or("Missing WintunCreateAdapter")?, + ) + }; + let close: CloseAdapter = unsafe { + std::mem::transmute( + GetProcAddress(module, c"WintunCloseAdapter".as_ptr().cast()).ok_or("Missing WintunCloseAdapter")?, + ) + }; + let luid: unsafe extern "system" fn(*mut c_void, *mut NET_LUID_LH) = unsafe { + std::mem::transmute( + GetProcAddress(module, c"WintunGetAdapterLUID".as_ptr().cast()).ok_or("Missing WintunGetAdapterLUID")?, + ) + }; + let start: unsafe extern "system" fn(*mut c_void, u32) -> *mut c_void = unsafe { + std::mem::transmute( + GetProcAddress(module, c"WintunStartSession".as_ptr().cast()).ok_or("Missing WintunStartSession")?, + ) + }; + let end: EndSession = unsafe { + std::mem::transmute( + GetProcAddress(module, c"WintunEndSession".as_ptr().cast()).ok_or("Missing WintunEndSession")?, + ) + }; + let name: Vec = format!("GP Connect Test {}", uuid::Uuid::new_v4().simple()) + .encode_utf16() + .chain(Some(0)) + .collect(); + let kind: Vec = "GP Connect".encode_utf16().chain(Some(0)).collect(); + let handle = unsafe { create(name.as_ptr(), kind.as_ptr(), ptr::null()) }; + if handle.is_null() { + return Err(io::Error::last_os_error().into()); + } + let mut adapter = Self { + handle, + session: ptr::null_mut(), + close, + end, + index: 0, + _library: library, + }; + let mut id = NET_LUID_LH::default(); + unsafe { + luid(handle, &mut id); + } + check(unsafe { ConvertInterfaceLuidToIndex(&id, &mut adapter.index) }); + adapter.session = unsafe { start(handle, 0x400000) }; + if adapter.session.is_null() { + return Err(io::Error::last_os_error().into()); + } + std::thread::sleep(std::time::Duration::from_secs(1)); + Ok(adapter) + } +} +impl Drop for Adapter { + fn drop(&mut self) { + unsafe { + if !self.session.is_null() { + (self.end)(self.session); + } + (self.close)(self.handle); + } + } +} + +use gpvpnc::windows::NetworkConfigurator; +use windows_sys::Win32::{NetworkManagement::IpHelper::*, Networking::WinSock::*}; +fn check(status: u32) { + assert_eq!( + status, + 0, + "Native IP Helper failed: {}", + io::Error::from_raw_os_error(status as i32) + ); +} +fn address(value: &SOCKADDR_INET) -> IpAddr { + unsafe { + match value.si_family { + AF_INET => std::net::Ipv4Addr::from(value.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into(), + AF_INET6 => std::net::Ipv6Addr::from(value.Ipv6.sin6_addr.u.Byte).into(), + _ => panic!("unexpected family"), + } + } +} +fn routes(index: Option) -> Vec { + let mut result = Vec::new(); + unsafe { + let mut table = std::ptr::null_mut(); + check(GetIpForwardTable2(AF_UNSPEC, &mut table)); + for row in std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize) { + if Some(row.InterfaceIndex) != index + && !["198.51.100.1", "203.0.113.128"].contains(&address(&row.DestinationPrefix.Prefix).to_string().as_str()) + { + continue; + } + result.push(format!( + "route {} {}/{} {} {}", + row.InterfaceIndex, + address(&row.DestinationPrefix.Prefix), + row.DestinationPrefix.PrefixLength, + address(&row.NextHop), + row.Metric + )); + } + FreeMibTable(table.cast()); + } + result.sort(); + result +} +fn state(index: u32) -> Vec { + let mut result = routes(Some(index)); + unsafe { + let mut table = std::ptr::null_mut(); + check(GetUnicastIpAddressTable(AF_UNSPEC, &mut table)); + for row in std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize) { + if row.InterfaceIndex == index { + result.push(format!("address {}/{}", address(&row.Address), row.OnLinkPrefixLength)); + } + } + FreeMibTable(table.cast()); + for family in [AF_INET, AF_INET6] { + let mut row = MIB_IPINTERFACE_ROW { + Family: family, + InterfaceIndex: index, + ..Default::default() + }; + check(GetIpInterfaceEntry(&mut row)); + result.push(format!( + "interface {} {} {} {} {}", + family, row.Metric, row.UseAutomaticMetric, row.NlMtu, row.DadTransmits + )); + } + } + unsafe { + let mut luid = NET_LUID_LH::default(); + let mut guid = GUID::default(); + check(ConvertInterfaceIndexToLuid(index, &mut luid)); + check(ConvertInterfaceLuidToGuid(&luid, &mut guid)); + let mut dns = DNS_INTERFACE_SETTINGS { + Version: DNS_INTERFACE_SETTINGS_VERSION1, + ..Default::default() + }; + check(GetInterfaceDnsSettings(guid, &mut dns)); + for (name, pointer) in [ + ("dns-domain", dns.Domain), + ("dns-search", dns.SearchList), + ("dns-servers", dns.NameServer), + ] { + let mut length = 0; + if !pointer.is_null() { + while *pointer.add(length) != 0 { + length += 1; + } + } + let text = if pointer.is_null() { + String::new() + } else { + String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length)) + }; + result.push(format!("{name} {text}")); + } + FreeInterfaceDnsSettings(&mut dns); + } + result.sort(); + result +} +fn best_route(destination: &str) -> MIB_IPFORWARD_ROW2 { + let ip: IpAddr = destination.parse().unwrap(); + let mut destination = SOCKADDR_INET::default(); + match ip { + IpAddr::V4(ip) => { + destination.Ipv4.sin_family = AF_INET; + destination.Ipv4.sin_addr.S_un.S_addr = u32::from_ne_bytes(ip.octets()); + } + IpAddr::V6(ip) => { + destination.Ipv6.sin6_family = AF_INET6; + destination.Ipv6.sin6_addr.u.Byte = ip.octets(); + } + } + let mut route = MIB_IPFORWARD_ROW2::default(); + let mut source = SOCKADDR_INET::default(); + check(unsafe { GetBestRoute2(ptr::null(), 0, ptr::null(), &destination, 0, &mut route, &mut source) }); + route +} + +fn assert_dns_policy(active: bool) { + const CHECK: &str = r#" +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$expected = [int]$env:GP_TEST_EXPECTED_DNS_POLICIES +$configured = @(Get-DnsClientNrptRule | Where-Object { $_.Namespace -contains '.gp-connect-test.invalid' }) +$effective = @(Get-DnsClientNrptPolicy | Where-Object { $_.Namespace -contains '.gp-connect-test.invalid' }) +if ($configured.Count -ne $expected -or $effective.Count -ne $expected) { throw 'Unexpected configured or effective VPN DNS policy' } +if ($expected) { + $servers = @($configured[0].NameServers) + if ($servers -notcontains '198.18.0.53' -or $servers -notcontains 'fd42:1235::53') { throw 'VPN DNS server families are missing' } +} +"#; + let powershell = + PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let output = std::process::Command::new(powershell) + .args(["-NoProfile", "-NonInteractive", "-Command", CHECK]) + .env("GP_TEST_EXPECTED_DNS_POLICIES", if active { "1" } else { "0" }) + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); +} + +#[test] +#[ignore = "requires administrator privileges and GP_TEST_WINTUN_DLL"] +fn installs_and_restores_native_network_configuration() -> Result<(), Box> { + let adapter = Adapter::create()?; + let index = adapter.index; + if let Some(recovery_key) = std::env::var_os("GP_TEST_CRASH_KEY") { + let recovery_key = recovery_key.to_str().ok_or("Invalid registry key")?; + let mut network = NetworkConfigurator::new(recovery_key)?; + network.configure("connect", &environment(index))?; + std::fs::write( + std::env::var_os("GP_TEST_CRASH_READY").ok_or("Missing readiness path")?, + index.to_string(), + )?; + loop { + std::thread::park(); + } + } + let environment = environment(index); + let recovery_key = format!(r"SOFTWARE\GP Connect\Tests\Network{}", uuid::Uuid::new_v4().simple()); + assert_dns_policy(false); + let before = state(index); + { + let mut network = NetworkConfigurator::new(&recovery_key)?; + network.configure("connect", &environment)?; + let during = state(index); + assert!(during.iter().any(|row| row == "address 192.0.2.2/24")); + assert!(during.iter().any(|row| row == "address fd42:1234::2/64")); + assert!( + during + .iter() + .any(|row| row.starts_with(&format!("route {index} 203.0.113.0/24 "))) + ); + assert!( + during + .iter() + .any(|row| row.starts_with(&format!("route {index} 2001:db8:1234::/64 "))) + ); + assert_eq!(best_route("203.0.113.1").InterfaceIndex, index); + assert_eq!(best_route("2001:db8:1234::1").InterfaceIndex, index); + assert_eq!(best_route("198.18.0.53").InterfaceIndex, index); + assert_eq!(best_route("fd42:1235::53").InterfaceIndex, index); + assert_ne!(best_route("203.0.113.200").InterfaceIndex, index); + assert_ne!(best_route("198.51.100.1").InterfaceIndex, index); + println!("PASS: IPv4/IPv6 addresses, split routes, resolver routes and MTU installed"); + assert_dns_policy(true); + network.configure("disconnect", &[])?; + } + assert_eq!(before, state(index), "Network state was not restored"); + assert_dns_policy(false); + println!("PASS: disconnect restored addresses, routes and interface settings"); + { + let mut network = NetworkConfigurator::new(&recovery_key)?; + network.configure("connect", &environment)?; + } + assert_eq!( + before, + state(index), + "Dropping the connection did not restore network state" + ); + assert_dns_policy(false); + let mut invalid = environment.clone(); + invalid[0].1 = Some(u32::MAX.to_string()); + assert!( + NetworkConfigurator::new(&recovery_key)? + .configure("connect", &invalid) + .is_err() + ); + assert_eq!(before, state(index), "Failed connection left a physical gateway route"); + println!("PASS: partial setup failure rolled back its physical gateway route"); + drop(adapter); + assert_crash_recovery(&recovery_key)?; + winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE).delete_subkey(&recovery_key)?; + Ok(()) +} + +fn environment(index: u32) -> Vec<(String, Option)> { + let pairs = [ + ("TUNIDX", index.to_string()), + ("VPNGATEWAY", "198.51.100.1".into()), + ("INTERNAL_IP4_ADDRESS", "192.0.2.2".into()), + ("INTERNAL_IP4_NETMASKLEN", "24".into()), + ("INTERNAL_IP6_ADDRESS", "fd42:1234::2".into()), + ("INTERNAL_IP6_NETMASK", "fd42:1234::2/64".into()), + ("INTERNAL_IP4_MTU", "1406".into()), + ("CISCO_SPLIT_INC", "1".into()), + ("CISCO_SPLIT_INC_0_ADDR", "203.0.113.0".into()), + ("CISCO_SPLIT_INC_0_MASKLEN", "24".into()), + ("CISCO_SPLIT_EXC", "1".into()), + ("CISCO_SPLIT_EXC_0_ADDR", "203.0.113.128".into()), + ("CISCO_SPLIT_EXC_0_MASKLEN", "25".into()), + ("CISCO_IPV6_SPLIT_INC", "1".into()), + ("CISCO_IPV6_SPLIT_INC_0_ADDR", "2001:db8:1234::".into()), + ("CISCO_IPV6_SPLIT_INC_0_MASKLEN", "64".into()), + ("INTERNAL_IP4_DNS", "198.18.0.53 fd42:1235::53".into()), + ("CISCO_DEF_DOMAIN", "gp-connect-test.invalid".into()), + ("CISCO_SPLIT_DNS", "gp-connect-test.invalid".into()), + ]; + pairs + .into_iter() + .map(|(key, value)| (key.to_string(), Some(value))) + .collect() +} + +struct CrashChild { + child: std::process::Child, + key: String, + modified_route: Option, +} +impl Drop for CrashChild { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + if let Some(route) = self.modified_route.take() { + unsafe { + DeleteIpForwardEntry2(&route); + } + } + let _ = gpvpnc::windows::recover(&self.key); + } +} +fn assert_crash_recovery(key: &str) -> Result<(), Box> { + let before = routes(None); + let directory = tempfile::tempdir()?; + let ready = directory.path().join("ready"); + let child = std::process::Command::new(std::env::current_exe()?) + .args([ + "--ignored", + "--exact", + "installs_and_restores_native_network_configuration", + ]) + .env("GP_TEST_CRASH_KEY", key) + .env("GP_TEST_CRASH_READY", &ready) + .stdout(std::process::Stdio::null()) + .spawn()?; + let mut child = CrashChild { + child, + key: key.into(), + modified_route: None, + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while !ready.exists() { + if child.child.try_wait()?.is_some() || std::time::Instant::now() > deadline { + return Err("Crash child did not install its network state".into()); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let child_index: u32 = std::fs::read_to_string(&ready)?.parse()?; + assert_dns_policy(true); + let dirty = routes(None); + assert_ne!(before, dirty, "Child did not create physical routes"); + child.child.kill()?; + child.child.wait()?; + assert_dns_policy(true); + let mut addresses = ptr::null_mut(); + check(unsafe { GetUnicastIpAddressTable(AF_UNSPEC, &mut addresses) }); + let child_addresses = unsafe { + std::slice::from_raw_parts((*addresses).Table.as_ptr(), (*addresses).NumEntries as usize) + .iter() + .any(|row| row.InterfaceIndex == child_index) + }; + unsafe { + FreeMibTable(addresses.cast()); + } + assert!(!child_addresses, "Terminated process left its Wintun addresses"); + assert_ne!( + before, + routes(None), + "Physical routes unexpectedly disappeared with the process" + ); + // Model an administrator taking ownership of an exclusion after the crash. + let mut modified = best_route("203.0.113.200"); + assert_eq!(address(&modified.DestinationPrefix.Prefix).to_string(), "203.0.113.128"); + modified.Metric += 1; + check(unsafe { SetIpForwardEntry2(&modified) }); + child.modified_route = Some(modified); + let mut expected = before.clone(); + expected.push(format!( + "route {} {}/{} {} {}", + modified.InterfaceIndex, + address(&modified.DestinationPrefix.Prefix), + modified.DestinationPrefix.PrefixLength, + address(&modified.NextHop), + modified.Metric + )); + expected.sort(); + gpvpnc::windows::recover(key)?; + assert_eq!( + expected, + routes(None), + "Recovery must remove owned routes and preserve the changed route" + ); + assert_dns_policy(false); + drop(NetworkConfigurator::new(key)?); + check(unsafe { DeleteIpForwardEntry2(&modified) }); + child.modified_route = None; + assert_eq!(before, routes(None), "Crash recovery did not restore the baseline"); + println!("PASS: crash recovery removed owned physical routes and DNS policy and preserved an administrator's change"); + Ok(()) +} diff --git a/crates/openconnect/Cargo.toml b/crates/openconnect/Cargo.toml index 5e7f3f1..5338b97 100644 --- a/crates/openconnect/Cargo.toml +++ b/crates/openconnect/Cargo.toml @@ -7,6 +7,7 @@ license = "MIT" links = "openconnect" [dependencies] +gp-xml = { path = "../gp-xml" } log.workspace = true libc = "0.2" is_executable.workspace = true @@ -19,3 +20,6 @@ fs_extra = "1" [dev-dependencies] tempfile = "3" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Networking_WinSock"] } diff --git a/crates/openconnect/build.rs b/crates/openconnect/build.rs index c5b7ca5..6ae59fd 100644 --- a/crates/openconnect/build.rs +++ b/crates/openconnect/build.rs @@ -1,3 +1,6 @@ +#[path = "build/windows.rs"] +mod windows; + use std::{env, path::PathBuf}; fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { @@ -188,6 +191,10 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { fn main() { let target = target_os(); + if target == "windows" { + windows::build(); + return; + } assert!( matches!(target.as_str(), "macos" | "linux" | "freebsd" | "openbsd"), "Unsupported OpenConnect target: {target}" diff --git a/crates/openconnect/build/windows.rs b/crates/openconnect/build/windows.rs new file mode 100644 index 0000000..9ace899 --- /dev/null +++ b/crates/openconnect/build/windows.rs @@ -0,0 +1,31 @@ +//! Link the MinGW-built OpenConnect DLL into the native MSVC Rust service. +use std::{env, path::PathBuf}; + +pub fn build() { + println!("cargo:rerun-if-env-changed=OPENCONNECT_WINDOWS_PREFIX"); + let prefix = PathBuf::from( + env::var_os("OPENCONNECT_WINDOWS_PREFIX") + .expect("Build native OpenConnect and set OPENCONNECT_WINDOWS_PREFIX to its install directory"), + ); + let include = prefix.join("include"); + let library = prefix.join("lib"); + assert!( + library.join("openconnect.lib").is_file(), + "The native OpenConnect MSVC import library is missing" + ); + println!("cargo:rerun-if-changed={}", library.join("openconnect.lib").display()); + println!("cargo:rerun-if-changed={}", include.join("openconnect.h").display()); + println!("cargo:rustc-link-search=native={}", library.display()); + println!("cargo:rustc-link-lib=dylib=openconnect"); + println!("cargo:rustc-link-lib=ws2_32"); + println!("cargo:include={}", include.display()); + println!("cargo:lib_dir={}", prefix.join("bin").display()); + println!("cargo:rerun-if-changed=src/ffi/vpn.c"); + println!("cargo:rerun-if-changed=src/ffi/vpn.h"); + cc::Build::new() + .file("src/ffi/vpn.c") + .include("src/ffi") + .include(include) + .std("c11") + .compile("vpn"); +} diff --git a/crates/openconnect/deps/openconnect b/crates/openconnect/deps/openconnect index 43b36d7..80b4f80 160000 --- a/crates/openconnect/deps/openconnect +++ b/crates/openconnect/deps/openconnect @@ -1 +1 @@ -Subproject commit 43b36d7293804d66a27addad54a2b3b78ae8f789 +Subproject commit 80b4f80926c45f1210af4dcc2b332af199027d20 diff --git a/crates/openconnect/src/ffi/gateway.rs b/crates/openconnect/src/ffi/gateway.rs index d672ff2..c1467a8 100644 --- a/crates/openconnect/src/ffi/gateway.rs +++ b/crates/openconnect/src/ffi/gateway.rs @@ -1,7 +1,11 @@ +#[cfg(unix)] +use libc::{AF_INET, AF_INET6, addrinfo, getaddrinfo}; use std::{ ffi::{c_char, c_int}, ptr, }; +#[cfg(windows)] +use windows_sys::Win32::Networking::WinSock::{ADDRINFOA as addrinfo, AF_INET, AF_INET6, getaddrinfo}; /// Resolve with the system's normal policy, then prefer one family without /// discarding alternatives. The returned list remains owned by libc and is @@ -13,18 +17,18 @@ use std::{ pub unsafe extern "C" fn vpn_resolve_gateway( node: *const c_char, service: *const c_char, - hints: *const libc::addrinfo, - result: *mut *mut libc::addrinfo, + hints: *const addrinfo, + result: *mut *mut addrinfo, preference: u32, ) -> c_int { // SAFETY: The OpenConnect callback forwards valid getaddrinfo arguments. - let status = unsafe { libc::getaddrinfo(node, service, hints, result) }; + let status = unsafe { getaddrinfo(node.cast(), service.cast(), hints, result) }; if status != 0 { return status; } let family = match preference { - 4 => libc::AF_INET, - 6 => libc::AF_INET6, + 4 => AF_INET as c_int, + 6 => AF_INET6 as c_int, _ => return 0, }; // SAFETY: A successful getaddrinfo call returns an owned, writable list. @@ -34,7 +38,7 @@ pub unsafe extern "C" fn vpn_resolve_gateway( /// # Safety /// `head` must be an exclusively owned, writable addrinfo list with no cycles. -unsafe fn prefer_family(head: *mut libc::addrinfo, family: c_int) -> *mut libc::addrinfo { +unsafe fn prefer_family(head: *mut addrinfo, family: c_int) -> *mut addrinfo { let mut addresses = Vec::new(); let mut current = head; // SAFETY: The caller owns every node; sorting only changes the list links. diff --git a/crates/openconnect/src/ffi/mod.rs b/crates/openconnect/src/ffi/mod.rs index 26d3512..ed79f3e 100644 --- a/crates/openconnect/src/ffi/mod.rs +++ b/crates/openconnect/src/ffi/mod.rs @@ -1,3 +1,8 @@ +#[cfg(unix)] +pub(crate) type CommandHandle = i32; +#[cfg(windows)] +pub(crate) type CommandHandle = usize; + mod gateway; mod hip; mod network_configuration; @@ -41,9 +46,11 @@ pub(crate) struct ConnectOptions { pub script: *const c_char, pub configure_network: Option c_int>, - pub interface: *const c_char, + pub interface_name: *const c_char, pub script_tun: u32, pub script_tun_launch: *const ScriptTunLaunchRaw, + #[cfg(windows)] + pub script_tun_pipe: isize, pub certificate: *const c_char, pub sslkey: *const c_char, @@ -77,17 +84,17 @@ pub(crate) struct VpnSessionInfoRaw { #[link(name = "vpn")] unsafe extern "C" { - fn vpn_write_cancel(fd: c_int) -> c_int; - fn vpn_write_statistics(fd: c_int) -> c_int; + fn vpn_write_cancel(fd: CommandHandle) -> c_int; + fn vpn_write_statistics(fd: CommandHandle) -> c_int; #[link_name = "vpn_connect"] fn vpn_connect( options: *const ConnectOptions, - callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void), + callback: extern "C" fn(CommandHandle, *const VpnSessionInfoRaw, *mut c_void), ) -> c_int; } -pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> { +pub(crate) fn write_cancel(fd: CommandHandle) -> std::io::Result<()> { let error = unsafe { vpn_write_cancel(fd) }; if error == 0 { Ok(()) @@ -96,7 +103,7 @@ pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> { } } -pub(crate) fn write_statistics(fd: i32) -> std::io::Result<()> { +pub(crate) fn write_statistics(fd: CommandHandle) -> std::io::Result<()> { let error = unsafe { vpn_write_statistics(fd) }; if error == 0 { Ok(()) @@ -106,7 +113,7 @@ pub(crate) fn write_statistics(fd: i32) -> std::io::Result<()> { } #[unsafe(no_mangle)] -extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int { +extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: CommandHandle) -> c_int { unsafe { &*(vpn as *const Vpn) }.attach_command_pipe(fd).into() } @@ -134,7 +141,7 @@ pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *cons } #[unsafe(no_mangle)] -extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) { +extern "C" fn on_vpn_connected(pipe_fd: CommandHandle, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) { let vpn = unsafe { &*(vpn as *const Vpn) }; vpn.on_connected(pipe_fd, crate::vpn::session_info_from_raw(session_info)); } @@ -146,6 +153,14 @@ extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfo extern "C" fn vpn_log(level: i32, message: *const c_char) { let message = unsafe { std::ffi::CStr::from_ptr(message) }; let message = message.to_str().unwrap_or("Invalid log message"); + // This dump comes from the native GlobalProtect protocol handler. + if let Some(body) = message.strip_prefix("GlobalProtect getconfig.esp response:\n") { + debug!( + "GlobalProtect getconfig.esp response:\n{}", + gp_xml::redact_xml(body.as_bytes()) + ); + return; + } // Strip the trailing newline let message = message.trim_end_matches('\n'); @@ -165,3 +180,41 @@ extern "C" fn vpn_log(level: i32, message: *const c_char) { debug!("{}", message); } } + +#[cfg(test)] +mod log_tests { + use super::vpn_log; + use std::sync::Mutex; + + struct Capture(Mutex); + impl log::Log for Capture { + fn enabled(&self, _: &log::Metadata<'_>) -> bool { + true + } + fn flush(&self) {} + fn log(&self, record: &log::Record<'_>) { + if record.target() == module_path!().trim_end_matches("::log_tests") { + self.0.lock().unwrap().push_str(&record.args().to_string()); + } + } + } + + #[test] + fn native_config_dump_keeps_settings_and_redacts_keys_before_logging() { + static CAPTURE: Capture = Capture(Mutex::new(String::new())); + log::set_logger(&CAPTURE).unwrap(); + log::set_max_level(log::LevelFilter::Debug); + let message = c"GlobalProtect getconfig.esp response:\n1400fixture-secret128fixture-handshake-key\n"; + vpn_log(2, message.as_ptr()); + vpn_log( + 2, + c"GlobalProtect getconfig.esp response:\nfixture-secret".as_ptr(), + ); + let output = CAPTURE.0.lock().unwrap(); + assert!(output.contains("1400")); + assert!(output.contains("[redacted]")); + assert!(output.contains("[XML omitted:")); + assert!(!output.contains("fixture-secret")); + assert!(!output.contains("fixture-handshake-key")); + } +} diff --git a/crates/openconnect/src/ffi/vpn.c b/crates/openconnect/src/ffi/vpn.c index d7d6483..d9c2178 100644 --- a/crates/openconnect/src/ffi/vpn.c +++ b/crates/openconnect/src/ffi/vpn.c @@ -1,16 +1,15 @@ -#include +#include "vpn.h" #include #include #include #include -#include +#ifndef _WIN32 #include - -#include "vpn.h" +#endif struct vpn_context { struct openconnect_info *vpninfo; - int command_fd; + vpn_command_handle command_fd; const vpn_options *options; vpn_connected_callback on_connected; }; @@ -59,21 +58,22 @@ static int validate_peer_cert(void *private_data, if (context->options->servercert) return openconnect_check_peer_cert_hash(context->vpninfo, context->options->servercert); - INFO("Accepting the server certificate though %s", reason); + VPN_INFO("Accepting the server certificate though %s", reason); return 0; } /* Print progress messages */ -static void print_progress(__attribute__((unused)) void *_vpninfo, int level, +static void print_progress(void *_vpninfo, int level, const char *format, ...) { + (void)_vpninfo; va_list args; va_start(args, format); char *message = format_message(format, args); va_end(args); if (message == NULL) { - ERROR("Failed to format log message"); + VPN_ERROR("Failed to format log message"); } else { vpn_log(level, message); free(message); @@ -88,15 +88,24 @@ static void setup_tun_handler(void *private_data) int ret; if (options->script_tun) { const struct openconnect_script_tun_launch *launch = options->script_tun_launch; +#ifdef _WIN32 + if (options->script_tun_pipe != -1) { + ret = openconnect_setup_tun_pipe(_vpninfo, options->script_tun_pipe); + } else +#endif if (launch) { +#ifndef _WIN32 ret = openconnect_setup_tun_script_exec(_vpninfo, launch); vpn_script_started(options->user_data); +#else + ret = -EOPNOTSUPP; +#endif } else { ret = openconnect_setup_tun_script(_vpninfo, options->script); } } else { ret = openconnect_setup_tun_device(_vpninfo, options->script, - options->interface); + options->interface_name); } if (!ret) { @@ -122,39 +131,39 @@ static void setup_tun_handler(void *private_data) int vpn_connect(const vpn_options *options, vpn_connected_callback callback) { struct openconnect_info *vpninfo; - struct utsname utsbuf; + char hostname[256]; const char *effective_local_hostname = NULL; struct vpn_context context = { .options = options, .on_connected = callback }; int result = 1; - INFO("USER_AGENT: %s", options->user_agent); - INFO("OS: %s", options->os); - INFO("CLIENT_VERSION: %s", options->client_version); - INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)"); + VPN_INFO("USER_AGENT: %s", options->user_agent); + VPN_INFO("OS: %s", options->os); + VPN_INFO("CLIENT_VERSION: %s", options->client_version); + VPN_INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)"); const char *configuration = options->script; if (options->configure_network) configuration = "callback"; else if (options->script_tun_launch) configuration = options->script_tun_launch->program; - INFO("Network configuration: %s", configuration); - INFO("SCRIPT_TUN: %d", options->script_tun); - INFO("CSD_USER: %d", options->hip_script.uid); - INFO("CSD_WRAPPER: %s", options->hip_script.path); - INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout); - INFO("MTU: %d", options->mtu); - INFO("DISABLE_IPV6: %d", options->disable_ipv6); - INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference); - INFO("NO_DTLS: %d", options->no_dtls); - INFO("DPD_INTERVAL: %d", options->dpd_interval); - INFO("NO_XMLPOST: %d", options->no_xmlpost); + VPN_INFO("Network configuration: %s", configuration); + VPN_INFO("SCRIPT_TUN: %d", options->script_tun); + VPN_INFO("CSD_USER: %d", options->hip_script.uid); + VPN_INFO("CSD_WRAPPER: %s", options->hip_script.path); + VPN_INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout); + VPN_INFO("MTU: %d", options->mtu); + VPN_INFO("DISABLE_IPV6: %d", options->disable_ipv6); + VPN_INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference); + VPN_INFO("NO_DTLS: %d", options->no_dtls); + VPN_INFO("DPD_INTERVAL: %d", options->dpd_interval); + VPN_INFO("NO_XMLPOST: %d", options->no_xmlpost); vpninfo = openconnect_vpninfo_new(options->user_agent, validate_peer_cert, NULL, NULL, print_progress, &context); if (!vpninfo) { - ERROR("openconnect_vpninfo_new failed"); + VPN_ERROR("openconnect_vpninfo_new failed"); vpn_tunnel_event(options->user_data, VPN_TUNNEL_ENDED); return 1; } @@ -168,20 +177,21 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback) openconnect_set_stats_handler(vpninfo, observe_statistics); openconnect_set_gp_hip_report_callback(vpninfo, options->user_data, options->on_hip_report_submitted); + /* Windows command pipes are Winsock sockets. Initialize before creating them. */ + openconnect_init_ssl(); context.command_fd = openconnect_setup_cmd_pipe(vpninfo); - if (context.command_fd < 0) { - ERROR("openconnect_setup_cmd_pipe failed"); + if (context.command_fd == (vpn_command_handle)-1) { + VPN_ERROR("openconnect_setup_cmd_pipe failed"); goto cleanup; } /* An earlier disconnect remains latched on this attempt. */ if (vpn_attach_command_pipe(options->user_data, context.command_fd)) { - INFO("VPN attempt canceled before startup"); + VPN_INFO("VPN attempt canceled before startup"); result = -EINTR; goto cleanup; } openconnect_set_loglevel(vpninfo, PRG_TRACE); - openconnect_init_ssl(); openconnect_set_protocol(vpninfo, "gp"); openconnect_parse_url(vpninfo, options->server); if (options->gateway_ip_preference) @@ -207,18 +217,19 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback) } effective_local_hostname = options->local_hostname; - if (!effective_local_hostname && !uname(&utsbuf)) { - effective_local_hostname = utsbuf.nodename; + if (!effective_local_hostname && !gethostname(hostname, sizeof(hostname))) { + hostname[sizeof(hostname) - 1] = 0; + effective_local_hostname = hostname; } if (effective_local_hostname) { openconnect_set_localname(vpninfo, effective_local_hostname); } - INFO("LOCAL_HOSTNAME: %s", + VPN_INFO("LOCAL_HOSTNAME: %s", effective_local_hostname ? effective_local_hostname : "(not set)"); if (options->certificate) { - INFO("Setting client certificate: %s", options->certificate); + VPN_INFO("Setting client certificate: %s", options->certificate); openconnect_set_client_cert(vpninfo, options->certificate, options->sslkey); } @@ -256,7 +267,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback) // Essential step vpn_tunnel_event(options->user_data, OC_TUNNEL_NEGOTIATING); if (openconnect_make_cstp_connection(vpninfo) != 0) { - ERROR("openconnect_make_cstp_connection failed"); + VPN_ERROR("openconnect_make_cstp_connection failed"); goto cleanup; } @@ -273,12 +284,12 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback) options->reconnect_timeout, 10); if (ret) { - INFO("openconnect_mainloop returned %d, exiting", ret); + VPN_INFO("openconnect_mainloop returned %d, exiting", ret); result = ret; goto cleanup; } - INFO("openconnect_mainloop returned 0, reconnecting"); + VPN_INFO("openconnect_mainloop returned 0, reconnecting"); } cleanup: vpn_detach_command_pipe(options->user_data); @@ -289,24 +300,28 @@ cleanup: } /* Called with the attempt cancellation mutex held, never after detach/free. */ -int vpn_write_cancel(int fd) +static int write_command(vpn_command_handle fd, char command) { - char command = OC_CMD_CANCEL; +#ifdef _WIN32 + int written = send(fd, &command, 1, 0); + return written == 1 ? 0 : (written == SOCKET_ERROR ? WSAGetLastError() : EIO); +#else ssize_t written; do { written = write(fd, &command, 1); } while (written < 0 && errno == EINTR); return written == 1 ? 0 : (written < 0 ? errno : EIO); +#endif } -int vpn_write_statistics(int fd) +int vpn_write_cancel(vpn_command_handle fd) { - char command = OC_CMD_STATS; - ssize_t written; - do { - written = write(fd, &command, 1); - } while (written < 0 && errno == EINTR); - return written == 1 ? 0 : (written < 0 ? errno : EIO); + return write_command(fd, OC_CMD_CANCEL); +} + +int vpn_write_statistics(vpn_command_handle fd) +{ + return write_command(fd, OC_CMD_STATS); } int vpn_collect_hip_report(const vpn_hip_script *script, diff --git a/crates/openconnect/src/ffi/vpn.h b/crates/openconnect/src/ffi/vpn.h index e159a76..b7332b5 100644 --- a/crates/openconnect/src/ffi/vpn.h +++ b/crates/openconnect/src/ffi/vpn.h @@ -1,3 +1,10 @@ +#ifdef _WIN32 +#include +#include +typedef SOCKET vpn_command_handle; +#else +typedef int vpn_command_handle; +#endif #include #include #include @@ -13,7 +20,7 @@ typedef struct vpn_session_info { const char *nlb_connected_gw_ip; } vpn_session_info; -typedef void (*vpn_connected_callback)(int cmd_pipe_fd, +typedef void (*vpn_connected_callback)(vpn_command_handle cmd_pipe_fd, const vpn_session_info *session_info, void *user_data); typedef void (*vpn_hip_report_callback)(void *user_data, const char *report, @@ -45,9 +52,12 @@ typedef struct vpn_options { const char *script; openconnect_configure_tun_fn configure_network; - const char *interface; + const char *interface_name; const int script_tun; const struct openconnect_script_tun_launch *script_tun_launch; +#ifdef _WIN32 + intptr_t script_tun_pipe; +#endif const char *certificate; const char *sslkey; @@ -73,7 +83,7 @@ extern int vpn_resolve_gateway(const char *node, const char *service, int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *, const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *); -extern int vpn_attach_command_pipe(void *user_data, int fd); +extern int vpn_attach_command_pipe(void *user_data, vpn_command_handle fd); extern void vpn_detach_command_pipe(void *user_data); extern void vpn_script_started(void *user_data); enum vpn_tunnel_event { @@ -82,7 +92,7 @@ enum vpn_tunnel_event { VPN_TUNNEL_ENDED, }; extern void vpn_tunnel_event(void *user_data, int event); -extern void vpn_tunnel_configuration(void *user_data, const char *interface, +extern void vpn_tunnel_configuration(void *user_data, const char *interface_name, const struct oc_ip_info *info); extern void vpn_tunnel_statistics(void *user_data, const struct oc_stats *stats); @@ -122,8 +132,8 @@ static void _log(int level, ...) } } -#define LOG(level, ...) _log(level, __VA_ARGS__) -#define ERROR(...) LOG(PRG_ERR, __VA_ARGS__) -#define INFO(...) LOG(PRG_INFO, __VA_ARGS__) -#define DEBUG(...) LOG(PRG_DEBUG, __VA_ARGS__) -#define TRACE(...) LOG(PRG_TRACE, __VA_ARGS__) +#define VPN_LOG(level, ...) _log(level, __VA_ARGS__) +#define VPN_ERROR(...) VPN_LOG(PRG_ERR, __VA_ARGS__) +#define VPN_INFO(...) VPN_LOG(PRG_INFO, __VA_ARGS__) +#define VPN_DEBUG(...) VPN_LOG(PRG_DEBUG, __VA_ARGS__) +#define VPN_TRACE(...) VPN_LOG(PRG_TRACE, __VA_ARGS__) diff --git a/crates/openconnect/src/vpn.rs b/crates/openconnect/src/vpn.rs index c38110b..46465a2 100644 --- a/crates/openconnect/src/vpn.rs +++ b/crates/openconnect/src/vpn.rs @@ -1,7 +1,10 @@ +#[cfg(unix)] +use std::os::fd::{AsRawFd, OwnedFd}; +#[cfg(windows)] +use std::os::windows::io::{AsRawHandle, OwnedHandle}; use std::{ ffi::{CStr, CString, c_char}, fmt, io, - os::fd::{AsRawFd, OwnedFd}, sync::{Arc, Mutex, RwLock}, }; @@ -37,7 +40,8 @@ pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSe let raw = unsafe { &*raw }; let warning_message = unsafe { optional_c_string(raw.lifetime_warning_message) }.filter(|message| !message.is_empty()); - let user_expires = positive_i64_to_u32(raw.user_expires).or_else(|| positive_i64_to_u32(raw.auth_expiration)); + let user_expires = + positive_i64_to_u32(raw.user_expires.into()).or_else(|| positive_i64_to_u32(raw.auth_expiration.into())); VpnSessionInfo { lifetime_secs: positive_i64_to_u32(raw.lifetime_secs as i64), @@ -73,12 +77,12 @@ struct Cancellation { #[derive(Default)] struct CancellationState { requested: bool, - command_fd: Option, + command_fd: Option, statistics_pending: bool, } impl Cancellation { - fn attach(&self, fd: i32) -> bool { + fn attach(&self, fd: ffi::CommandHandle) -> bool { let mut state = self.state.lock().unwrap(); state.command_fd = Some(fd); state.requested @@ -150,7 +154,10 @@ pub struct Vpn { pub(crate) network_configuration_handler: Option>, interface: Option, script_tun: bool, + #[cfg(unix)] script_tun_launch: Option, + #[cfg(windows)] + script_tun_pipe: Option, certificate: Option, sslkey: Option, @@ -232,7 +239,9 @@ impl Vpn { } self.callback.write().unwrap().replace(Box::new(on_connected)); let mut options = self.build_connect_options(); + #[cfg(unix)] let mut argv = Vec::new(); + #[cfg(unix)] let launch = self.script_tun_launch.as_ref().map(|launch| { argv.push(launch.program.as_ptr()); argv.extend(launch.arguments.iter().map(|s| s.as_ptr())); @@ -245,7 +254,10 @@ impl Vpn { } }); // Both the borrowed launch record and argv remain alive through native connect. - options.script_tun_launch = launch.as_ref().map_or(std::ptr::null(), |launch| launch); + #[cfg(unix)] + { + options.script_tun_launch = launch.as_ref().map_or(std::ptr::null(), |launch| launch); + } let environment = match self.hip_source.as_ref() { HipSource::Script(script) => ffi::script_environment(script), _ => Vec::new(), @@ -269,7 +281,7 @@ impl Vpn { } } - pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) { + pub(crate) fn on_connected(&self, pipe_fd: ffi::CommandHandle, session_info: VpnSessionInfo) { info!("Connected to VPN, pipe_fd: {}", pipe_fd); if let Some(callback) = self.callback.write().unwrap().take() { @@ -277,7 +289,7 @@ impl Vpn { } } - pub(crate) fn attach_command_pipe(&self, fd: i32) -> bool { + pub(crate) fn attach_command_pipe(&self, fd: ffi::CommandHandle) -> bool { self.cancellation.attach(fd) } @@ -311,9 +323,15 @@ impl Vpn { .network_configuration_handler .as_ref() .map(|_| ffi::configure_network as _), - interface: Self::option_to_ptr(&self.interface), + interface_name: Self::option_to_ptr(&self.interface), script_tun: self.script_tun as u32, script_tun_launch: std::ptr::null(), + #[cfg(windows)] + script_tun_pipe: self + .script_tun_pipe + .as_ref() + .map(|handle| handle.as_raw_handle() as isize) + .unwrap_or(-1), certificate: Self::option_to_ptr(&self.certificate), sslkey: Self::option_to_ptr(&self.sslkey), @@ -366,6 +384,7 @@ impl fmt::Display for VpnError { impl std::error::Error for VpnError {} +#[cfg(unix)] struct ScriptTunLaunch { program: CString, arguments: Vec, @@ -381,7 +400,10 @@ pub struct VpnBuilder { script_is_path: bool, interface: Option, script_tun: bool, + #[cfg(unix)] script_tun_launch: Option, + #[cfg(windows)] + script_tun_pipe: Option, user_agent: Option, os: Option, @@ -416,7 +438,10 @@ impl VpnBuilder { script_is_path: false, interface: None, script_tun: false, + #[cfg(unix)] script_tun_launch: None, + #[cfg(windows)] + script_tun_pipe: None, user_agent: None, os: None, @@ -469,6 +494,7 @@ impl VpnBuilder { self } + #[cfg(unix)] pub fn script_tun_program( mut self, program: &str, @@ -495,6 +521,19 @@ impl VpnBuilder { Ok(self) } + /// Deliver packets through a connected Windows message-mode pipe. + /// + /// # Safety + /// The handle must use overlapped I/O and must not be associated with an IOCP. + /// OpenConnect duplicates it and owns its own completion events; attaching a + /// Tokio/Mio handle would send native OVERLAPPED completions into that reactor. + #[cfg(windows)] + pub unsafe fn script_tun_pipe(mut self, pipe: OwnedHandle) -> Self { + self.script_tun = true; + self.script_tun_pipe = Some(pipe); + self + } + pub fn script_tun(mut self, script_tun: bool) -> Self { self.script_tun = script_tun; self @@ -596,9 +635,17 @@ impl VpnBuilder { } return Ok(None); } + #[cfg(unix)] if self.script_tun_launch.is_some() { return Ok(None); } + #[cfg(windows)] + if self.script_tun_pipe.is_some() { + if self.script.is_some() || !self.script_tun { + return Err(VpnError::new("Packet pipe conflicts with script options".into())); + } + return Ok(None); + } let script = match &self.script { Some(script) => { if self.script_is_path && !std::path::Path::new(script).exists() { @@ -618,6 +665,7 @@ impl VpnBuilder { } pub fn build(self) -> Result { + #[cfg(unix)] if self.script_tun_launch.is_some() && !self.script_tun { return Err(VpnError::new("Child identity requires script-tun".into())); } @@ -642,7 +690,10 @@ impl VpnBuilder { network_configuration_handler: self.network_configuration_handler, interface: self.interface.as_deref().map(Self::to_cstring), script_tun: self.script_tun, + #[cfg(unix)] script_tun_launch: self.script_tun_launch, + #[cfg(windows)] + script_tun_pipe: self.script_tun_pipe, certificate: self.certificate.as_deref().map(Self::to_cstring), sslkey: self.sslkey.as_deref().map(Self::to_cstring), @@ -774,7 +825,10 @@ mod tests { network_configuration_handler: None, interface: None, script_tun: false, + #[cfg(unix)] script_tun_launch: None, + #[cfg(windows)] + script_tun_pipe: None, certificate: None, sslkey: None, key_password: None, @@ -1078,6 +1132,7 @@ mod tests { } #[unsafe(no_mangle)] +#[cfg(unix)] extern "C" fn vpn_script_started(data: *mut std::ffi::c_void) { // Native setup has forked or failed; only the child may retain this endpoint. let vpn = unsafe { &*(data as *const Vpn) }; diff --git a/crates/openconnect/tests/windows_packet_pipe.c b/crates/openconnect/tests/windows_packet_pipe.c new file mode 100644 index 0000000..2a229ee --- /dev/null +++ b/crates/openconnect/tests/windows_packet_pipe.c @@ -0,0 +1,169 @@ +/* Exercise the DLL's packet mainloop without a VPN server or kernel adapter. */ +#include "config.h" +#include "openconnect-internal.h" +#include + +struct test_context { + wchar_t name[128]; + SOCKET command; + int mode, seeded; + volatile LONG statistics; +}; +static void progress(void *data, int level, const char *format, ...) +{ + (void)data; (void)level; (void)format; +} +static void statistics(void *data, const struct oc_stats *stats) +{ + struct test_context *context = data; + (void)stats; + InterlockedIncrement(&context->statistics); +} +static int pump(struct openconnect_info *vpninfo, int *timeout, int readable) +{ + struct test_context *context = vpninfo->cbdata; + struct pkt *packet; + int work = 0; + (void)timeout; (void)readable; + vpninfo->need_poll_cmd_fd = 1; + while ((packet = dequeue_packet(&vpninfo->outgoing_queue))) { + queue_packet(&vpninfo->incoming_queue, packet); + work = 1; + } + if (context->mode == 2 && !context->seeded) { + int index; + context->seeded = 1; + for (index = 0; index < 32; index++) { + packet = calloc(1, sizeof(*packet) + 1500); + assert(packet); + packet->len = 1500; + memset(packet->data, index, packet->len); + queue_packet(&vpninfo->incoming_queue, packet); + } + work = 1; + } + return work; +} +static const struct vpn_proto protocol = { .name = "packet-test", .tcp_mainloop = pump }; +static DWORD WINAPI client(void *data) +{ + struct test_context *context = data; + HANDLE pipe = CreateFileW(context->name, GENERIC_READ | GENERIC_WRITE, 0, NULL, + OPEN_EXISTING, 0, NULL); + DWORD mode = PIPE_READMODE_MESSAGE, count; + char bytes[1024], response[1024], command; + assert(pipe != INVALID_HANDLE_VALUE); + assert(SetNamedPipeHandleState(pipe, &mode, NULL, NULL)); + if (context->mode == 0) { + int index; + for (index = 0; index < 2; index++) { + DWORD length = 257 + index * 97; + memset(bytes, 'a' + index, length); + assert(WriteFile(pipe, bytes, length, &count, NULL) && count == length); + assert(ReadFile(pipe, response, sizeof(response), &count, NULL) && count == length); + assert(!memcmp(bytes, response, length)); + } + } else if (context->mode == 3) { + /* Free before mainloop must close the duplicate and drain its read. */ + assert(!ReadFile(pipe, response, sizeof(response), &count, NULL)); + assert(GetLastError() == ERROR_BROKEN_PIPE); + } else { + /* No reads: mode 2 fills the service-to-worker packet buffer. */ + Sleep(100); + command = OC_CMD_STATS; + assert(send(context->command, &command, 1, 0) == 1); + Sleep(100); + command = OC_CMD_CANCEL; + assert(send(context->command, &command, 1, 0) == 1); + Sleep(100); + } + CloseHandle(pipe); + return 0; +} +static DWORD WINAPI watchdog(void *event) +{ + if (WaitForSingleObject(event, 15000) == WAIT_TIMEOUT) { + fputs("FAIL: packet pipe test timed out\n", stderr); + ExitProcess(99); + } + return 0; +} +static void run(int mode) +{ + struct test_context context = { .mode = mode }; + struct openconnect_info *vpninfo; + HANDLE pipe, thread, event; + OVERLAPPED connected = { 0 }; + DWORD count; + ULONGLONG started; + int result; + swprintf(context.name, 128, L"\\\\.\\pipe\\GPConnect.NativePacketTest.%lu.%d", GetCurrentProcessId(), mode); + pipe = CreateNamedPipeW(context.name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS, 1, 4096, 4096, 0, NULL); + assert(pipe != INVALID_HANDLE_VALUE); + vpninfo = openconnect_vpninfo_new("packet-test", NULL, NULL, NULL, progress, &context); + assert(vpninfo); + context.command = openconnect_setup_cmd_pipe(vpninfo); + assert(context.command != INVALID_SOCKET); + vpninfo->proto = &protocol; + vpninfo->dtls_state = DTLS_DISABLED; + vpninfo->ip_info.mtu = 1500; + openconnect_set_stats_handler(vpninfo, statistics); + thread = CreateThread(NULL, 0, client, &context, 0, NULL); + assert(thread); + event = CreateEvent(NULL, TRUE, FALSE, NULL); + assert(event); + connected.hEvent = event; + if (!ConnectNamedPipe(pipe, &connected)) { + DWORD error = GetLastError(); + if (error != ERROR_PIPE_CONNECTED) { + assert(error == ERROR_IO_PENDING); + assert(GetOverlappedResult(pipe, &connected, &count, TRUE)); + } + } + CloseHandle(event); + assert(!openconnect_setup_tun_pipe(vpninfo, (intptr_t)pipe)); + assert(vpninfo->tun_is_pipe && vpninfo->tun_fh != pipe); + CloseHandle(pipe); + started = GetTickCount64(); + if (mode == 3) { + vpninfo->tun_pkt = calloc(1, sizeof(struct pkt) + 1500); + assert(vpninfo->tun_pkt); + assert(!ReadFile(vpninfo->tun_fh, vpninfo->tun_pkt->data, 1500, &count, &vpninfo->tun_rd_overlap)); + assert(GetLastError() == ERROR_IO_PENDING); + vpninfo->tun_rd_pending = 1; + openconnect_vpninfo_free(vpninfo); + } else { + result = openconnect_mainloop(vpninfo, 1, 1); + assert(result < 0); + assert(vpninfo->tun_fh == INVALID_HANDLE_VALUE && !vpninfo->tun_rd_pending); + assert(!vpninfo->tun_rd_overlap.hEvent && !vpninfo->tun_wr_overlap.hEvent); + if (mode) { + assert(GetTickCount64() - started < 3000); + assert(context.statistics == 1); + if (mode == 2) + assert(vpninfo->stats.rx_pkts > 0 && vpninfo->stats.rx_pkts < 32); + } else { + assert(vpninfo->stats.rx_pkts == 2 && vpninfo->stats.tx_pkts == 2); + } + openconnect_vpninfo_free(vpninfo); + } + assert(WaitForSingleObject(thread, 2000) == WAIT_OBJECT_0); + CloseHandle(thread); + printf("PASS: native packet pipe case %d\n", mode); +} +int main(void) +{ + HANDLE stop = CreateEvent(NULL, TRUE, FALSE, NULL); + HANDLE guard = CreateThread(NULL, 0, watchdog, stop, 0, NULL); + int mode; + assert(stop && guard); + assert(!openconnect_init_ssl()); + for (mode = 0; mode < 4; mode++) + run(mode); + SetEvent(stop); + WaitForSingleObject(guard, 1000); + CloseHandle(guard); + CloseHandle(stop); + return 0; +} diff --git a/flake.nix b/flake.nix index fbe3122..6ab6057 100644 --- a/flake.nix +++ b/flake.nix @@ -86,7 +86,6 @@ linuxRuntimeDependencies = with pkgs; [ glib-networking - libayatana-appindicator xdg-utils ]; @@ -174,7 +173,6 @@ webkitgtk_4_1 glib-networking libsecret - libayatana-appindicator ]; installNixosPolkitRule = '' diff --git a/nix/gui-package.nix b/nix/gui-package.nix index b739f64..f2dc3c9 100644 --- a/nix/gui-package.nix +++ b/nix/gui-package.nix @@ -18,10 +18,10 @@ pkgs.stdenv.mkDerivation { ); buildInputs = with pkgs; [ gnutls ] ++ (if nativeShell then [ gtk4 ] else [ - gtk3 webkitgtk_4_1 libsoup_3 glib-networking libsecret libayatana-appindicator + gtk3 webkitgtk_4_1 libsoup_3 glib-networking libsecret ]); runtimeDependencies = [ pkgs.libglvnd ] ++ pkgs.lib.optionals (!nativeShell) [ - pkgs.glib-networking pkgs.libayatana-appindicator + pkgs.glib-networking ]; installPhase = '' runHook preInstall diff --git a/packaging/apk/APKBUILD.in b/packaging/apk/APKBUILD.in index c3e6940..90c243d 100644 --- a/packaging/apk/APKBUILD.in +++ b/packaging/apk/APKBUILD.in @@ -10,7 +10,6 @@ license="GPL-3.0-only" depends=" gmp gnutls - libayatana-appindicator libsecret libxml2 lz4 @@ -30,7 +29,6 @@ makedepends=" gmp-dev gnutls-dev gtk+3.0-dev - libayatana-appindicator-dev libsecret-dev librsvg-dev libtool diff --git a/packaging/aur/globalprotect-openconnect-git/PKGBUILD b/packaging/aur/globalprotect-openconnect-git/PKGBUILD index 1fb867b..0891833 100644 --- a/packaging/aur/globalprotect-openconnect-git/PKGBUILD +++ b/packaging/aur/globalprotect-openconnect-git/PKGBUILD @@ -10,7 +10,7 @@ url="https://github.com/yuezk/GlobalProtect-openconnect" license=('GPL3') makedepends=(git pkg-config make autoconf automake gettext libtool patch curl wget file appmenu-gtk-module librsvg cargo) -depends=(webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle libhogweed.so gmp shared-mime-info desktop-file-utils xdg-utils) +depends=(webkit2gtk-4.1 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle libhogweed.so gmp shared-mime-info desktop-file-utils xdg-utils) optdepends=('wmctrl: for window management') conflicts=('globalprotect-openconnect') diff --git a/packaging/bsd/freebsd/MANIFEST.in b/packaging/bsd/freebsd/MANIFEST.in index fc28b83..65afbe5 100644 --- a/packaging/bsd/freebsd/MANIFEST.in +++ b/packaging/bsd/freebsd/MANIFEST.in @@ -23,10 +23,6 @@ deps: { origin: "security/gnutls" version: "*" } - "libayatana-appindicator": { - origin: "devel/libayatana-appindicator" - version: "*" - } "liblz4": { origin: "archivers/liblz4" version: "*" diff --git a/packaging/deb/control.in b/packaging/deb/control.in index 7fc5110..a2773bf 100644 --- a/packaging/deb/control.in +++ b/packaging/deb/control.in @@ -19,7 +19,6 @@ Build-Depends: debhelper (>= 9), nettle-dev, libgmp-dev, libsecret-1-0, - libayatana-appindicator3-1, gnome-keyring, libwebkit2gtk-4.1-dev, cargo-@RUST_VERSION@, @@ -33,7 +32,6 @@ Depends: ${misc:Depends}, ${shlibs:Depends}, libsecret-1-0, - libayatana-appindicator3-1, gnome-keyring, xdg-utils, Description: A GUI client for GlobalProtect VPN diff --git a/packaging/pkgbuild/PKGBUILD.in b/packaging/pkgbuild/PKGBUILD.in index 2d86b40..a868e97 100644 --- a/packaging/pkgbuild/PKGBUILD.in +++ b/packaging/pkgbuild/PKGBUILD.in @@ -9,7 +9,7 @@ arch=('x86_64' 'aarch64') url="https://github.com/yuezk/GlobalProtect-openconnect" license=('GPL3') makedepends=('make' 'pkg-config' 'cargo' 'file' 'autoconf' 'automake' 'gettext' 'libtool' 'patch') -depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'appmenu-gtk-module' +depends=('webkit2gtk-4.1' 'librsvg' 'libsecret' 'appmenu-gtk-module' 'gnutls' 'libxml2' 'zlib' 'lz4' 'libp11-kit' 'nettle' 'libhogweed.so' 'gmp' 'xdg-utils') optdepends=('wmctrl: for window management') diff --git a/packaging/rpm/globalprotect-openconnect.spec.in b/packaging/rpm/globalprotect-openconnect.spec.in index 4fe2b10..d7953be 100644 --- a/packaging/rpm/globalprotect-openconnect.spec.in +++ b/packaging/rpm/globalprotect-openconnect.spec.in @@ -28,15 +28,9 @@ BuildRequires: file BuildRequires: perl BuildRequires: pkgconfig(webkit2gtk-4.1) -BuildRequires: (pkgconfig(appindicator3-0.1) or pkgconfig(ayatana-appindicator3-0.1)) BuildRequires: (librsvg2-devel or librsvg-devel) -%if 0%{?suse_version} -Requires: (libappindicator3-1 or libayatana-appindicator3-1) -%else -Requires: (libappindicator-gtk3 or libayatana-appindicator-gtk3) -%endif Requires: xdg-utils Conflicts: globalprotect-openconnect-snapshot diff --git a/packaging/windows/README.md b/packaging/windows/README.md new file mode 100644 index 0000000..aeffb86 --- /dev/null +++ b/packaging/windows/README.md @@ -0,0 +1,99 @@ +# Windows installer + +`installer.nsi` embeds a complete Windows payload and the canonical +`machine-install.ps1` installation implementation. Build it with NSIS 3 Unicode: + +```powershell +& makensis /DTARGET_ARCH=x64 /DPAYLOAD_DIR=C:\build\payload /DOUTPUT_FILE=C:\build\GPConnect-Setup.exe /DPRODUCT_VERSION=3.4.0 /DBUILD_VERSION=3.4.0.0 /DDISPLAY_VERSION=3.4.0-snapshot.2026.1114.2 .\packaging\windows\installer.nsi +``` + +`TARGET_ARCH` is `x64` or `arm64` and must match every executable and DLL in +the payload. Each installer accepts only its native Windows architecture. ARM64 +requires Windows 11; x64 requires Windows 10 build 19041 or newer. + +The native library build accepts `scripts/build-openconnect-windows.ps1 -TunnelType 'GP Connect'` +(the default). This passes OpenConnect's `--with-wintun-tunnel-type` build option; +OpenConnect itself defaults to `OpenConnect`. Wintun appends ` Tunnel` to the +selected type. The gateway-based connection name is unchanged. + +`BUILD_VERSION` must contain four numeric components. `PRODUCT_VERSION` must +match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release +identity, including the snapshot build when applicable. The payload must contain matching +`gpgui.exe`, `gpauth.exe`, `gpservice.exe`, their DLL dependency closure, the +vendor-signed `wintun.dll`, `licenses`, and `build-info.json`. The NSIS compiler +adds the generated uninstaller; it is not a separately built executable. + +The installer, extraction progress and uninstaller use the shared Windows icon +from `apps/gpauth/icons/windows/icon.ico`. The confirmation and Finish pages use `sidebar.bmp`, +derived from that same icon. After regenerating application icons, run +`powershell -NoProfile -File scripts/generate-windows-installer-artwork.ps1` +on Windows and retain the updated bitmap before building installers. + +The development ZIP includes the same machine implementation as +`installer/machine-install.ps1`. Its install/uninstall entrypoints call that +implementation rather than maintaining a second file replacement algorithm. +Use the EXE installer to upgrade an installation that already has an NSIS +uninstaller; the development ZIP does not contain that generated executable. + +Installation waits for the installed GUI/auth paths in all Windows sessions; +it does not stop arbitrary same-name processes. Service shutdown uses SCM, +checks the existing network-recovery criteria, and waits for file release. +Application files are staged under Program Files with protected ACLs. The old +directory is renamed to `GP Connect.previous` until the new service is Running. +Handled replacement/start failures restore old files and metadata and restart +the previous service. An interrupted installer with a retained backup requires +explicit repair; it is not automatically recovered. + +Disk use includes the downloaded installer and one expanded new payload. NSIS +extracts into its temporary directory, then the machine implementation consumes +those disposable files into protected staging instead of copying the whole bundle. +When temp and Program Files use different volumes, file moves may temporarily +duplicate the file currently being moved. The old installation is renamed, not +copied. The machine implementation checks the installation volume before staging; +NSIS extraction errors must complete before service shutdown. +Successful installation removes the old copy and staging. Installer logs keep +the current and previous attempt in ProgramData. No updater cache is added. + +The installer never launches the GUI as administrator. Users open GP Connect +from the Start menu after completion. User configuration and licensing state +are retained during upgrades and uninstall. Release builds use Azure Artifact +Signing with GitHub OIDC and RFC 3161 timestamps. Application executables, +the built OpenConnect DLL, and the generated NSIS uninstaller and installer +are signed before checksums and WinSparkle signatures are generated. +Vendor DLL signatures are preserved. WinSparkle independently verifies its +installer payload signature before handoff. + +The GitHub `windows-signing` environment is trusted by the Entra application +`gp-connect-github-signing`. Its only Azure role is Artifact Signing Certificate +Profile Signer on `tangramly-signing/certificateProfiles/gp-connect`. +Environment deployment policies allow the `release/next` branch and `v*` tags. +Repository variables supply `AZURE_SIGNING_CLIENT_ID`, `AZURE_TENANT_ID`, +`AZURE_SUBSCRIPTION_ID`, `AZURE_SIGNING_ENDPOINT`, `AZURE_SIGNING_ACCOUNT`, +`AZURE_SIGNING_PROFILE`, and `WINDOWS_SIGNING_PUBLISHER`. No Azure client secret +or Authenticode private key is stored in GitHub. `build-windows.ps1 -Sign` requires +Microsoft's ArtifactSigning PowerShell module 0.1.20 and an Azure CLI login. +The build verifies the publisher, certificate trust and timestamp on each signed +file. The installer smoke test repeats those checks on the installed runtime +and uninstaller before testing removal. + +The Start menu shortcut registers `System.AppUserModel.ID` as `com.yuezk.gpgui`, +matching the GUI and native toast sender. Windows uses the shortcut's name and +executable icon to identify GP Connect in Notification Center. Its identity is +part of the shortcut, so the existing shortcut rollback and uninstall own its cleanup. + +Manual launches show an Install/Cancel confirmation page (Update/Cancel when +GP Connect is already installed). The update feed supplies `/UPDATE` through +WinSparkle's `sparkle:installerArguments` to skip that page after the user has +already confirmed the in-app update. This is not silent mode: elevation, +installation progress, errors, and the Finish page remain visible. + +The service log rotates after 5 MiB and retains three numbered archives, keeping +each entry whole. The bundle includes `licenses/file-rotate.txt` for the Windows +service's rotation library. + +On a disposable Windows installation, verify a normal A-to-B upgrade and a B +payload whose `gpservice.exe` is replaced with another valid PE executable that +cannot host a Windows service. The latter must fail service startup, restore A's +files and uninstall metadata, and leave A's service running. Also check held +runtime files, active GUI/auth windows, Wintun-signature failure, and concurrent +installer attempts. Do not run failure fixtures against a live company VPN. diff --git a/packaging/windows/installer.nsi b/packaging/windows/installer.nsi new file mode 100644 index 0000000..3d0b198 --- /dev/null +++ b/packaging/windows/installer.nsi @@ -0,0 +1,127 @@ +Unicode true +RequestExecutionLevel admin +!include "MUI2.nsh" +!include "x64.nsh" +!include "FileFunc.nsh" + +!ifndef PAYLOAD_DIR + !error "PAYLOAD_DIR is required" +!endif +!ifndef OUTPUT_FILE + !error "OUTPUT_FILE is required" +!endif +!ifndef PRODUCT_VERSION + !error "PRODUCT_VERSION is required" +!endif +!ifndef TARGET_ARCH + !define TARGET_ARCH "x64" +!endif +!ifndef BUILD_VERSION + !define BUILD_VERSION "${PRODUCT_VERSION}.0" +!endif +!ifndef DISPLAY_VERSION + !define DISPLAY_VERSION "${PRODUCT_VERSION}" +!endif +!ifdef SIGN_SCRIPT + !uninstfinalize 'pwsh -NoLogo -NoProfile -NonInteractive -File "${SIGN_SCRIPT}" -Files "%1"' = 0 + !finalize 'pwsh -NoLogo -NoProfile -NonInteractive -File "${SIGN_SCRIPT}" -Files "%1"' = 0 +!endif + +Name "GP Connect" +OutFile "${OUTPUT_FILE}" +InstallDir "$PROGRAMFILES64\GP Connect" +VIProductVersion "${BUILD_VERSION}" +VIAddVersionKey "ProductName" "GP Connect" +VIAddVersionKey "FileDescription" "GP Connect Installer" +VIAddVersionKey "ProductVersion" "${DISPLAY_VERSION}" +VIAddVersionKey "FileVersion" "${BUILD_VERSION}" +VIAddVersionKey "LegalCopyright" "GP Connect contributors" +ShowInstDetails show +ShowUninstDetails show +Var InstallAction +!define MUI_ICON "${__FILEDIR__}\..\..\apps\gpauth\icons\windows\icon.ico" +!define MUI_UNICON "${MUI_ICON}" +!define MUI_WELCOMEFINISHPAGE_BITMAP "${__FILEDIR__}\sidebar.bmp" +!define MUI_ABORTWARNING +!define MUI_FINISHPAGE_TITLE "GP Connect is ready" +!define MUI_FINISHPAGE_TEXT "Open GP Connect from the Start menu." +!define MUI_WELCOMEPAGE_TITLE "$InstallAction GP Connect" +!define MUI_WELCOMEPAGE_TEXT "$InstallAction GP Connect for all users on this computer.$\r$\n$\r$\nClick $InstallAction to continue." +!define MUI_PAGE_CUSTOMFUNCTION_PRE ConfirmInstall +!define MUI_PAGE_CUSTOMFUNCTION_SHOW ShowInstallAction +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_INSTFILES +!insertmacro MUI_PAGE_FINISH +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES +!insertmacro MUI_LANGUAGE "English" + +Function .onInit +!if "${TARGET_ARCH}" == "arm64" + ${IfNot} ${IsNativeARM64} + MessageBox MB_OK|MB_ICONSTOP "This GP Connect installer requires Windows 11 on ARM64." /SD IDOK + SetErrorLevel 1 + Abort + ${EndIf} +!else if "${TARGET_ARCH}" == "x64" + ${IfNot} ${IsNativeAMD64} + MessageBox MB_OK|MB_ICONSTOP "This GP Connect installer requires x64 Windows." /SD IDOK + SetErrorLevel 1 + Abort + ${EndIf} +!else + !error "Unsupported TARGET_ARCH" +!endif + SetRegView 64 + StrCpy $InstallAction "Install" + ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect" "DisplayVersion" + ${If} $0 != "" + StrCpy $InstallAction "Update" + ${EndIf} +FunctionEnd + +Function ConfirmInstall + ${GetParameters} $0 + ClearErrors + ${GetOptions} $0 "/UPDATE" $1 + ${IfNot} ${Errors} + Abort + ${EndIf} +FunctionEnd + +Function ShowInstallAction + GetDlgItem $0 $HWNDPARENT 1 + SendMessage $0 ${WM_SETTEXT} 0 "STR:$InstallAction" +FunctionEnd + +Section "Install" + InitPluginsDir + SetOutPath "$PLUGINSDIR\payload" + File /r "${PAYLOAD_DIR}\*" + WriteUninstaller "$PLUGINSDIR\payload\uninstall.exe" + SetOutPath "$PLUGINSDIR" + File "${__FILEDIR__}\machine-install.ps1" + DetailPrint "Preparing GP Connect and waiting for open windows to close..." + nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\machine-install.ps1" -Action Install -SourceDirectory "$PLUGINSDIR\payload" -Version "${PRODUCT_VERSION}" -ConsumeSource' + Pop $0 + ${If} $0 != 0 + MessageBox MB_OK|MB_ICONSTOP "GP Connect could not be installed. See the details below and try again." /SD IDOK + SetErrorLevel 1 + Abort + ${EndIf} +SectionEnd + +Section "Uninstall" + SetRegView 64 + InitPluginsDir + SetOutPath "$PLUGINSDIR" + File "${__FILEDIR__}\machine-install.ps1" + DetailPrint "Waiting for GP Connect and sign-in windows to close..." + nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\machine-install.ps1" -Action Uninstall' + Pop $0 + ${If} $0 != 0 + MessageBox MB_OK|MB_ICONSTOP "GP Connect could not be removed. See the details below and try again." /SD IDOK + SetErrorLevel 1 + Abort + ${EndIf} +SectionEnd diff --git a/packaging/windows/licenses/file-rotate.txt b/packaging/windows/licenses/file-rotate.txt new file mode 100644 index 0000000..5a75d5a --- /dev/null +++ b/packaging/windows/licenses/file-rotate.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 BourgondAries + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packaging/windows/machine-install.ps1 b/packaging/windows/machine-install.ps1 new file mode 100644 index 0000000..1c53508 --- /dev/null +++ b/packaging/windows/machine-install.ps1 @@ -0,0 +1,437 @@ +#Requires -RunAsAdministrator +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][ValidateSet('Install', 'Uninstall')][string]$Action, + [string]$SourceDirectory, + [string]$Version, + [switch]$ConsumeSource +) +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +if ($PSVersionTable.PSEdition -eq 'Desktop') { + # A PowerShell 7 caller can pass incompatible modules to Windows PowerShell. + $env:PSModulePath = Join-Path $PSHOME 'Modules' +} +if (![Environment]::Is64BitProcess) { throw 'Run the GP Connect installer with 64-bit PowerShell.' } +$destination = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'GP Connect' +$state = Join-Path $env:ProgramData 'GP Connect' +$serviceName = 'GPConnect' +$serviceBinary = Join-Path $destination 'gpservice.exe' +$shortcutPath = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk' +$uninstallKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect' +$recoveryKey = 'HKLM:\SOFTWARE\GP Connect\NetworkRecovery' +$publicAcl = 'O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FRFX;;;BU)' +$privateAcl = 'O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)' +$backup = $destination + '.previous' +$stage = $null +$oldMoved = $false +$newMoved = $false +$serviceStopped = $false +$createdService = $false +$committed = $false +$oldMetadata = $null +$oldShortcut = $null + +function Assert-RegularDirectory([string]$Path) { + if (Test-Path -LiteralPath $Path) { + $item = Get-Item -LiteralPath $Path -Force + if (!$item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw "The installation folder must be a regular directory: $Path" + } + } +} + +function Set-DirectoryAcl([string]$Path, [string]$Descriptor) { + Assert-RegularDirectory $Path + if (!(Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path | Out-Null } + $acl = Get-Acl -LiteralPath $Path + $acl.SetSecurityDescriptorSddlForm($Descriptor) + Set-Acl -LiteralPath $Path -AclObject $acl +} + +function Wait-ForApplications { + $deadline = [DateTime]::UtcNow.AddSeconds(30) + do { + $running = @(Get-CimInstance Win32_Process -Filter "Name='gpgui.exe' OR Name='gpauth.exe'" | + Where-Object { $_.ExecutablePath -in @((Join-Path $destination 'gpgui.exe'), (Join-Path $destination 'gpauth.exe')) }) + if (!$running.Count) { return } + if ([DateTime]::UtcNow -ge $deadline) { + throw 'Quit GP Connect and finish or cancel sign-in in all Windows sessions, then try again.' + } + Start-Sleep -Milliseconds 250 + } while ($true) +} + +function Wait-ServiceState([string]$Expected) { + $controller = Get-Service -Name $serviceName + try { $controller.WaitForStatus($Expected, [TimeSpan]::FromSeconds(30)) } + finally { $controller.Dispose() } +} + +function Stop-InstalledService { + $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue + if (!$service) { return } + try { $stopped = $service.Status -eq 'Stopped' } finally { $service.Dispose() } + if (!$stopped) { Stop-Service -Name $serviceName; Wait-ServiceState 'Stopped' } +} + +function Start-InstalledService { + Start-Service -Name $serviceName + Wait-ServiceState 'Running' +} + +function Move-InstalledDirectoryToBackup { + try { Move-Item -LiteralPath $destination -Destination $backup } + catch [IO.IOException] { + throw 'GP Connect files are in use. Close any GP Connect folders in File Explorer and try again.' + } +} + +function Wait-ForRuntimeRelease { + $deadline = [DateTime]::UtcNow.AddSeconds(30) + do { + $locked = $false + foreach ($file in Get-ChildItem -LiteralPath $destination -File | Where-Object { $_.Extension -in @('.exe', '.dll') }) { + try { + $stream = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) + $stream.Dispose() + } catch [IO.IOException] { $locked = $true; break } + } + if (!$locked) { return } + if ([DateTime]::UtcNow -ge $deadline) { throw 'An application file is still in use. Close GP Connect in all Windows sessions and try again.' } + Start-Sleep -Milliseconds 250 + } while ($true) +} + +function Assert-NetworkClean { + $records = @() + if (Test-Path $recoveryKey) { $records = @((Get-Item $recoveryKey).GetValueNames() | Where-Object { $_ -like 'Route-*' }) } + $policies = @(Get-DnsClientNrptRule | Where-Object { $_.Comment -like 'GPConnect:*' }) + if ($records.Count -or $policies.Count) { + throw 'VPN network cleanup is incomplete. Restart GP Connect before trying again.' + } +} + +function Invoke-ServiceCommand([string[]]$Arguments) { + & "$env:SystemRoot\System32\sc.exe" @Arguments | Out-Null + if ($LASTEXITCODE -ne 0) { throw "Windows service configuration failed ($LASTEXITCODE)." } +} + +function Set-MachineState { + Set-DirectoryAcl $state $publicAcl + Set-DirectoryAcl (Join-Path $state 'Private') $privateAcl + foreach ($name in @('gpservice.lock', 'gpservice.log')) { + $path = Join-Path $state $name + if (Test-Path -LiteralPath $path) { + if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { + throw "Service state file must not be a link: $path" + } + $acl = Get-Acl -LiteralPath $path + $acl.SetSecurityDescriptorSddlForm($publicAcl) + Set-Acl -LiteralPath $path -AclObject $acl + } + } + $registry = [Microsoft.Win32.Registry]::LocalMachine.CreateSubKey('SOFTWARE\GP Connect') + try { + $recovery = $registry.CreateSubKey('NetworkRecovery', [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [Microsoft.Win32.RegistryOptions]::Volatile) + try { + foreach ($key in @($registry, $recovery)) { + $acl = New-Object System.Security.AccessControl.RegistrySecurity + $acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;CI;KA;;;SY)(A;CI;KA;;;BA)') + $key.SetAccessControl($acl) + } + } finally { $recovery.Dispose() } + } finally { $registry.Dispose() } +} + +function Set-ShortcutAppUserModelId([string]$Path, [string]$ApplicationId) { + if (-not ('GPConnect.Installer.ShortcutIdentity' -as [type])) { + # NSIS also extracts a native System.dll; reference the loaded .NET assembly explicitly. + Add-Type -ReferencedAssemblies ([System.Uri].Assembly.Location) -TypeDefinition @' +using System; +using System.Runtime.InteropServices; + +namespace GPConnect.Installer { + public static class ShortcutIdentity { + [StructLayout(LayoutKind.Sequential)] + private struct PropertyKey { public Guid Format; public uint Id; } + + // PROPVARIANT is 24 bytes in both supported 64-bit architectures. + [StructLayout(LayoutKind.Explicit, Size = 24)] + private struct PropVariant { + [FieldOffset(0)] public ushort Type; + [FieldOffset(8)] public IntPtr Value; + } + + [ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IPropertyStore { + void GetCount(out uint count); + void GetAt(uint index, out PropertyKey key); + void GetValue(ref PropertyKey key, out PropVariant value); + void SetValue(ref PropertyKey key, ref PropVariant value); + void Commit(); + } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] + private static extern void SHGetPropertyStoreFromParsingName( + string path, IntPtr context, uint flags, ref Guid iid, out IPropertyStore store); + + public static void Set(string path, string applicationId) { + var iid = typeof(IPropertyStore).GUID; + IPropertyStore store; + SHGetPropertyStoreFromParsingName(path, IntPtr.Zero, 2, ref iid, out store); // GPS_READWRITE + var value = new PropVariant { Type = 31, Value = Marshal.StringToCoTaskMemUni(applicationId) }; // VT_LPWSTR + try { + var key = new PropertyKey { Format = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), Id = 5 }; + store.SetValue(ref key, ref value); // PKEY_AppUserModel_ID + store.Commit(); + } finally { + Marshal.FreeCoTaskMem(value.Value); + Marshal.ReleaseComObject(store); + } + } + } +} +'@ + } + [GPConnect.Installer.ShortcutIdentity]::Set($Path, $ApplicationId) +} + +function Set-InstallationMetadata([string]$InstalledVersion) { + $shell = New-Object -ComObject WScript.Shell + $shortcut = $shell.CreateShortcut($shortcutPath) + $shortcut.TargetPath = Join-Path $destination 'gpgui.exe' + $shortcut.WorkingDirectory = $destination + $shortcut.Description = 'A GUI client for GlobalProtect VPN' + $shortcut.IconLocation = (Join-Path $destination 'gpgui.exe') + ',0' + $shortcut.Save() + Set-ShortcutAppUserModelId $shortcutPath 'com.yuezk.gpgui' + if (Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) { + New-Item -Path $uninstallKey -Force | Out-Null + $values = @{ + DisplayName = 'GP Connect'; DisplayVersion = $InstalledVersion; Publisher = 'GP Connect' + InstallLocation = $destination; DisplayIcon = (Join-Path $destination 'gpgui.exe') + UninstallString = '"' + (Join-Path $destination 'uninstall.exe') + '"' + } + foreach ($entry in $values.GetEnumerator()) { + New-ItemProperty -Path $uninstallKey -Name $entry.Key -Value $entry.Value -PropertyType String -Force | Out-Null + } + foreach ($name in @('NoModify', 'NoRepair')) { + New-ItemProperty -Path $uninstallKey -Name $name -Value 1 -PropertyType DWord -Force | Out-Null + } + } +} + +function Restore-InstallationMetadata { + if (Test-Path $uninstallKey) { Remove-Item $uninstallKey -Recurse -Force } + if ($oldMetadata) { + New-Item -Path $uninstallKey -Force | Out-Null + foreach ($entry in $oldMetadata.GetEnumerator()) { + New-ItemProperty -Path $uninstallKey -Name $entry.Key -Value $entry.Value.Value -PropertyType $entry.Value.Kind -Force | Out-Null + } + } + if ($oldShortcut) { [IO.File]::WriteAllBytes($shortcutPath, $oldShortcut) } + elseif (Test-Path -LiteralPath $shortcutPath) { Remove-Item -LiteralPath $shortcutPath -Force } +} + +function Remove-OwnedCallback { + $callback = 'HKCU:\Software\Classes\globalprotectcallback' + $commandKey = "$callback\shell\open\command" + if (Test-Path $commandKey) { + $command = (Get-Item $commandKey).GetValue('') + $authBinary = Join-Path $destination 'gpauth.exe' + $owned = @("`"$authBinary`" auth-callback `"%1`"", "`"\\?\$authBinary`" auth-callback `"%1`"") + if ($command -in $owned) { Remove-Item $callback -Recurse -Force } + } +} + +$mutex = New-Object System.Threading.Mutex($false, 'Global\GPConnect.Installer') +$owned = $false +$transcript = $false +try { + try { $owned = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $owned = $true } + if (!$owned) { throw 'Another GP Connect installation is running. Wait for it to finish.' } + Assert-RegularDirectory $destination + Assert-RegularDirectory $state + if (Test-Path -LiteralPath $backup) { + throw "A previous installation needs repair. The retained files are in $backup. Do not delete them before restoring GP Connect." + } + # Keep only this attempt and one previous diagnostic log. + Set-DirectoryAcl $state $publicAcl + $log = Join-Path $state 'installer.log' + $previousLog = Join-Path $state 'installer.previous.log' + foreach ($path in @($log, $previousLog)) { + if ((Test-Path -LiteralPath $path) -and ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw 'Installer log must not be a link.' + } + } + if (Test-Path -LiteralPath $previousLog) { Remove-Item -LiteralPath $previousLog -Force } + if (Test-Path -LiteralPath $log) { Move-Item -LiteralPath $log -Destination $previousLog } + Start-Transcript -Path $log -Force | Out-Null + $transcript = $true + $existing = Get-CimInstance Win32_Service -Filter "Name='$serviceName'" + if ($existing -and $existing.PathName -ne ('"' + $serviceBinary + '"')) { + throw 'The GPConnect service is registered to another installation.' + } + $wasRunning = $existing -and $existing.State -ne 'Stopped' + + if ($Action -eq 'Install') { + if (!$SourceDirectory) { throw 'An installation source is required.' } + $source = (Resolve-Path -LiteralPath $SourceDirectory).Path.TrimEnd('\') + if ($source -eq $destination -or $source.StartsWith($destination + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw 'Install from an extracted package outside the application folder.' + } + foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) { + if (!(Test-Path -LiteralPath (Join-Path $source $name) -PathType Leaf)) { throw "Missing Windows package file: $name" } + } + $info = Get-Content -LiteralPath (Join-Path $source 'build-info.json') -Raw | ConvertFrom-Json + if ((Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) -and + !(Test-Path -LiteralPath (Join-Path $source 'uninstall.exe'))) { + throw 'Use the Windows installer to update this installation.' + } + if (!$Version) { $Version = $info.version } + $architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant() + if ($info.product -ne 'GP Connect' -or $info.architecture -notin @('x64','arm64') -or $info.architecture -ne $architecture -or !$Version -or $info.version -ne $Version) { + throw 'The package version or architecture does not match this installer.' + } + if (![Environment]::Is64BitProcess -or [Environment]::OSVersion.Version.Build -lt 19041) { + throw 'GP Connect requires Windows 10 build 19041 or newer.' + } + if ($architecture -eq 'arm64' -and [Environment]::OSVersion.Version.Build -lt 22000) { + throw 'GP Connect for ARM64 requires Windows 11.' + } + $payload = @(Get-ChildItem -LiteralPath $source -Force | Where-Object { + ($_.PSIsContainer -and $_.Name -eq 'licenses') -or + (!$_.PSIsContainer -and ($_.Extension -eq '.dll' -or + $_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'uninstall.exe', 'build-info.json'))) + }) + foreach ($item in $payload) { + $items = @($item) + if ($item.PSIsContainer) { $items += @(Get-ChildItem -LiteralPath $item.FullName -Force -Recurse) } + if ($items | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint }) { throw 'The package must not contain file links.' } + } + $requiredBytes = [long]0 + foreach ($item in $payload) { + if ($item.PSIsContainer) { $requiredBytes += [long](Get-ChildItem -LiteralPath $item.FullName -File -Recurse | Measure-Object -Property Length -Sum).Sum } + else { $requiredBytes += $item.Length } + } + $volume = New-Object IO.DriveInfo([IO.Path]::GetPathRoot($destination)) + $additionalBytes = $requiredBytes + 16MB + if ($ConsumeSource -and [IO.Path]::GetPathRoot($source) -eq $volume.Name) { + # The extracted files already occupy this volume; renaming them adds no copy. + $additionalBytes = 16MB + } + if ($volume.AvailableFreeSpace -lt $additionalBytes) { throw 'There is not enough free space to install GP Connect.' } + $stage = $destination + '.stage-' + [Guid]::NewGuid().ToString('N') + Set-DirectoryAcl $stage $publicAcl + foreach ($item in $payload) { + if (!$ConsumeSource) { + Copy-Item -LiteralPath $item.FullName -Destination $stage -Recurse -Force + continue + } + # NSIS's extracted payload is disposable. Move files individually so temp + # and Program Files may be on different volumes without keeping two bundles. + $files = @($item) + if ($item.PSIsContainer) { $files = @(Get-ChildItem -LiteralPath $item.FullName -File -Recurse) } + foreach ($file in $files) { + $relative = $file.Name + if ($item.PSIsContainer) { + # Enumerated paths share the same expanded spelling, including 8.3 temp paths. + $child = $file.FullName.Substring($item.FullName.Length).TrimStart('\') + $relative = Join-Path $item.Name $child + } + $target = Join-Path $stage $relative + $parent = Split-Path $target -Parent + if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } + Move-Item -LiteralPath $file.FullName -Destination $target + } + } + # Copies inherit the staging directory's protected policy, even when source ACLs differ. + foreach ($item in Get-ChildItem -LiteralPath $stage -Force -Recurse) { + $acl = Get-Acl -LiteralPath $item.FullName + $acl.SetSecurityDescriptorSddlForm($publicAcl) + Set-Acl -LiteralPath $item.FullName -AclObject $acl + } + $signature = Get-AuthenticodeSignature (Join-Path $stage 'wintun.dll') + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'WireGuard LLC') { + throw 'The package requires the vendor-signed Wintun driver DLL.' + } + if ((Test-Path -LiteralPath $destination) -and !$existing) { throw 'The service is not registered. Repair the existing installation before updating.' } + if ($existing -and !(Test-Path -LiteralPath $destination)) { throw 'The registered installation is missing. Restore its files before updating.' } + if (Test-Path $uninstallKey) { + $key = Get-Item $uninstallKey + $oldMetadata = @{} + foreach ($name in $key.GetValueNames()) { $oldMetadata[$name] = @{ Value = $key.GetValue($name); Kind = $key.GetValueKind($name).ToString() } } + } + if (Test-Path -LiteralPath $shortcutPath) { $oldShortcut = [IO.File]::ReadAllBytes($shortcutPath) } + Wait-ForApplications + if ($existing) { + $serviceStopped = $true + Stop-InstalledService + Assert-NetworkClean + Wait-ForRuntimeRelease + } + if (Test-Path -LiteralPath $destination) { Move-InstalledDirectoryToBackup; $oldMoved = $true } + Move-Item -LiteralPath $stage -Destination $destination + $stage = $null + $newMoved = $true + Set-MachineState + if (!$existing) { + New-Service -Name $serviceName -DisplayName 'GP Connect' -BinaryPathName ('"' + $serviceBinary + '"') -StartupType Automatic -Description 'Connects GP Connect to your GlobalProtect VPN network.' | Out-Null + $createdService = $true + } else { Set-Service -Name $serviceName -StartupType Automatic } + Invoke-ServiceCommand @('failure', $serviceName, 'reset=', '86400', 'actions=', 'restart/3000/restart/10000/none/0') + Set-InstallationMetadata $Version + Start-InstalledService + $committed = $true + if ($oldMoved) { Remove-Item -LiteralPath $backup -Recurse -Force; $oldMoved = $false } + Write-Host "Installed GP Connect $Version. Open it from the Start menu." + } else { + if (!$existing) { + if (Test-Path -LiteralPath $destination) { throw 'The service is not registered. Review the installation folder before removing it.' } + Write-Host 'GP Connect is not installed.' + return + } + Wait-ForApplications + $serviceStopped = $true + Stop-InstalledService + Assert-NetworkClean + Wait-ForRuntimeRelease + # Move first: a locked runtime aborts while its registration and files are intact. + Move-InstalledDirectoryToBackup + $oldMoved = $true + Invoke-ServiceCommand @('delete', $serviceName) + $committed = $true + Remove-Item -LiteralPath $backup -Recurse -Force + $oldMoved = $false + if (Test-Path -LiteralPath $shortcutPath) { Remove-Item -LiteralPath $shortcutPath -Force } + if (Test-Path $uninstallKey) { Remove-Item $uninstallKey -Recurse -Force } + if (Test-Path $recoveryKey) { Remove-Item $recoveryKey -Force } + Remove-OwnedCallback + Write-Host 'Removed GP Connect. User settings and service logs are kept.' + } +} catch { + $failure = $_ + if (!$committed) { + try { + if ($newMoved) { Stop-InstalledService; Remove-Item -LiteralPath $destination -Recurse -Force } + if ($oldMoved) { Move-Item -LiteralPath $backup -Destination $destination; $oldMoved = $false } + if ($createdService) { Invoke-ServiceCommand @('delete', $serviceName) } + if ($newMoved) { Restore-InstallationMetadata } + if ($existing -and $serviceStopped -and $wasRunning) { Start-InstalledService } + } catch { + Write-Host "Could not restore GP Connect: $($_.Exception.Message)" + Write-Host "Keep any retained files in $backup and run the installer again after restoring the installation." + } + } + Write-Host "Installation failed: $($failure.Exception.Message)" + Write-Host "Details: $(Join-Path $state 'installer.log')" + throw $failure +} finally { + if ($stage -and (Test-Path -LiteralPath $stage)) { + try { Remove-Item -LiteralPath $stage -Recurse -Force } catch { Write-Warning "Could not remove temporary files: $stage" } + } + if ($transcript) { Stop-Transcript | Out-Null } + if ($owned) { $mutex.ReleaseMutex() } + $mutex.Dispose() +} diff --git a/packaging/windows/sidebar.bmp b/packaging/windows/sidebar.bmp new file mode 100644 index 0000000000000000000000000000000000000000..9014f34536abe001cc6d3ba151a6174cad3165ee GIT binary patch literal 154542 zcmeI5_g`CSmgal*57-}eyQ_P4c6MgEx_i2+oJ|IaAfgapm$O}VIpBmtIh3)vW z{EuIu4;%RPXZTeMza0MVSHJqZU;PeVkspTt`Kw={U*?a0!yi}ytN>O3D}WWi3Sb4W z0$2g809F7ifEBO3 zD}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g8 z09F7ifEBO3D}WWi z3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7ifEBBkQr-v9XHkK{jOVr=yFv)hlZs;}!R&$T8R>yCDo>`)bKl5^I`*a4lnt5kWb zRe4{lII9#n0qt3SvYfT@{7s#ud%7A<_DM2t^$4EcIz9CA$-8&&$R9}j@DD%z^wVGa zLOcbm8bkl@f470`Kbnm^Hazh3hT)1L+fW&(D_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hP4$JzAf(AbmmsgkMH0A`z{mzDN2FcH`|(w z2l&?ymGtgHYiqn{<>V$%)xS_)~5hsVZ&>(lhBiqCARzVfZ0@A%{AcoI$F`j5UCd-b6ETvp@Ref3uk zG6kKyi?Ww!rA~GhXifGn&`~) zaomv1Yj{5K8hEx8JaPyP-|*N1uyc&gD@7lW-@U2&%8ughE#0@P-o6?Ck6s@B^RpCq z{-9f9h*aqhNDV=Co!bjKH)M6LPE!Y@=mL@qtC9@xIUr3Nz*YtnNdou{0ji=^hTK(T z;|}v@b29%+xSVnn!Ttr!yze-bp z!VG$r!RJ^xx2V>jRLf=>vVA*?R<-iix5&1&^#oQLwurC9KYn%Lud2c)^q0STGyeRR z_F6|mA9wdn(V+{xeW$Co8%sCo3)krKS8MWCX@D{U9YC`F*|<@WhMJt``f8vf6Lfbe zSr5;Jyvz^0)wsK_cK01k-s>N(d_qG1EnVvH57+MZRGb$cztptWRk0Z!+}Ex8tyFc;;SrSzq(X({;P9w(P$yI&ev_?_9&~)3rOgsB}}ipGI_QE6FCgG80bwZL1W$B5Q?tE~yX&%G&$Z@#7x}x-)bG9|iGFyF zKm5aWc;?h6s_ftJWq)`#IrRM2^BaoWhLTI-s9xT|o|>H(8v);bQ?vwKYuOJ?kBQh1 z-4r3N2=|`l?(C`E-OK;(nmpxRPtB|QJrhIN#ec)3XZ_ROP7IFp-+`wHy||@$bfM+` znfg1%(!1T|ce=`O3D}WWi3Sb4W0$2g809F7ifEBO3D}WWi3Sb4W0$2g809F7i zfEBO3D}WWi3Sb4W e0$2g809F7ifEB literal 0 HcmV?d00001 diff --git a/scripts/build-openconnect-windows.ps1 b/scripts/build-openconnect-windows.ps1 new file mode 100644 index 0000000..9b173e2 --- /dev/null +++ b/scripts/build-openconnect-windows.ps1 @@ -0,0 +1,71 @@ +# Requires MSYS2 base-devel/autoconf/automake/libtool and the selected native gcc, +# pkgconf, gnutls, libxml2 and lz4 packages, plus Visual Studio C++ Build Tools. +[CmdletBinding()] +param( + [string]$MsysRoot = 'C:\msys64', + [ValidateSet('mingw64','ucrt64','clangarm64')][string]$MsysSubsystem = 'mingw64', + [string]$Prefix, + [int]$Jobs = 4, + [ValidateNotNullOrEmpty()][string]$TunnelType = 'GP Connect' +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path $PSScriptRoot -Parent +if (!$Prefix) { $Prefix = Join-Path $repo 'target\native-windows' } +$Prefix = [System.IO.Path]::GetFullPath($Prefix) +$bash = Join-Path $MsysRoot 'usr\bin\bash.exe' +if (!(Test-Path $bash)) { throw 'MSYS2 is required to build OpenConnect.' } +$ErrorActionPreference = 'Continue' +& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem $TunnelType +$nativeExit = $LASTEXITCODE +$ErrorActionPreference = 'Stop' +if ($nativeExit -ne 0) { throw 'OpenConnect compilation failed.' } + +$architecture = 'x64' +if ($MsysSubsystem -eq 'clangarm64') { $architecture = 'arm64' } +$component = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' +if ($architecture -eq 'arm64') { $component = 'Microsoft.VisualStudio.Component.VC.Tools.ARM64' } +$hostTools = 'Hostx64' +if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { $hostTools = 'Hostarm64' } +$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" +$vs = & $vswhere -latest -products '*' -requires $component -property installationPath +if (!$vs) { throw 'Visual Studio C++ Build Tools are required.' } +$tools = (Get-ChildItem "$vs\VC\Tools\MSVC\*\bin\$hostTools\$architecture\lib.exe" | + Sort-Object FullName | Select-Object -Last 1).DirectoryName +$dll = Join-Path $Prefix 'bin\libopenconnect-5.dll' +$exports = & "$tools\dumpbin.exe" /nologo /exports $dll +if ($LASTEXITCODE -ne 0) { throw 'Could not inspect OpenConnect exports.' } +$names = @($exports | ForEach-Object { + if ($_ -match '^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)') { $Matches[1] } +}) +foreach ($symbol in @('openconnect_setup_cmd_pipe', 'openconnect_setup_tun_pipe', 'openconnect_set_configure_tun_handler', 'openconnect_set_tunnel_handler')) { + if ($names -notcontains $symbol) { throw "OpenConnect is missing $symbol." } +} +$definition = Join-Path $Prefix 'lib\openconnect.def' +[System.IO.File]::WriteAllLines($definition, @('LIBRARY libopenconnect-5.dll', 'EXPORTS') + $names) +& "$tools\lib.exe" /nologo "/machine:$architecture" "/def:$definition" "/out:$Prefix\lib\openconnect.lib" +if ($LASTEXITCODE -ne 0) { throw 'Could not generate the MSVC import library.' } + +# Copy only the native DLL's transitive MinGW runtime dependencies. +$pending = [System.Collections.Generic.Queue[string]]::new() +$visited = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) +$pending.Enqueue($dll) +while ($pending.Count) { + $current = $pending.Dequeue() + if (!$visited.Add([System.IO.Path]::GetFileName($current))) { continue } + $dependencies = & "$tools\dumpbin.exe" /nologo /dependents $current + if ($LASTEXITCODE -ne 0) { throw "Could not inspect dependencies of $current." } + foreach ($line in $dependencies) { + if ($line -notmatch '^\s+(\S+\.dll)\s*$') { continue } + $name = $Matches[1] + $source = Join-Path "$MsysRoot\$MsysSubsystem\bin" $name + if (Test-Path $source) { + $target = Join-Path "$Prefix\bin" $name + Copy-Item $source $target -Force + $pending.Enqueue($target) + } elseif (!(Test-Path "$env:SystemRoot\System32\$name") -and $name -notmatch '^(api|ext)-ms-win-') { + throw "Missing runtime dependency: $name" + } + } +} +Write-Host "OpenConnect native files: $Prefix" +Write-Host "Set OPENCONNECT_WINDOWS_PREFIX to this directory before building gpservice." diff --git a/scripts/build-openconnect-windows.sh b/scripts/build-openconnect-windows.sh new file mode 100644 index 0000000..294b512 --- /dev/null +++ b/scripts/build-openconnect-windows.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Build the bundled protocol library with MSYS2's native Windows compiler. +set -euo pipefail +subsystem=$4 +export PATH="/$subsystem/bin:/usr/bin:$PATH" +repo=$(cygpath -u "$1") +prefix=$(cygpath -u "$2") +jobs=$3 +tunnel_type=$5 +export ACLOCAL_PATH="/$subsystem/share/aclocal" +source_dir="$repo/crates/openconnect/deps/openconnect" +build_dir="$repo/target/openconnect-windows" +cd "$source_dir" +autoreconf -fi +mkdir -p "$build_dir" +cd "$build_dir" +host=x86_64-w64-mingw32 +if [[ $subsystem == clangarm64 ]]; then + host=aarch64-w64-mingw32 + export CC=clang AR=llvm-ar RANLIB=llvm-ranlib NM=llvm-nm +fi +"$source_dir/configure" --host="$host" --prefix="$prefix" \ + --enable-shared --disable-static --disable-nls --disable-docs --disable-dsa-tests \ + --without-libproxy --without-stoken --without-libpcsclite --without-libpskc \ + --without-gssapi --with-gnutls --without-openssl --with-gnutls-tss2=no \ + --with-vpnc-script=unused --with-wintun-tunnel-type="$tunnel_type" +grep -q '^#define OPENCONNECT_GNUTLS 1$' config.h +make -j"$jobs" libopenconnect.la +make install-libLTLIBRARIES +install -Dm644 "$source_dir/openconnect.h" "$prefix/include/openconnect.h" diff --git a/scripts/generate-windows-installer-artwork.ps1 b/scripts/generate-windows-installer-artwork.ps1 new file mode 100644 index 0000000..4894d05 --- /dev/null +++ b/scripts/generate-windows-installer-artwork.ps1 @@ -0,0 +1,33 @@ +# Regenerate the NSIS sidebar from the shared Windows application icon. +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Drawing +Add-Type -AssemblyName PresentationCore +$root = Split-Path $PSScriptRoot -Parent +$iconPath = Join-Path $root 'apps\gpauth\icons\windows\icon.ico' +$outputPath = Join-Path $root 'packaging\windows\sidebar.bmp' +# WPF decodes PNG-compressed ICO frames correctly; GDI+ Icon.ToBitmap does not. +$decoder = [Windows.Media.Imaging.BitmapDecoder]::Create( + [Uri]$iconPath, + [Windows.Media.Imaging.BitmapCreateOptions]::PreservePixelFormat, + [Windows.Media.Imaging.BitmapCacheOption]::OnLoad +) +$frame = $decoder.Frames | Sort-Object PixelWidth -Descending | Select-Object -First 1 +$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder +$encoder.Frames.Add($frame) +$stream = New-Object IO.MemoryStream +$encoder.Save($stream) +$stream.Position = 0 +$image = [Drawing.Image]::FromStream($stream) +$canvas = New-Object Drawing.Bitmap(164, 314, ([Drawing.Imaging.PixelFormat]::Format24bppRgb)) +$graphics = [Drawing.Graphics]::FromImage($canvas) +try { + $graphics.Clear([Drawing.Color]::White) + $graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic + $graphics.DrawImage($image, 34, 54, 96, 96) + $canvas.Save($outputPath, [Drawing.Imaging.ImageFormat]::Bmp) +} finally { + $graphics.Dispose() + $canvas.Dispose() + $image.Dispose() + $stream.Dispose() +} diff --git a/scripts/install-windows.ps1 b/scripts/install-windows.ps1 new file mode 100644 index 0000000..30d408e --- /dev/null +++ b/scripts/install-windows.ps1 @@ -0,0 +1,6 @@ +#Requires -RunAsAdministrator +[CmdletBinding()] +param([Parameter(Mandatory=$true)][string]$SourceDirectory) +$ErrorActionPreference = 'Stop' +$source = (Resolve-Path -LiteralPath $SourceDirectory).Path +& (Join-Path $source 'installer\machine-install.ps1') -Action Install -SourceDirectory $source diff --git a/scripts/sign-windows.ps1 b/scripts/sign-windows.ps1 new file mode 100644 index 0000000..7cd1447 --- /dev/null +++ b/scripts/sign-windows.ps1 @@ -0,0 +1,24 @@ +[CmdletBinding()] +param([Parameter(Mandatory=$true)][string[]]$Files) +$ErrorActionPreference = 'Stop' +foreach ($name in @('AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_SIGNING_PROFILE', 'WINDOWS_SIGNING_PUBLISHER')) { + if (![Environment]::GetEnvironmentVariable($name)) { throw "Missing signing configuration: $name" } +} +Import-Module ArtifactSigning -RequiredVersion 0.1.20 +$credentials = @{ + ExcludeEnvironmentCredential = $true + ExcludeWorkloadIdentityCredential = $true + ExcludeManagedIdentityCredential = $true + ExcludeSharedTokenCacheCredential = $true + ExcludeVisualStudioCredential = $true + ExcludeVisualStudioCodeCredential = $true + ExcludeAzurePowerShellCredential = $true + ExcludeAzureDeveloperCliCredential = $true + ExcludeInteractiveBrowserCredential = $true +} +# Azure CLI holds the short-lived GitHub OIDC login; no client secret is used. +Invoke-ArtifactSigning -Endpoint $env:AZURE_SIGNING_ENDPOINT ` + -CodeSigningAccountName $env:AZURE_SIGNING_ACCOUNT -CertificateProfileName $env:AZURE_SIGNING_PROFILE ` + -Files ($Files -join ',') -FileDigest SHA256 -TimestampDigest SHA256 ` + -TimestampRfc3161 'http://timestamp.acs.microsoft.com' -Description 'GP Connect' @credentials +& (Join-Path $PSScriptRoot 'test-windows-signature.ps1') -Files $Files -Publisher $env:WINDOWS_SIGNING_PUBLISHER diff --git a/scripts/test-openconnect-windows.ps1 b/scripts/test-openconnect-windows.ps1 new file mode 100644 index 0000000..8a534cc --- /dev/null +++ b/scripts/test-openconnect-windows.ps1 @@ -0,0 +1,7 @@ +[CmdletBinding()] +param([string]$MsysRoot = 'C:\msys64', [string]$Prefix = $env:OPENCONNECT_WINDOWS_PREFIX, + [ValidateSet('mingw64','ucrt64','clangarm64')][string]$MsysSubsystem = 'mingw64') +$repo = Split-Path $PSScriptRoot -Parent +if (!$Prefix) { $Prefix = Join-Path $repo 'target\native-windows' } +& "$MsysRoot\usr\bin\bash.exe" "$PSScriptRoot/test-openconnect-windows.sh" $repo $Prefix $MsysSubsystem +if ($LASTEXITCODE -ne 0) { throw 'Native OpenConnect packet-pipe tests failed.' } diff --git a/scripts/test-openconnect-windows.sh b/scripts/test-openconnect-windows.sh new file mode 100644 index 0000000..4827ef2 --- /dev/null +++ b/scripts/test-openconnect-windows.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Run the native packet-pipe regression against the bundled Windows DLL. +set -euo pipefail +subsystem=$3 +export PATH="/$subsystem/bin:/usr/bin:$PATH" +repo=$(cygpath -u "$1") +prefix=$(cygpath -u "$2") +build_dir="$repo/target/openconnect-windows" +source_dir="$repo/crates/openconnect/deps/openconnect" +export PATH="$prefix/bin:$PATH" +compiler=gcc +if [[ $subsystem == clangarm64 ]]; then compiler=clang; fi +"$compiler" -Wall -Wextra -I"$build_dir" -I"$source_dir" -I"$source_dir/json" \ + $(pkg-config --cflags gnutls libxml-2.0) \ + "$repo/crates/openconnect/tests/windows_packet_pipe.c" \ + -L"$prefix/lib" -lopenconnect -lws2_32 -o "$build_dir/test-windows-packet-pipe.exe" +"$build_dir/test-windows-packet-pipe.exe" diff --git a/scripts/test-private-desktop.sh b/scripts/test-private-desktop.sh index 20b7ce8..008c3bc 100644 --- a/scripts/test-private-desktop.sh +++ b/scripts/test-private-desktop.sh @@ -60,6 +60,6 @@ run_stage 'Frontend tests' 5m \ run_stage 'Frontend build' 10m \ docker exec --workdir "$workspace" "$container" pnpm --filter gpgui build run_stage 'Compile Rust tests' 30m \ - docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --no-run + docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --features gpapi/openssl-tests --no-run run_stage 'Rust tests' 10m \ - docker exec --workdir "$workspace" "$container" cargo test --workspace --locked + docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --features gpapi/openssl-tests diff --git a/scripts/test-windows-installer.ps1 b/scripts/test-windows-installer.ps1 index 9ec56e1..4ad6d6a 100644 --- a/scripts/test-windows-installer.ps1 +++ b/scripts/test-windows-installer.ps1 @@ -20,14 +20,34 @@ if ($process.ExitCode -ne 0) { } $info = Get-Content (Join-Path $destination 'build-info.json') -Raw | ConvertFrom-Json if ($info.architecture -ne $Architecture -or [string]$info.build_version -ne $Build) { throw 'The installed package identity does not match.' } +if ($env:WINDOWS_SIGNING_PUBLISHER) { + $signed = @($Installer) + foreach ($name in @('gpgui.exe', 'gpauth.exe', 'gpservice.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'uninstall.exe')) { + $signed += Join-Path $destination $name + } + & (Join-Path $PSScriptRoot 'test-windows-signature.ps1') -Files $signed -Publisher $env:WINDOWS_SIGNING_PUBLISHER +} $service = Get-CimInstance Win32_Service -Filter "Name='GPConnect'" if ($service.State -ne 'Running' -or $service.StartMode -ne 'Auto' -or $service.StartName -ne 'LocalSystem') { throw 'The service did not start automatically as LocalSystem.' } +$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk' +$shell = New-Object -ComObject Shell.Application +$link = $shell.Namespace((Split-Path $shortcut)).ParseName((Split-Path $shortcut -Leaf)) +if (!$link -or $link.ExtendedProperty('System.AppUserModel.ID') -ne 'com.yuezk.gpgui') { + throw 'The Start menu shortcut does not register the notification application identity.' +} foreach ($name in @('gpgui.exe', 'gpauth.exe')) { $process = Start-Process (Join-Path $destination $name) -ArgumentList '--version' -PassThru -Wait if ($process.ExitCode -ne 0) { throw "The installed $name cannot start." } } +$helper = Join-Path $destination 'gp-posture.exe' +$output = Join-Path $env:TEMP 'gp-posture-install-test.json' +$process = Start-Process $helper -PassThru -Wait -RedirectStandardOutput $output +if ($process.ExitCode -ne 0) { throw 'The installed posture helper failed.' } +$report = Get-Content $output -Raw | ConvertFrom-Json +if ($null -eq $report.anti_malware -or $null -eq $report.firewall) { throw 'Invalid posture helper output.' } +Remove-Item $output $state = Join-Path $env:LOCALAPPDATA 'GP Connect\config\protected-state' New-Item -ItemType Directory -Force $state | Out-Null $marker = Join-Path $state 'ci-install-retention' @@ -37,7 +57,6 @@ if ($process.ExitCode -ne 0) { throw 'The uninstaller failed.' } if ((Get-Service GPConnect -ErrorAction SilentlyContinue) -or (Test-Path $destination) -or (Test-Path ($destination + '.previous'))) { throw 'The uninstaller left service registration or runtime files.' } -$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk' if ((Test-Path $shortcut) -or (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect')) { throw 'The uninstaller left its shortcut or registration.' } diff --git a/scripts/test-windows-signature.ps1 b/scripts/test-windows-signature.ps1 new file mode 100644 index 0000000..d4affe7 --- /dev/null +++ b/scripts/test-windows-signature.ps1 @@ -0,0 +1,14 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][string[]]$Files, + [Parameter(Mandatory=$true)][string]$Publisher +) +$ErrorActionPreference = 'Stop' +foreach ($file in $Files) { + $signature = Get-AuthenticodeSignature -LiteralPath $file + if ($signature.Status -ne 'Valid') { throw "Invalid Authenticode signature: $file ($($signature.Status))" } + $name = $signature.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false) + if ($name -ne $Publisher) { throw "Unexpected signing publisher for ${file}: $name" } + if (!$signature.TimeStamperCertificate) { throw "Missing signature timestamp: $file" } + Write-Host "Verified $file (publisher: $name; timestamped)" +} diff --git a/scripts/tests/test_windows_update_feed.py b/scripts/tests/test_windows_update_feed.py index 6ac8f3b..c05161c 100644 --- a/scripts/tests/test_windows_update_feed.py +++ b/scripts/tests/test_windows_update_feed.py @@ -64,6 +64,7 @@ class WindowsFeedTests(unittest.TestCase): self.assertEqual(int(enclosure.get("length")), payload.installer.stat().st_size) self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}edSignature"), payload.signature_file.read_text()) self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}os"), f"windows-{payload.architecture}") + self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}installerArguments"), "/UPDATE") self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.4.0") minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.19041" self.assertEqual(item.findtext(f"{{{feed.SPARKLE}}}minimumSystemVersion"), minimum) diff --git a/scripts/tests/windows-webview-resize.ps1 b/scripts/tests/windows-webview-resize.ps1 new file mode 100644 index 0000000..333d550 --- /dev/null +++ b/scripts/tests/windows-webview-resize.ps1 @@ -0,0 +1,91 @@ +# Run in an unlocked Windows desktop; drives only its own isolated fixture. +param([Parameter(Mandatory)][string]$Binary) +$ErrorActionPreference='Stop' +Add-Type -AssemblyName UIAutomationClient +Add-Type -AssemblyName UIAutomationTypes +Add-Type -AssemblyName System.Drawing +Add-Type @' +using System; +using System.Runtime.InteropServices; +public class GPAuthLiveResize { + [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X,Y; } + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left,Top,Right,Bottom; } + [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr value); + [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h,uint flags); + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h,out RECT r); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] public static extern bool SetCursorPos(int x,int y); + [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p); + [DllImport("user32.dll")] public static extern void mouse_event(uint flags,uint x,uint y,uint data,UIntPtr extra); + [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p); +} +'@ +[GPAuthLiveResize]::SetThreadDpiAwarenessContext([IntPtr](-4)) | Out-Null +$work=Join-Path $env:TEMP ('gp-resize-test-'+[Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory $work | Out-Null +$previous=$env:WEBVIEW2_USER_DATA_FOLDER +$env:WEBVIEW2_USER_DATA_FOLDER=Join-Path $work 'profile' +$old=New-Object GPAuthLiveResize+POINT +[GPAuthLiveResize]::GetCursorPos([ref]$old) | Out-Null +$p=$null +try { + $p=Start-Process $Binary -ArgumentList @('https://preview.invalid','--saml-request','"

Resize fixture

"','--window-title','"GP Auth Resize Test"') -PassThru -RedirectStandardOutput "$work\result.json" -RedirectStandardError "$work\stderr.log" + $deadline=[DateTime]::UtcNow.AddSeconds(12) + $condition=New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty,[int]$p.Id) + $root=$null + do { + $roots=[Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children,$condition) + $root=@($roots | Where-Object {$_.Current.Name -eq 'GP Auth Resize Test' -and !$_.Current.IsOffscreen})[0] + if ($root) {break} + Start-Sleep -Milliseconds 100 + } while([DateTime]::UtcNow -lt $deadline) + if (!$root) {throw 'Resize fixture did not open'} + $hwnd=[GPAuthLiveResize]::GetAncestor([IntPtr]$root.Current.NativeWindowHandle,2) + [GPAuthLiveResize]::SetForegroundWindow($hwnd) | Out-Null + Start-Sleep -Milliseconds 300 + $name=New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty,'Edit') + $address=$root.FindFirst([Windows.Automation.TreeScope]::Descendants,$name) + $bounds=$address.Current.BoundingRectangle + $sample=New-Object GPAuthLiveResize+POINT + $sample.X=[int]($bounds.Left+300);$sample.Y=[int]($bounds.Top+$bounds.Height/2) + $pixel=New-Object Drawing.Bitmap(1,1) + $graphics=[Drawing.Graphics]::FromImage($pixel) + function Pixel { + $graphics.CopyFromScreen($sample.X,$sample.Y,0,0,$pixel.Size) + $pixel.GetPixel(0,0).ToArgb() + } + $baseline=Pixel + $frame=New-Object GPAuthLiveResize+RECT + [GPAuthLiveResize]::GetWindowRect($hwnd,[ref]$frame) | Out-Null + $startX=$frame.Right-2;$startY=[int](($frame.Top+$frame.Bottom)/2) + $edge=New-Object GPAuthLiveResize+POINT + $edge.X=$startX;$edge.Y=$startY + if ([GPAuthLiveResize]::GetAncestor([GPAuthLiveResize]::WindowFromPoint($edge),2) -ne $hwnd) {throw 'Resize edge is covered'} + [GPAuthLiveResize]::SetCursorPos($startX,$startY) | Out-Null + [GPAuthLiveResize]::mouse_event(2,0,0,0,[UIntPtr]::Zero) + $bad=0;$total=0 + try { + foreach($direction in @(1,-1,1,-1,1,-1)) { + for($i=1;$i -le 40;$i++) { + $offset=6*$i + if ($direction -lt 0) {$offset=6*(40-$i)} + [GPAuthLiveResize]::SetCursorPos($startX+$offset,$startY) | Out-Null + Start-Sleep -Milliseconds 8 + $value=Pixel + $total++ + if ($value -ne $baseline) {$bad++} + } + } + } finally {[GPAuthLiveResize]::mouse_event(4,0,0,0,[UIntPtr]::Zero)} + "Address samples while dragging: $bad hidden of $total; baseline $baseline" + if ($bad -gt 0) {throw 'Address bar disappears during live resizing'} + 'PASS: address bar remains visible throughout live resize' +} finally { + [GPAuthLiveResize]::mouse_event(4,0,0,0,[UIntPtr]::Zero) + [GPAuthLiveResize]::SetCursorPos($old.X,$old.Y) | Out-Null + if ($graphics) {$graphics.Dispose();$pixel.Dispose()} + if ($p -and !$p.HasExited) {Stop-Process -Id $p.Id} + $env:WEBVIEW2_USER_DATA_FOLDER=$previous + Start-Sleep -Milliseconds 500 + Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/scripts/tests/windows-webview-server.py b/scripts/tests/windows-webview-server.py new file mode 100644 index 0000000..ab11284 --- /dev/null +++ b/scripts/tests/windows-webview-server.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Loopback-only SAML/WebView2 fixture. All returned credentials are synthetic.""" +import argparse +import base64 +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import ssl +import threading + +BODY = '1webview-fixturesynthetic-webview-cookie' + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_POST(self): + self.rfile.read(int(self.headers.get('Content-Length', '0'))) + request = base64.b64encode(f'http://127.0.0.1:{args.http_port}/body'.encode()).decode() + self.respond(f'SuccessPOST{request}no') + + def respond(self, body, headers=(), status=200): + data = body.encode() + self.send_response(status) + self.send_header('Content-Type', 'text/html; charset=utf-8') + self.send_header('Content-Length', str(len(data))) + for name, value in headers: + self.send_header(name, value) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + path = self.path.split('?')[0] + if path == '/redirect': + self.respond('', [('Location', '/body')], 302) + elif path == '/headers': + self.respond('Header response', [('saml-auth-status', '1'), ('saml-username', 'webview-fixture'), ('prelogin-cookie', 'synthetic-header-cookie')]) + elif path == '/callback': + self.respond('') + elif path == '/cookie-set': + self.respond(BODY, [('Set-Cookie', 'webview_fixture=present; Max-Age=3600; Path=/; HttpOnly')]) + elif path in ['/cookie-present', '/cookie-clean']: + present = 'webview_fixture=present' in self.headers.get('Cookie', '') + success = present if path == '/cookie-present' else not present + self.respond(BODY if success else '0') + elif path == '/user-agent': + agent = self.headers.get('User-Agent', '') + self.respond(BODY if agent.startswith('PAN GlobalProtect/') and 'Mozilla/' in agent else '0') + elif path == '/temporary': + self.respond('Temporarily Unavailable') + elif path == '/signin': + self.respond('Fixture sign-in

Sign in

Complete fixture sign-in') + elif path == '/rejected': + self.respond('0') + elif path == '/cross-host': + self.respond('', [('Location', f'https://127.0.0.1:{args.https_port}/body')], 302) + elif path == '/body': + self.respond(BODY) + else: + self.send_error(404) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--http-port', type=int, default=18769) + parser.add_argument('--https-port', type=int, default=18770) + parser.add_argument('--cert', required=True) + parser.add_argument('--key', required=True) + args = parser.parse_args() + http = ThreadingHTTPServer(('127.0.0.1', args.http_port), Handler) + https = ThreadingHTTPServer(('127.0.0.1', args.https_port), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(args.cert, args.key) + https.socket = context.wrap_socket(https.socket, server_side=True) + threading.Thread(target=https.serve_forever, daemon=True).start() + print('Webview fixture ready', flush=True) + http.serve_forever() diff --git a/scripts/tests/windows-webview.ps1 b/scripts/tests/windows-webview.ps1 new file mode 100644 index 0000000..02014f4 --- /dev/null +++ b/scripts/tests/windows-webview.ps1 @@ -0,0 +1,193 @@ +# Run in an unlocked Windows desktop. Start windows-webview-server.py first. +# Use a GUI-subsystem binary; ordinary debug builds intentionally open a console. +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$Binary, + [string]$FixtureUrl = 'http://127.0.0.1:18769', + [string]$TlsUrl = 'https://localhost:18770' +) +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName UIAutomationClient +Add-Type -AssemblyName UIAutomationTypes +Add-Type @' +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +public class GPWebviewFixture { + [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } + [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p); + [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int height, uint flags); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + delegate bool WindowCallback(IntPtr h, IntPtr l); + [DllImport("user32.dll")] static extern bool EnumWindows(WindowCallback callback, IntPtr l); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, StringBuilder name, int length); + public static long[] ConsoleWindows() { + var windows = new List(); + EnumWindows((h, l) => { + var name = new StringBuilder(256); + GetClassName(h, name, name.Capacity); + if (IsWindowVisible(h) && (name.ToString() == "ConsoleWindowClass" || name.ToString() == "CASCADIA_HOSTING_WINDOW_CLASS")) windows.Add(h.ToInt64()); + return true; + }, IntPtr.Zero); + return windows.ToArray(); + } +} +'@ +$work = Join-Path $env:TEMP ('gp-webview-test-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory $work | Out-Null +$previousProfile = $env:WEBVIEW2_USER_DATA_FOLDER +# Microsoft's override isolates cookie tests from the user's real sign-in profile. +$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $work 'profile' +$script:current = $null +$script:index = 0 +function Start-Auth([string]$Request, [string[]]$Extra = @()) { + $script:index++ + $script:stdout = Join-Path $work "$script:index.json" + $script:stderr = Join-Path $work "$script:index.log" + $arguments = @($FixtureUrl, '--saml-request', ('"' + $Request + '"'), '--window-title', '"GP Auth Fixture"', '--os', 'Windows') + $Extra + $consoles = @([GPWebviewFixture]::ConsoleWindows()) + $script:current = Start-Process -FilePath $Binary -ArgumentList $arguments -PassThru -RedirectStandardOutput $script:stdout -RedirectStandardError $script:stderr + $null = $script:current.Handle + # Watch startup: device-information commands finish before the sign-in window appears. + $deadline = [DateTime]::UtcNow.AddSeconds(15) + do { + foreach ($console in [GPWebviewFixture]::ConsoleWindows()) { + if ($console -notin $consoles) { throw "Authentication opened a console in case $script:index" } + } + if ($script:current.HasExited -or $script:current.MainWindowHandle -ne [IntPtr]::Zero) { break } + Start-Sleep -Milliseconds 20 + $script:current.Refresh() + } while ([DateTime]::UtcNow -lt $deadline) +} +function Finish-Auth([bool]$Success) { + if (!$script:current.WaitForExit(20000)) { throw "Authentication timed out in case $script:index" } + if ($script:current.ExitCode -ne 0) { throw "Authenticator exited with $($script:current.ExitCode): $(Get-Content $script:stderr -Tail 8 | Out-String)" } + $result = Get-Content $script:stdout -Raw | ConvertFrom-Json + if ($Success) { + if ($result.success.username -ne 'webview-fixture') { throw "Expected successful fixture authentication in case $script:index" } + } elseif ($result -ne 'cancelled') { throw "Expected cancellation in case $script:index" } + $script:current = $null +} +function Find-Control([string]$Name) { + $processCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$script:current.Id) + $windows = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $processCondition) + $condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, $Name) + foreach ($window in $windows) { + $node = $window.FindFirst([Windows.Automation.TreeScope]::Descendants, $condition) + if ($node) { return $node } + } +} +function Wait-Control([string]$Name) { + $deadline = [DateTime]::UtcNow.AddSeconds(15) + do { + $node = Find-Control $Name + if ($node -and !$node.Current.IsOffscreen) { return $node } + Start-Sleep -Milliseconds 100 + } while ([DateTime]::UtcNow -lt $deadline -and !$script:current.HasExited) + throw "Missing '$Name' in authentication case $script:index" +} +function Invoke-Control([string]$Name) { + (Wait-Control $Name).GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke() +} +function Close-Auth { + $processCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$script:current.Id) + $deadline = [DateTime]::UtcNow.AddSeconds(15) + do { + $windows = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $processCondition) + foreach ($window in $windows) { + if ($window.Current.Name -eq 'GP Auth Fixture' -and !$window.Current.IsOffscreen) { + [GPWebviewFixture]::PostMessage([IntPtr]$window.Current.NativeWindowHandle, 0x10, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null + return + } + } + Start-Sleep -Milliseconds 100 + } while ([DateTime]::UtcNow -lt $deadline) + throw 'Sign-in window did not become visible' +} +try { + foreach ($path in @('/body', '/headers', '/redirect', '/callback', '/user-agent')) { + Start-Auth ($FixtureUrl + $path) + Finish-Auth $true + "PASS: $path" + } + Start-Auth '1webview-fixturesynthetic-html-cookie' + Finish-Auth $true + 'PASS: supplied HTML' + Start-Auth ($FixtureUrl + '/cookie-set') + Finish-Auth $true + Start-Auth ($FixtureUrl + '/cookie-present') + Finish-Auth $true + Start-Auth ($FixtureUrl + '/cookie-clean') @('--clean') + Finish-Auth $true + 'PASS: cookie persistence and clean sign-in' + Start-Auth ($FixtureUrl + '/signin') + $link = Wait-Control 'Complete fixture sign-in' + $condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$script:current.Id) + $roots = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $condition) + $root = @($roots | Where-Object { $_.Current.Name -eq 'GP Auth Fixture' })[0] + if (!$root) { throw 'Missing sign-in window' } + $editCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty, 'Edit') + $address = $root.FindFirst([Windows.Automation.TreeScope]::Descendants, $editCondition) + if (!$address) { throw 'Missing native address bar' } + $bounds = $address.Current.BoundingRectangle + if ($link.Current.BoundingRectangle.Top -lt $bounds.Bottom) { throw 'Webview overlaps the address bar' } + [GPWebviewFixture]::SetForegroundWindow([IntPtr]$root.Current.NativeWindowHandle) | Out-Null + Start-Sleep -Milliseconds 200 + $point = New-Object GPWebviewFixture+POINT + $point.X = [int]($bounds.Left + $bounds.Width / 2); $point.Y = [int]($bounds.Top + $bounds.Height / 2) + if ([GPWebviewFixture]::WindowFromPoint($point) -ne [IntPtr]$address.Current.NativeWindowHandle) { throw 'Native address bar is covered' } + $frame = $root.Current.BoundingRectangle + [GPWebviewFixture]::SetWindowPos([IntPtr]$root.Current.NativeWindowHandle, [IntPtr]::Zero, 0, 0, [int]$frame.Width - 40, [int]$frame.Height - 40, 6) | Out-Null + Start-Sleep -Milliseconds 300 + $bounds = $address.Current.BoundingRectangle + $point.X = [int]($bounds.Left + $bounds.Width / 2); $point.Y = [int]($bounds.Top + $bounds.Height / 2) + if ($link.Current.BoundingRectangle.Top -lt $bounds.Bottom -or [GPWebviewFixture]::WindowFromPoint($point) -ne [IntPtr]$address.Current.NativeWindowHandle) { throw 'Resizing broke the native address bar layout' } + $link.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke() + Finish-Auth $true + 'PASS: interactive embedded sign-in' + Start-Auth ($FixtureUrl + '/signin') + Close-Auth + Finish-Auth $false + 'PASS: window cancellation' + Start-Auth ($FixtureUrl + '/rejected') + Invoke-Control 'Cancel' + Finish-Auth $false + 'PASS: rejected sign-in recovery' + Start-Auth ($FixtureUrl + '/missing') + $null = Wait-Control ('Couldn' + [char]0x2019 + 't load sign-in.') + Invoke-Control 'Try Again' + Finish-Auth $true + 'PASS: initial page-load failure and fresh-prelogin retry' + Start-Auth ($FixtureUrl + '/temporary') + Finish-Auth $true + 'PASS: automatic fresh-prelogin recovery' + Start-Auth ($TlsUrl + '/body') @('--ignore-tls-errors') + Finish-Auth $true + 'PASS: explicit ignore-TLS option' + Start-Auth ($TlsUrl + '/body') + Invoke-Control ('Continue Anyway' + [char]0x2026) + Invoke-Control 'Yes' + Finish-Auth $true + 'PASS: certificate warning and confirmed exception' + Start-Auth ($TlsUrl + '/body') + Invoke-Control 'Cancel' + Finish-Auth $false + 'PASS: certificate exception does not survive the sign-in window' + Start-Auth ($TlsUrl + '/cross-host') + Invoke-Control ('Continue Anyway' + [char]0x2026) + Invoke-Control 'Yes' + Invoke-Control 'Cancel' + Finish-Auth $false + 'PASS: certificate exception is scoped to the approved host' +} finally { + if ($script:current -and !$script:current.HasExited) { Stop-Process -Id $script:current.Id; $script:current.WaitForExit() } + $env:WEBVIEW2_USER_DATA_FOLDER = $previousProfile + # WebView2's browser process releases its profile shortly after the window closes. + for ($attempt = 0; $attempt -lt 10; $attempt++) { + try { Remove-Item $work -Recurse -Force; break } catch { Start-Sleep -Milliseconds 500 } + } + if (Test-Path $work) { Write-Warning "Fixture profile remains at $work" } +} diff --git a/scripts/uninstall-windows.ps1 b/scripts/uninstall-windows.ps1 new file mode 100644 index 0000000..c8339c4 --- /dev/null +++ b/scripts/uninstall-windows.ps1 @@ -0,0 +1,5 @@ +#Requires -RunAsAdministrator +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +& (Join-Path $PSScriptRoot 'installer\machine-install.ps1') -Action Uninstall diff --git a/scripts/windows-update-feed.py b/scripts/windows-update-feed.py index 0b9d339..d6b1e06 100644 --- a/scripts/windows-update-feed.py +++ b/scripts/windows-update-feed.py @@ -102,6 +102,7 @@ def generate(args: argparse.Namespace) -> None: "url": payload.installer_url, "length": str(length), "type": "application/octet-stream", f"{{{SPARKLE}}}version": display_version, f"{{{SPARKLE}}}shortVersionString": display_version, + f"{{{SPARKLE}}}installerArguments": "/UPDATE", f"{{{SPARKLE}}}os": f"windows-{payload.architecture}", f"{{{SPARKLE}}}edSignature": signature, }) ET.indent(rss) From 5f4b2b602aeff95361731d35eea2181e122801dd Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Thu, 19 Nov 2026 03:15:45 +0800 Subject: [PATCH 2/2] release: validate Nix packages for v3.5.0 --- flake.lock | 6 +++--- flake.nix | 14 ++++++++------ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/flake.lock b/flake.lock index 486976a..e2d9c62 100644 --- a/flake.lock +++ b/flake.lock @@ -63,11 +63,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1794408178, - "narHash": "sha256-OUDRQTMmN/6cQ/ebDsazUmLj84RxSLaHznKv5As9E1k=", + "lastModified": 1794840529, + "narHash": "sha256-ySrWnmZB5UsZTYGHHnBjllT05O5iFjElCRS+mabtfP0=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "9397dcb09c9598a33509fbc0cce699bd4e6c84d5", + "rev": "e21fec321d73511849707a7585e4ea155ee4bf40", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 6ab6057..27010a4 100644 --- a/flake.nix +++ b/flake.nix @@ -29,8 +29,8 @@ cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml); pname = "globalprotect-openconnect"; version = cargoToml.workspace.package.version; - releaseTag = "v3.4.0"; - releaseVersion = "3.4.0"; + releaseTag = "v3.5.0"; + releaseVersion = "3.5.0"; toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; @@ -55,8 +55,8 @@ cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name; gpguiHashes = { - x86_64 = "sha256-2qZQICnK5fa18suhnqeYnDI1z+SGqXJa1ZXI2NhfQP0="; - aarch64 = "sha256-iOM3+Qte/6C4Gs/e9jVvx5DtBFq7DG2PNDCsGwPMeY0="; + x86_64 = "sha256-nA6+URV5FafIynXFQL7YmimhVU0sYEuaYqQ4I9YZ5eY="; + aarch64 = "sha256-gPuz6UV7Xir0WKZac8ZsEw8mjN92wRdidbHu5FjS1cw="; }; gpguiArchive = pkgs.fetchurl { @@ -70,8 +70,8 @@ }; binaryHashes = { - x86_64 = "sha256-hBnfMAS3qEby9Dyc3ysH8tdGQwarXqo9xtY1gbN8gJI="; - aarch64 = "sha256-lW1yQQD1G633tdBGBhVEAEQvMtnntK3mMU9M69x9ID0="; + x86_64 = "sha256-l8NrsyiLfYTcALybjOPVnJMLL8Qe2q1jGrwnDu4Grg8="; + aarch64 = "sha256-+vSsvbqXhoEnxz8dxm/Qq0P5Ve/0HDLs2WnLsTszsgw="; }; binaryArchive = pkgs.fetchurl { @@ -86,6 +86,7 @@ linuxRuntimeDependencies = with pkgs; [ glib-networking + libayatana-appindicator xdg-utils ]; @@ -173,6 +174,7 @@ webkitgtk_4_1 glib-networking libsecret + libayatana-appindicator ]; installNixosPolkitRule = ''