release: prepare GP Connect 3.5.0 with Windows support

This commit is contained in:
Kevin Yue committed 2026-11-19 01:40:22 +08:00
1 parent 6ffb1e8709
commit 43c20d0976
172 files changed
+9629 -1171

No files matched your search

+17 -1
View File
@@ -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" }
+4 -65
View File
@@ -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<String, CallbackReadError> {
let mut magic = [0_u8; 4];
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
if &magic != PROTOCOL_MAGIC {
return Err(CallbackReadError::Invalid);
}
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
if version != PROTOCOL_VERSION {
return Err(CallbackReadError::UnsupportedVersion);
}
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
if length == 0 || length > MAX_CALLBACK_SIZE {
return Err(CallbackReadError::Invalid);
}
let mut payload = vec![0; length];
stream
.read_exact(&mut payload)
.await
.map_err(|_| CallbackReadError::Io)?;
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
Ok(callback)
}
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u8(status).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use tempfile::tempdir;
use super::*;
+73
View File
@@ -0,0 +1,73 @@
//! Bounded authentication callback wire format, shared by local transports.
use anyhow::bail;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
pub(super) const CALLBACK_SCHEME: &str = "globalprotectcallback";
pub(super) const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
pub(super) const PROTOCOL_VERSION: u8 = 1;
pub(super) const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
pub(super) const IO_TIMEOUT: Duration = Duration::from_secs(5);
// Acceptance acknowledges delivery, including an authentication failure.
pub(super) const STATUS_ACCEPTED: u8 = 0;
pub(super) const STATUS_INVALID_CALLBACK: u8 = 1;
pub(super) const STATUS_UNSUPPORTED_VERSION: u8 = 2;
pub fn validate_auth_callback(callback: &str) -> anyhow::Result<()> {
if callback.len() > MAX_CALLBACK_SIZE {
bail!("Authentication callback exceeds the maximum supported size");
}
let Some((scheme, data)) = callback.split_once(':') else {
bail!("Authentication callback URL is invalid");
};
if scheme != CALLBACK_SCHEME || data.is_empty() {
bail!("Authentication callback URL is invalid");
}
Ok(())
}
pub(super) enum CallbackReadError {
UnsupportedVersion,
Invalid,
Io,
}
pub(super) async fn read_callback(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
) -> Result<String, CallbackReadError> {
let mut magic = [0_u8; 4];
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
if &magic != PROTOCOL_MAGIC {
return Err(CallbackReadError::Invalid);
}
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
if version != PROTOCOL_VERSION {
return Err(CallbackReadError::UnsupportedVersion);
}
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
if length == 0 || length > MAX_CALLBACK_SIZE {
return Err(CallbackReadError::Invalid);
}
let mut payload = vec![0; length];
stream
.read_exact(&mut payload)
.await
.map_err(|_| CallbackReadError::Io)?;
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
validate_auth_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
Ok(callback)
}
pub(super) async fn write_response(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
status: u8,
) -> anyhow::Result<()> {
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u8(status).await?;
Ok(())
}
+170
View File
@@ -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<Self> {
Ok(Self {
listener: gpapi::windows::create_user_pipe(&pipe_name()?, true)
.context("Another browser authentication is already waiting")?,
})
}
pub async fn receive(mut self) -> anyhow::Result<SamlAuthData> {
loop {
self.listener.connect().await?;
let mut stream = &mut self.listener;
let callback = timeout(IO_TIMEOUT, read_callback(&mut stream)).await;
let result = match callback {
Ok(Ok(callback)) => match SamlAuthData::from_gpcallback(&callback) {
Ok(data) => {
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
Some(Ok(data))
}
Err(error @ AuthDataParseError::AuthenticationFailed(_)) => {
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
Some(Err(error.into()))
}
Err(_) => {
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
None
}
},
Ok(Err(CallbackReadError::UnsupportedVersion)) => {
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
None
}
_ => None,
};
// DisconnectNamedPipe discards unread response bytes. Wait for the client
// to confirm it consumed the response before disconnecting this instance.
let _ = timeout(IO_TIMEOUT, stream.read_u8()).await;
self.listener.disconnect()?;
if let Some(result) = result {
if let Err(error) = delegate_foreground_to_parent() {
log::debug!("Could not delegate authentication foreground permission to the parent: {error}");
}
return result;
}
}
}
}
fn pipe_name() -> anyhow::Result<String> {
Ok(format!(
r"\\.\pipe\GPConnect.Auth.{}",
gpapi::windows::current_user_sid()?
))
}
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
validate_auth_callback(callback)?;
timeout(IO_TIMEOUT, async {
let mut stream = ClientOptions::new()
.open(pipe_name()?)
.context("No external-browser authentication is waiting for a callback")?;
stream.write_all(PROTOCOL_MAGIC).await?;
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u32(callback.len() as u32).await?;
stream.write_all(callback.as_bytes()).await?;
let version = stream.read_u8().await?;
let status = stream.read_u8().await?;
// The receiver waits for our acknowledgement before returning to its caller.
if version == PROTOCOL_VERSION && status == STATUS_ACCEPTED {
if let Err(error) = delegate_foreground_to_receiver(&stream) {
log::debug!("Could not delegate browser foreground permission to the authenticator: {error}");
}
}
stream.write_u8(status).await?;
anyhow::ensure!(
version == PROTOCOL_VERSION,
"Authentication callback protocol version mismatch"
);
match status {
STATUS_ACCEPTED => Ok(()),
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
_ => bail!("Authentication callback protocol is unsupported"),
}
})
.await
.context("Timed out forwarding the authentication callback")?
}
fn delegate_foreground_to_receiver(stream: &NamedPipeClient) -> io::Result<()> {
let mut process_id = 0;
unsafe {
if GetNamedPipeServerProcessId(stream.as_raw_handle(), &mut process_id) == 0 {
return Err(io::Error::last_os_error());
}
}
allow_foreground(process_id)
}
fn delegate_foreground_to_parent() -> anyhow::Result<()> {
let Some(process_id) = std::env::var_os(gpapi::process::auth_launcher::AUTH_PARENT_PROCESS_ID_ENV) else {
return Ok(());
};
let process_id = process_id.to_string_lossy().parse::<u32>()?;
allow_foreground(process_id)?;
Ok(())
}
fn allow_foreground(process_id: u32) -> io::Result<()> {
if unsafe { AllowSetForegroundWindow(process_id) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
use winreg::{RegKey, enums::HKEY_CURRENT_USER};
let executable = common::binary_paths::gpauth();
anyhow::ensure!(executable.is_file(), "The authentication helper is missing");
let root = RegKey::predef(HKEY_CURRENT_USER);
let (scheme, _) = root.create_subkey(r"Software\Classes\globalprotectcallback")?;
scheme.set_value("", &"URL:GlobalProtect authentication callback")?;
scheme.set_value("URL Protocol", &"")?;
let (application, _) = scheme.create_subkey("Application")?;
application.set_value("ApplicationName", &"GP Connect Login")?;
let (command, _) = scheme.create_subkey(r"shell\open\command")?;
// URL association activation requires a shell path, not Rust's verbatim
// canonical path (\\?\C:\...), even though CreateProcess accepts both.
let executable = dunce::simplified(&executable);
command.set_value("", &format!("\"{}\" auth-callback \"%1\"", executable.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn forwards_browser_callback_over_private_windows_pipe() {
let receiver = AuthCallbackReceiver::bind().unwrap();
// The first-instance flag preserves one pending browser authentication per user.
assert!(AuthCallbackReceiver::bind().is_err());
let sender = tokio::spawn(async {
forward_auth_callback("globalprotectcallback:cas-as=1&[email protected]&token=test-token").await
});
let data = timeout(std::time::Duration::from_secs(5), receiver.receive())
.await
.unwrap()
.unwrap();
sender.await.unwrap().unwrap();
assert_eq!(data.username(), "[email protected]");
assert_eq!(data.token(), Some("test-token"));
}
}
+1
View File
@@ -8,6 +8,7 @@ use gpapi::{
mod browser;
#[cfg(feature = "browser-auth")]
#[cfg_attr(windows, path = "callback/windows.rs")]
mod callback;
#[cfg(feature = "browser-auth")]
+6 -1
View File
@@ -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};
+2 -2
View File
@@ -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;
+2 -1
View File
@@ -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)
}
+4
View File
@@ -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.",
+44 -24
View File
@@ -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<tauri::Theme>) -> anyhow::Result<AuthWindow> {
let builder = AuthWindow::builder(app, "auth_window", WebviewUrl::default())
.title(title)
.theme(theme)
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let builder = builder.on_navigation(super::platform_impl::open_okta_verify);
Ok(
builder
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
.min_inner_size(400.0, 300.0)
.focused(true)
.visible(false)
.center()
.build()?,
)
}
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
pub trait PlatformWebviewExt {
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
pub(super) trait PlatformWebviewExt {
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> 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<String>;
}
@@ -125,19 +154,7 @@ impl<'a> WebviewAuthenticator<'a> {
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_messenger = Arc::new(AuthMessenger::new());
let auth_window_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<AuthMessenger>,
) -> anyhow::Result<SamlAuthData> {
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<AuthMessenger>,
) -> anyhow::Result<()> {
info!("Setting up auth window...");
if self.clean {
info!("Clearing all browsing data...");
#[cfg(windows)]
super::platform_impl::clear_browsing_data(auth_window).await?;
#[cfg(not(windows))]
auth_window.clear_all_browsing_data()?;
}
@@ -361,7 +381,7 @@ impl<'a> WebviewAuthenticator<'a> {
Ok(())
}
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
fn handle_not_found(&self, auth_window: &AuthWindow, auth_messenger: &Arc<AuthMessenger>) {
let visible = auth_window.is_visible().unwrap_or(false);
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<AuthMessenger>,
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;
+380
View File
@@ -0,0 +1,380 @@
//! WebView2 authentication. All COM objects and native controls stay on the UI thread.
use std::{
cell::{Cell, RefCell},
collections::HashMap,
rc::Rc,
sync::Arc,
};
use super::{
auth_messenger::{AuthDataLocation, AuthError, AuthEvent, AuthMessenger},
recovery::RecoveryStatus,
webview_auth::{GetHeader, PlatformWebviewExt},
};
use anyhow::{Context, bail};
use gpapi::auth::SamlAuthData;
use tauri::{
AppHandle, LogicalPosition, Webview, WebviewBuilder, WebviewUrl, Window, WindowBuilder, webview::PlatformWebview,
};
use webview2_com::{
ClearBrowsingDataCompletedHandler, CoTaskMemPWSTR, DOMContentLoadedEventHandler, ExecuteScriptCompletedHandler,
Microsoft::Web::WebView2::Win32::*, NavigationCompletedEventHandler, NavigationStartingEventHandler,
SourceChangedEventHandler, WebResourceResponseReceivedEventHandler,
};
use windows::core::{BOOL, HSTRING, Interface, PWSTR};
#[path = "windows/controls.rs"]
mod controls;
#[path = "windows/tls.rs"]
mod tls;
/// Windows hosts native chrome and a manually sized child webview in one window.
/// Host-owned child bounds keep the page surface below the native controls
/// throughout live resizing.
#[derive(Clone)]
pub(super) struct AuthWindow {
window: Window,
webview: Webview,
}
impl std::ops::Deref for AuthWindow {
type Target = Window;
fn deref(&self) -> &Window {
&self.window
}
}
impl AuthWindow {
pub(super) fn with_webview(&self, callback: impl FnOnce(PlatformWebview) + Send + 'static) -> tauri::Result<()> {
self.webview.with_webview(callback)
}
}
impl gpapi::utils::window::WindowExt for AuthWindow {
fn raise(&self) -> anyhow::Result<()> {
self.window.show()?;
self.window.set_focus()?;
self.webview.set_focus()?;
Ok(())
}
}
pub(super) fn create_auth_window(
app: &AppHandle,
title: &str,
theme: Option<tauri::Theme>,
) -> anyhow::Result<AuthWindow> {
let window = WindowBuilder::new(app, "auth_window")
.title(title)
.theme(theme)
.inner_size(900.0, 650.0 + super::address_bar::TOOLBAR_HEIGHT)
.min_inner_size(400.0, 300.0)
.focused(true)
.visible(false)
.center()
.build()?;
let webview = window.add_child(
WebviewBuilder::new("auth_webview", WebviewUrl::default())
.devtools(cfg!(any(debug_assertions, feature = "release-devtools"))),
LogicalPosition::new(0.0, 0.0),
window.inner_size()?,
)?;
Ok(AuthWindow { window, webview })
}
thread_local! {
static STATES: RefCell<HashMap<usize, Rc<State>>> = RefCell::default();
}
struct State {
core: ICoreWebView2,
controller: ICoreWebView2Controller,
messenger: Arc<AuthMessenger>,
controls: controls::Controls,
pending: Cell<Option<u64>>,
navigations: RefCell<HashMap<u64, u64>>,
document: RefCell<(String, u64)>,
tls: RefCell<tls::Policy>,
}
fn text(get: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
let mut value = PWSTR::null();
let result = get(&mut value);
let value = CoTaskMemPWSTR::from(value);
result?;
Ok(value.to_string())
}
fn state(webview: &PlatformWebview) -> anyhow::Result<Rc<State>> {
let core = unsafe { webview.controller().CoreWebView2()? };
STATES
.with_borrow(|states| states.get(&(core.as_raw() as usize)).cloned())
.context("Authentication controls are unavailable")
}
impl State {
fn read_html(&self, generation: u64) -> windows::core::Result<()> {
if generation != self.messenger.generation() {
return Ok(());
}
let messenger = Arc::clone(&self.messenger);
unsafe {
self.core.ExecuteScript(
&HSTRING::from("document.documentElement.outerHTML"),
&ExecuteScriptCompletedHandler::create(Box::new(move |result, json| {
result?;
if let Ok(html) = serde_json::from_str::<String>(&json) {
messenger.read_from_html(&html, generation);
}
Ok(())
})),
)
}
}
fn listen(self: &Rc<Self>) -> windows::core::Result<()> {
let mut token = 0;
let weak = Rc::downgrade(self);
let starting = NavigationStartingEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let mut id = 0;
args.NavigationId(&mut id)?;
let generation = *state
.navigations
.borrow_mut()
.entry(id)
.or_insert_with(|| state.pending.take().unwrap_or_else(|| state.messenger.generation()));
let uri = text(|p| args.Uri(p))?;
if uri.starts_with("globalprotectcallback:") {
args.SetCancel(true)?;
match SamlAuthData::from_gpcallback(&uri) {
Ok(data) => state
.messenger
.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
Err(error) => state
.messenger
.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(error.into()))),
}
} else if generation == state.messenger.generation() {
*state.document.borrow_mut() = (uri, generation);
state.messenger.cancel_raise_window();
}
}
Ok(())
}));
unsafe {
self.core.add_NavigationStarting(&starting, &mut token)?;
}
let weak = Rc::downgrade(self);
let loaded = DOMContentLoadedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
let mut id = 0;
unsafe {
args.NavigationId(&mut id)?;
}
let generation = state.navigations.borrow().get(&id).copied();
if let Some(generation) = generation {
state.read_html(generation)?;
}
Ok(())
}));
unsafe {
self
.core
.cast::<ICoreWebView2_2>()?
.add_DOMContentLoaded(&loaded, &mut token)?;
}
let weak = Rc::downgrade(self);
let completed = NavigationCompletedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let mut id = 0;
args.NavigationId(&mut id)?;
let Some(generation) = state.navigations.borrow_mut().remove(&id) else {
return Ok(());
};
let mut success = BOOL(0);
args.IsSuccess(&mut success)?;
if success.as_bool() {
state.read_html(generation)?;
state.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
} else {
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
args.WebErrorStatus(&mut error)?;
if error != COREWEBVIEW2_WEB_ERROR_STATUS_OPERATION_CANCELED {
state.messenger.send_auth_event(AuthEvent::Error(
generation,
AuthError::LoadFailed(anyhow::anyhow!("WebView2 navigation failed ({})", error.0)),
));
}
}
}
Ok(())
}));
unsafe {
self.core.add_NavigationCompleted(&completed, &mut token)?;
}
let weak = Rc::downgrade(self);
let source = SourceChangedEventHandler::create(Box::new(move |_, _| {
if let Some(state) = weak.upgrade() {
let uri = unsafe { text(|p| state.core.Source(p))? };
state.controls.set_address(&uri)?;
}
Ok(())
}));
unsafe {
self.core.add_SourceChanged(&source, &mut token)?;
}
let weak = Rc::downgrade(self);
let response = WebResourceResponseReceivedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let uri = text(|p| args.Request()?.Uri(p))?;
let (document, generation) = state.document.borrow().clone();
// Subresources must not supply authentication credentials for the page.
if uri == document && generation == state.messenger.generation() {
state
.messenger
.read_from_response(&Headers(args.Response()?.Headers()?), generation);
}
}
Ok(())
}));
unsafe {
self
.core
.cast::<ICoreWebView2_2>()?
.add_WebResourceResponseReceived(&response, &mut token)?;
}
tls::install(self)?;
Ok(())
}
}
struct Headers(ICoreWebView2HttpResponseHeaders);
impl GetHeader for Headers {
fn get_header(&self, key: &str) -> Option<String> {
unsafe { text(|p| self.0.GetHeader(&HSTRING::from(key), p)).ok() }
}
}
impl PlatformWebviewExt for PlatformWebview {
fn install_auth_controls(&self, window: &AuthWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
let controller = self.controller();
let core = unsafe { controller.CoreWebView2()? };
let key = core.as_raw() as usize;
let controls = controls::Controls::new(window, &controller, key)?;
let state = Rc::new(State {
core,
controller,
messenger,
controls,
pending: Cell::new(None),
navigations: RefCell::default(),
document: RefCell::new((String::new(), 0)),
tls: RefCell::default(),
});
STATES.with_borrow_mut(|states| states.insert(key, Rc::clone(&state)));
state.listen()?;
state.controls.layout(&state)?;
Ok(())
}
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
let state = state(self)?;
state.controls.update(&state, status)?;
Ok(())
}
fn stop_loading(&self) {
let _ = unsafe { self.controller().CoreWebView2().and_then(|wv| wv.Stop()) };
}
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
tls::confirm(state(self)?.as_ref())
}
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
state(self)?.tls.borrow_mut().ignore_errors = true;
Ok(())
}
fn user_agent(&self) -> anyhow::Result<String> {
unsafe {
Ok(text(|p| {
self
.controller()
.CoreWebView2()?
.Settings()?
.cast::<ICoreWebView2Settings2>()?
.UserAgent(p)
})?)
}
}
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
unsafe {
self
.controller()
.CoreWebView2()?
.Settings()?
.cast::<ICoreWebView2Settings2>()?
.SetUserAgent(&HSTRING::from(user_agent))?;
}
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
let state = state(self)?;
state.pending.set(Some(state.messenger.generation()));
unsafe {
state.core.Navigate(&HSTRING::from(url))?;
}
Ok(())
}
fn load_html(&self, html: &str) -> anyhow::Result<()> {
let state = state(self)?;
state.pending.set(Some(state.messenger.generation()));
unsafe {
state.core.NavigateToString(&HSTRING::from(html))?;
}
Ok(())
}
}
/// WebView2 clears profiles asynchronously; do not navigate until cookies are gone.
pub(super) async fn clear_browsing_data(window: &AuthWindow) -> anyhow::Result<()> {
let (tx, rx) = tokio::sync::oneshot::channel();
window.with_webview(move |wv| {
let tx = Rc::new(RefCell::new(Some(tx)));
let complete = Rc::clone(&tx);
let callback = ClearBrowsingDataCompletedHandler::create(Box::new(move |result| {
if let Some(tx) = complete.borrow_mut().take() {
let _ = tx.send(result);
}
Ok(())
}));
let result = (|| unsafe {
wv.controller()
.CoreWebView2()?
.cast::<ICoreWebView2_13>()?
.Profile()?
.cast::<ICoreWebView2Profile2>()?
.ClearBrowsingDataAll(&callback)
})();
if let Err(error) = result {
if let Some(tx) = tx.borrow_mut().take() {
let _ = tx.send(Err(error));
}
}
})?;
rx.await.context("Could not clear sign-in data")??;
Ok(())
}
+391
View File
@@ -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<RecoveryStatus>,
recovery_bounds: Cell<RECT>,
font: Cell<Option<(u32, HFONT)>>,
}
impl Controls {
pub(super) fn new(window: &AuthWindow, controller: &ICoreWebView2Controller, key: usize) -> anyhow::Result<Self> {
// The host owns both the toolbar and the child webview's remaining area.
let parent = HWND(window.hwnd()?.0);
let mut webview_host = HWND::default();
unsafe {
controller.ParentWindow(&mut webview_host)?;
}
let child = |class: PCWSTR, title: &str, style: WINDOW_STYLE, id: usize| -> windows::core::Result<HWND> {
unsafe {
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE::default(),
class,
&HSTRING::from(title),
WS_CHILD | style,
0,
0,
0,
0,
Some(parent),
Some(HMENU(id as *mut _)),
None,
None,
)?;
Ok(hwnd)
}
};
let controls = Self {
parent,
webview_host,
address: child(
w!("EDIT"),
super::super::address_bar::LOADING_ADDRESS,
WS_VISIBLE | WS_BORDER | WINDOW_STYLE(ES_READONLY as u32 | ES_MULTILINE as u32 | ES_AUTOHSCROLL as u32),
0,
)?,
message: child(w!("STATIC"), "", WINDOW_STYLE::default(), 0)?,
retry: child(w!("BUTTON"), "Try Again", WS_TABSTOP, RETRY)?,
proceed: child(w!("BUTTON"), "Continue Anyway…", WS_TABSTOP, PROCEED)?,
cancel: child(w!("BUTTON"), "Cancel", WS_TABSTOP, CANCEL)?,
status: Cell::new(RecoveryStatus::Hidden),
recovery_bounds: Cell::new(RECT::default()),
font: Cell::new(None),
};
unsafe {
anyhow::ensure!(
SetWindowSubclass(controls.address, Some(address_proc), ADDRESS_SUBCLASS, 0).as_bool(),
"Could not style the sign-in address"
);
anyhow::ensure!(
SetWindowSubclass(parent, Some(window_proc), SUBCLASS, key).as_bool(),
"Could not install sign-in controls"
);
}
Ok(controls)
}
pub(super) fn set_address(&self, uri: &str) -> windows::core::Result<()> {
unsafe {
SetWindowTextW(
self.address,
&HSTRING::from(super::super::address_bar::display_address(Some(uri))),
)
}
}
pub(super) fn update(&self, state: &State, status: RecoveryStatus) -> windows::core::Result<()> {
self.status.set(status);
let message = if status.detail().is_empty() {
status.message().to_owned()
} else {
format!("{}\r\n{}", status.message(), status.detail())
};
unsafe {
SetWindowTextW(self.message, &HSTRING::from(message))?;
for (hwnd, visible) in [
(self.message, status != RecoveryStatus::Hidden),
(self.retry, status.can_retry()),
(self.proceed, status.can_continue()),
(self.cancel, status.blocks_page()),
] {
let _ = ShowWindow(hwnd, if visible { SW_SHOW } else { SW_HIDE });
}
state.controller.SetIsVisible(!status.blocks_page())?;
}
self.layout(state)
}
pub(super) fn layout(&self, state: &State) -> windows::core::Result<()> {
unsafe {
let dpi = GetDpiForWindow(self.parent);
let scale = dpi as f64 / 96.0;
let px = |value: i32| (value as f64 * scale).round() as i32;
let mut bounds = RECT::default();
GetClientRect(self.parent, &mut bounds)?;
let width = bounds.right;
if self.font.get().is_none_or(|(current_dpi, _)| current_dpi != dpi) {
let mut metrics = NONCLIENTMETRICSW {
cbSize: std::mem::size_of::<NONCLIENTMETRICSW>() as u32,
..Default::default()
};
SystemParametersInfoForDpi(
SPI_GETNONCLIENTMETRICS.0,
metrics.cbSize,
Some(&mut metrics as *mut _ as *mut _),
0,
dpi,
)?;
metrics.lfMessageFont.lfHeight = -px(13);
let font = CreateFontIndirectW(&metrics.lfMessageFont);
if font.is_invalid() {
return Err(windows::core::Error::from_thread());
}
for control in [self.address, self.message, self.retry, self.proceed, self.cancel] {
SendMessageW(control, WM_SETFONT, Some(WPARAM(font.0 as usize)), Some(LPARAM(1)));
}
if let Some((_, old)) = self.font.replace(Some((dpi, font))) {
let _ = DeleteObject(old.into());
}
}
MoveWindow(
self.address,
px(8),
px(5),
(width - px(16)).max(0),
px(ADDRESS_HEIGHT),
true,
)?;
// A one-line formatting rectangle centers the native read-only edit text.
// ES_AUTOHSCROLL keeps long URLs on one line and lets users select/copy them.
let mut client = RECT::default();
GetClientRect(self.address, &mut client)?;
let dc = GetDC(Some(self.address));
let previous = SelectObject(dc, self.font.get().expect("font initialized").1.into());
let mut text_metrics = TEXTMETRICW::default();
let measured = GetTextMetricsW(dc, &mut text_metrics);
SelectObject(dc, previous);
ReleaseDC(Some(self.address), dc);
measured.ok()?;
let top = ((client.bottom - text_metrics.tmHeight) / 2).max(0);
let text = RECT {
left: px(6),
top,
right: client.right - px(6),
bottom: top + text_metrics.tmHeight,
};
SendMessageW(
self.address,
EM_SETRECT,
Some(WPARAM(0)),
Some(LPARAM(&text as *const _ as isize)),
);
let status = self.status.get();
let buttons = [
(self.cancel, status.blocks_page(), 70),
(self.proceed, status.can_continue(), 136),
(self.retry, status.can_retry(), 84),
];
let button_width: i32 = buttons
.iter()
.filter(|(_, visible, _)| *visible)
.map(|(_, _, size)| size + 6)
.sum();
let stacked = width < px(700) && button_width > 0;
let message_height = if status.detail().is_empty() { 20 } else { 40 };
let row_height = message_height.max(28);
let recovery_content_height = if stacked { message_height + 8 + 28 } else { row_height };
// Equal padding surrounds the controls; the divider occupies one physical pixel.
let recovery_height = px(recovery_content_height + 2 * RECOVERY_PADDING) + 1;
let header_height = if status == RecoveryStatus::Hidden {
px(TOOLBAR_HEIGHT)
} else {
px(TOOLBAR_HEIGHT) + recovery_height
};
self.recovery_bounds.set(RECT {
left: 0,
top: px(TOOLBAR_HEIGHT),
right: width,
bottom: header_height,
});
let message_width = if stacked {
width - px(24)
} else {
width - px(24 + button_width)
};
MoveWindow(
self.message,
px(12),
px(TOOLBAR_HEIGHT + RECOVERY_PADDING + if stacked { 0 } else { (row_height - message_height) / 2 }),
message_width.max(0),
px(message_height),
true,
)?;
let button_top = TOOLBAR_HEIGHT
+ RECOVERY_PADDING
+ if stacked {
message_height + 8
} else {
(row_height - 28) / 2
};
let mut right = width - px(8);
for (hwnd, visible, size) in buttons {
if visible {
right -= px(size);
MoveWindow(hwnd, right, px(button_top), px(size), px(28), true)?;
right -= px(6);
}
}
let content_height = (bounds.bottom - header_height).max(0);
MoveWindow(self.webview_host, 0, header_height, width, content_height, true)?;
state.controller.SetBounds(RECT {
left: 0,
top: 0,
right: width,
bottom: content_height,
})?;
let _ = InvalidateRect(Some(self.parent), None, true);
}
Ok(())
}
}
impl Drop for Controls {
fn drop(&mut self) {
if let Some((_, font)) = self.font.get() {
unsafe {
let _ = DeleteObject(font.into());
}
}
}
}
/// Keep the native edit's selection and accessibility, with a quiet, flat frame.
unsafe extern "system" fn address_proc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
_: usize,
) -> LRESULT {
if msg == WM_NCDESTROY {
unsafe {
let _ = RemoveWindowSubclass(hwnd, Some(address_proc), id);
}
}
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
// EDIT also repaints its frame during WM_PAINT, so style it after native drawing.
if matches!(msg, WM_NCPAINT | WM_PAINT) {
unsafe {
let dc = GetWindowDC(Some(hwnd));
let mut bounds = RECT::default();
if !dc.is_invalid() && GetWindowRect(hwnd, &mut bounds).is_ok() {
let background = GetSysColor(COLOR_3DFACE);
let foreground = GetSysColor(COLOR_WINDOWTEXT);
let mut border = 0;
for shift in [0, 8, 16] {
let channel = (((background >> shift) & 255) * 82 + ((foreground >> shift) & 255) * 18) / 100;
border |= channel << shift;
}
let brush = CreateSolidBrush(COLORREF(border));
FrameRect(
dc,
&RECT {
left: 0,
top: 0,
right: bounds.right - bounds.left,
bottom: bounds.bottom - bounds.top,
},
brush,
);
let _ = DeleteObject(brush.into());
}
ReleaseDC(Some(hwnd), dc);
}
}
result
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
key: usize,
) -> LRESULT {
let state = STATES.with_borrow(|states| states.get(&key).cloned());
if msg == WM_CTLCOLORSTATIC {
unsafe {
let dc = HDC(wparam.0 as *mut _);
let is_message = state
.as_ref()
.is_some_and(|state| state.controls.message.0 as isize == lparam.0);
let background = if is_message { COLOR_3DFACE } else { COLOR_WINDOW };
SetTextColor(dc, COLORREF(GetSysColor(COLOR_WINDOWTEXT)));
SetBkColor(dc, COLORREF(GetSysColor(background)));
return LRESULT(GetSysColorBrush(background).0 as isize);
}
}
// Paint the native toolbar and recovery surface outside the child webview.
if msg == WM_ERASEBKGND {
unsafe {
let mut bounds = RECT::default();
if GetClientRect(hwnd, &mut bounds).is_ok() {
let dc = HDC(wparam.0 as *mut _);
FillRect(dc, &bounds, GetSysColorBrush(COLOR_WINDOW));
if let Some(state) = &state {
let row = state.controls.recovery_bounds.get();
if row.bottom > row.top {
FillRect(dc, &row, GetSysColorBrush(COLOR_3DFACE));
let divider = RECT {
top: row.bottom - 1,
..row
};
FillRect(dc, &divider, GetSysColorBrush(COLOR_3DLIGHT));
}
}
}
}
return LRESULT(1);
}
if let Some(state) = &state {
if msg == WM_COMMAND && (wparam.0 >> 16) == BN_CLICKED as usize {
let event = match wparam.0 & 0xffff {
RETRY => Some(AuthEvent::Retry),
PROCEED => Some(AuthEvent::RequestTlsException),
CANCEL => Some(AuthEvent::Close),
_ => None,
};
if let Some(event) = event {
state.messenger.send_auth_event(event);
return LRESULT(0);
}
}
}
let result = unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) };
if msg == WM_SIZE || msg == WM_DPICHANGED {
if let Some(state) = &state {
let _ = state.controls.layout(state);
}
}
if msg == WM_NCDESTROY {
unsafe {
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
}
STATES.with_borrow_mut(|states| states.remove(&key));
if let Some(state) = state {
super::tls::clear_exceptions(&state.core);
}
}
result
}
+128
View File
@@ -0,0 +1,128 @@
use super::super::tls::{TlsFailure, TlsFailureReason};
use super::*;
use std::collections::HashSet;
use webview2_com::{ClearServerCertificateErrorActionsCompletedHandler, ServerCertificateErrorDetectedEventHandler};
use windows::Win32::UI::WindowsAndMessaging::{IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_YESNO, MessageBoxW};
#[derive(Default)]
pub(super) struct Policy {
pub ignore_errors: bool,
approved: HashSet<(String, String)>,
pending: Option<Failure>,
}
#[derive(Clone)]
struct Failure {
identity: (String, String),
failure: TlsFailure,
generation: u64,
}
fn reason(error: COREWEBVIEW2_WEB_ERROR_STATUS) -> TlsFailureReason {
match error {
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT => TlsFailureReason::HostnameMismatch,
COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED => TlsFailureReason::Expired,
_ => TlsFailureReason::InvalidCertificate,
}
}
pub(super) fn install(state: &Rc<State>) -> windows::core::Result<()> {
let weak = Rc::downgrade(state);
let handler = ServerCertificateErrorDetectedEventHandler::create(Box::new(move |_, args| {
let (Some(state), Some(args)) = (weak.upgrade(), args) else {
return Ok(());
};
unsafe {
let uri = text(|p| args.RequestUri(p))?;
let host = url::Url::parse(&uri)
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_default();
let pem = text(|p| args.ServerCertificate()?.ToPemEncoding(p))?;
let mut error = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN;
args.ErrorStatus(&mut error)?;
let identity = (host.clone(), pem);
let mut policy = state.tls.borrow_mut();
if policy.ignore_errors || policy.approved.contains(&identity) {
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_ALWAYS_ALLOW)?;
} else {
args.SetAction(COREWEBVIEW2_SERVER_CERTIFICATE_ERROR_ACTION_CANCEL)?;
let generation = state.document.borrow().1;
let failure = TlsFailure {
host,
reason: reason(error),
can_continue: error != COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_REVOKED,
};
state
.messenger
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure.clone())));
policy.pending = Some(Failure {
identity,
failure,
generation,
});
}
}
Ok(())
}));
let mut token = 0;
unsafe {
state
.core
.cast::<ICoreWebView2_14>()?
.add_ServerCertificateErrorDetected(&handler, &mut token)
}
}
pub(super) fn confirm(state: &State) -> anyhow::Result<()> {
let pending = state
.tls
.borrow()
.pending
.clone()
.context("No certificate error to confirm")?;
if !pending.failure.can_continue || pending.generation != state.messenger.generation() {
bail!("This certificate exception is no longer available");
}
let answer = unsafe {
MessageBoxW(
Some(state.controls.parent),
&HSTRING::from(pending.failure.confirmation_message()),
&HSTRING::from(pending.failure.confirmation_title()),
MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
)
};
if answer == IDYES {
let identity = pending.identity.clone();
let generation = pending.generation;
state.tls.borrow_mut().approved.insert(identity);
state.messenger.send_auth_event(AuthEvent::TlsAccepted(generation));
}
Ok(())
}
// WebView2 caches approvals in the session. Do not leave them for another sign-in window.
pub(super) fn clear_exceptions(core: &ICoreWebView2) {
if let Ok(core) = core.cast::<ICoreWebView2_14>() {
let _ = unsafe {
core.ClearServerCertificateErrorActions(&ClearServerCertificateErrorActionsCompletedHandler::create(Box::new(
|_| Ok(()),
)))
};
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_certificate_failure_reasons() {
assert_eq!(
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_COMMON_NAME_IS_INCORRECT),
TlsFailureReason::HostnameMismatch
);
assert_eq!(
reason(COREWEBVIEW2_WEB_ERROR_STATUS_CERTIFICATE_EXPIRED),
TlsFailureReason::Expired
);
}
}
+10 -3
View File
@@ -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 }
+5 -2
View File
@@ -1,8 +1,11 @@
#[cfg(all(feature = "launcher", windows))]
#[path = "platform/windows.rs"]
mod platform;
#[cfg(all(feature = "launcher", target_os = "macos"))]
#[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",
@@ -0,0 +1,35 @@
//! Windows browsers are resolved through their registered App Paths.
use crate::Browser;
use anyhow::{Context, bail};
use std::path::PathBuf;
use winreg::{
RegKey,
enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE},
};
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
let executable = match browser {
Browser::Auto | Browser::Default => return webbrowser::open(url).context("Could not open the browser"),
Browser::Chrome => registered_browser("chrome.exe").context("Chrome is not installed")?,
Browser::Edge => registered_browser("msedge.exe").context("Edge is not installed")?,
Browser::Firefox => registered_browser("firefox.exe").context("Firefox is not installed")?,
Browser::Safari => bail!("Safari is not available on Windows"),
Browser::Other(program) => PathBuf::from(program),
};
std::process::Command::new(executable)
.arg(url)
.spawn()
.context("Could not open the configured browser")?;
Ok(())
}
fn registered_browser(name: &str) -> Option<PathBuf> {
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE].into_iter().find_map(|hive| {
let key = RegKey::predef(hive)
.open_subkey(format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{name}"))
.ok()?;
let path: String = key.get_value("").ok()?;
let path = PathBuf::from(path.trim_matches('"'));
path.is_file().then_some(path)
})
}
+10 -5
View File
@@ -5,11 +5,16 @@ fn main() {
let workspace_dir = Path::new(manifest_dir).ancestors().nth(2).unwrap();
let 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());
+1 -1
View File
@@ -89,7 +89,7 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option<PathBuf> {
let executable = executable.canonicalize().ok()?;
let bin_dir = executable.parent()?;
let binary = bin_dir.join(binary_name);
let binary = bin_dir.join(format!("{binary_name}{}", std::env::consts::EXE_SUFFIX));
if is_file(&binary) {
return Some(binary);
}
-1
View File
@@ -2,7 +2,6 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
#[cfg(target_os = "linux")]
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
#[cfg(target_os = "linux")]
+1
View File
@@ -1,2 +1,3 @@
pub mod binary_paths;
pub mod constants;
pub mod paths;
+32
View File
@@ -0,0 +1,32 @@
//! Machine-wide service state shared by the daemon and desktop clients.
use std::path::PathBuf;
pub fn service_lock_file() -> PathBuf {
#[cfg(unix)]
{
PathBuf::from("/var/run/gpservice.lock")
}
#[cfg(windows)]
{
std::env::var_os("ProgramData")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
.join("GP Connect")
.join("gpservice.lock")
}
}
#[cfg(windows)]
pub const SERVICE_PIPE: &str = r"\\.\pipe\GPConnect.Service";
#[cfg(windows)]
pub const SERVICE_NAME: &str = "GPConnect";
/// Installer-owned SYSTEM/Administrators-only state, including temporary keys.
#[cfg(windows)]
pub fn service_private_dir() -> PathBuf {
service_lock_file()
.parent()
.expect("service state directory")
.join("Private")
}
+11
View File
@@ -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
+172
View File
@@ -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("<!doctype") {
return "[XML omitted: DTD]".into();
}
let Ok(nodes) = Element::parse_all(body) else {
return "[XML omitted: malformed or non-XML response]".into();
};
let mut roots = nodes.into_iter().filter_map(|node| match node {
XMLNode::Element(element) => 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#"<response><jnlp><application-desc><argument>fixture-auth-cookie</argument><argument>fixture-user</argument></application-desc></jnlp><ipsec><ekey-c2s><bits>256</bits><val>fixture-key-c2s</val></ekey-c2s><ekey-s2c>fixture-key-s2c</ekey-s2c><akey-c2s><val>fixture-auth-c2s</val></akey-c2s><akey-s2c>fixture-auth-s2c</akey-s2c></ipsec><enc-hs-key>fixture-hs-key</enc-hs-key><PrivateKey>fixture-private-key</PrivateKey><SAMLResponse>fixture-saml-response</SAMLResponse><tunnel-opaque><val>fixture-opaque</val></tunnel-opaque><mtu>1400</mtu></response>"#);
assert!(!xml.contains("fixture-"));
assert!(xml.contains("<mtu>1400</mtu>"));
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"<response><cookie>fixture-secret",
b"<html><body>fixture-secret</body></html>",
b"<!DOCTYPE response [<!ENTITY secret 'fixture-secret'>]><response>&secret;</response>",
b"<response/>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]"
);
}
}
+36 -5
View File
@@ -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"]
+16
View File
@@ -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.
+16 -2
View File
@@ -10,6 +10,7 @@ pub enum AnchorSource {
UnixMac,
UnixRandom,
MacosIokit,
WindowsSmbios,
}
impl From<AnchorSource> for u8 {
@@ -18,6 +19,7 @@ impl From<AnchorSource> for u8 {
AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3,
AnchorSource::WindowsSmbios => 4,
}
}
}
@@ -41,6 +43,7 @@ impl TryFrom<u8> for AnchorSource {
1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit),
4 => Ok(Self::WindowsSmbios),
value => Err(InvalidAnchorSource(value)),
}
}
@@ -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::<AnchorSource>("4").unwrap(),
AnchorSource::WindowsSmbios
);
assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac
);
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
assert!(serde_json::from_str::<AnchorSource>("5").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
}
}
+11 -1
View File
@@ -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::{
+4 -1
View File
@@ -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);
}
+5 -10
View File
@@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &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<HashMap<Str
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
fn parse_extend_session_status(root: &Element) -> anyhow::Result<String> {
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#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
assert_eq!(parse_extend_session_status(&root).unwrap(), "success");
}
#[test]
@@ -242,9 +239,7 @@ mod tests {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
parse_extend_session_status(&root).unwrap_err().to_string(),
"Malformed extend session response"
);
}
+40 -6
View File
@@ -70,17 +70,17 @@ impl GuiVariant {
}
}
#[cfg(target_os = "linux")]
fn preference_path() -> anyhow::Result<PathBuf> {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn preference_path(name: &str) -> anyhow::Result<PathBuf> {
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<GuiVariant> {
#[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<GuiVariant> {
#[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<PathBuf> {
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(())
}
+24
View File
@@ -45,3 +45,27 @@ mod tests {
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
}
}
/// Collection metadata for the exact XML returned by a generated preview.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HipReport {
pub xml: String,
pub windows_updates: Option<WindowsUpdateStatus>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WindowsUpdateStatus {
/// Present only when this report includes a completed local patch observation.
pub checked_at: Option<u64>,
/// 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<u64>,
}
impl WindowsUpdateStatus {
pub fn refresh_cursor(&self) -> Option<u64> {
self.checked_at.or(self.omitted_snapshot_at)
}
}
+3
View File
@@ -31,3 +31,6 @@ pub mod clap;
#[cfg(feature = "desktop")]
pub mod script_tun;
#[cfg(all(feature = "desktop", windows))]
pub mod windows;
+14
View File
@@ -12,6 +12,20 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
type BoxedLogger = Box<dyn Log + Send + Sync>;
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::init_file;
/// Keep helper diagnostics with the application's records when a file logger owns them.
pub fn diagnostic_writer() -> Box<dyn std::io::Write + Send> {
#[cfg(windows)]
if let Some(writer) = windows::diagnostic_writer() {
return writer;
}
Box::new(std::io::stderr())
}
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
#[cfg(target_os = "macos")]
if log_format == LogFormat::Text && macos_unified_log_enabled() {
+98
View File
@@ -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<DiagnosticWriter> = OnceLock::new();
#[derive(Clone)]
struct DiagnosticWriter(Arc<Mutex<FileRotate<AppendCount>>>);
impl DiagnosticWriter {
fn open(path: &Path) -> io::Result<Self> {
if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
// FileRotate's constructor suppresses open errors, so check the destination first.
OpenOptions::new().create(true).append(true).open(path)?;
Ok(Self(Arc::new(Mutex::new(FileRotate::new(
path,
AppendCount::new(ARCHIVE_COUNT),
ContentLimit::BytesSurpassed(ROTATE_BYTES),
Compression::None,
None,
)))))
}
}
impl Write for DiagnosticWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self
.0
.lock()
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
.write(bytes)
}
fn flush(&mut self) -> io::Result<()> {
self
.0
.lock()
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
.flush()
}
}
pub fn init_file(path: &Path, level: log::Level) -> io::Result<()> {
let writer = DiagnosticWriter::open(path)?;
let logger = super::build_env_logger(crate::log_format::LogFormat::Text)
.target(env_logger::Target::Pipe(Box::new(writer.clone())))
.build();
DIAGNOSTICS
.set(writer)
.map_err(|_| io::Error::other("File logging is already initialized"))?;
super::init_with_logger(level, logger);
Ok(())
}
pub(super) fn diagnostic_writer() -> Option<Box<dyn Write + Send>> {
DIAGNOSTICS
.get()
.map(|writer| Box::new(writer.clone()) as Box<dyn Write + Send>)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gui_and_helper_writers_share_rotation_and_keep_only_three_archives() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("logs/gui.log");
let mut gui = DiagnosticWriter::open(&path).unwrap();
let mut helper = gui.clone();
for marker in b'0'..=b'5' {
let writer = if marker % 2 == 0 { &mut gui } else { &mut helper };
writer.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
}
helper.flush().unwrap();
drop((gui, helper));
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
assert_eq!(
fs::read(path.with_extension(format!("log.{suffix}"))).unwrap(),
vec![marker; ROTATE_BYTES + 1]
);
}
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 4);
let mut reopened = DiagnosticWriter::open(&path).unwrap();
reopened.write_all(b"after restart\n").unwrap();
reopened.flush().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"after restart\n");
}
}
+8 -1
View File
@@ -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,
+85 -2
View File
@@ -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());
}
}
+66 -19
View File
@@ -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<String> {
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<String> {
}
fn windows_machine_seed() -> Option<String> {
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<String> {
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<String> {
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
// Native Windows uses the OS installation ID and physical NetBIOS name.
// Keep the hardware identity used to seed other OS profiles unchanged.
pub(super) fn native_profile_identity(
identity: super::HostIdentity,
host_id_override: Option<&str>,
) -> io::Result<super::HostIdentity> {
let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) {
Some(id) => id.to_owned(),
None => collect_windows_machine_guid()?,
};
Ok(super::HostIdentity::from_parts(
collect_windows_computer_name()?,
host_id,
identity.serialno().into(),
identity.mac_addr().into(),
))
}
fn collect_windows_computer_name() -> io::Result<String> {
let mut name = [0u16; 256];
let mut size = name.len() as u32;
// SAFETY: the buffer and character count describe writable UTF-16 storage.
if unsafe { GetComputerNameExW(ComputerNamePhysicalNetBIOS, name.as_mut_ptr(), &mut size) } == 0 {
return Err(io::Error::last_os_error());
}
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<String> {
let key: Vec<u16> = "SOFTWARE\\Microsoft\\Cryptography\0".encode_utf16().collect();
let value: Vec<u16> = "MachineGuid\0".encode_utf16().collect();
let mut buffer = [0u16; 128];
let mut size = std::mem::size_of_val(&buffer) as u32;
// SAFETY: both names are NUL-terminated; buffer and byte length describe writable storage.
let status = unsafe {
RegGetValueW(
HKEY_LOCAL_MACHINE,
key.as_ptr(),
value.as_ptr(),
RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY,
std::ptr::null_mut(),
buffer.as_mut_ptr().cast(),
&mut size,
)
};
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32));
}
let end = buffer.iter().position(|value| *value == 0).unwrap_or(buffer.len());
let guid = String::from_utf16(&buffer[..end]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
if guid.trim().is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Windows MachineGuid is empty",
));
}
Ok(guid)
}
impl RuntimeNativeHostIdentity {
+1 -2
View File
@@ -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
}
+6 -6
View File
@@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() {
}
#[test]
fn csc_support_defaults_match_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())
+9 -5
View File
@@ -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()));
}
+2 -4
View File
@@ -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())
})?;
+140 -16
View File
@@ -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<dyn std::io::Write + Send> = 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::<std::io::Error>()
.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<dyn std::io::Write + Send>);
impl std::io::Write for AuthStderr {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
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));
}
}
}
+19 -3
View File
@@ -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<String, String>>,
credential: &SessionCredential,
cancellation: &CancellationToken,
detect_gbm_failure: bool,
) -> anyhow::Result<ExitStatus> {
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());
+5 -1
View File
@@ -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?;
}
@@ -79,6 +79,7 @@ impl<'a> GuiHelperLauncher<'a> {
self.envs,
self.credential,
cancellation,
false,
)
.await?;
Ok(())
+46 -26
View File
@@ -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::<GbmBufferFailure>() && 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();
+23 -2
View File
@@ -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;
+98 -6
View File
@@ -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<String>,
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::<RenderingCrash>().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::<GbmBufferFailure>().is_some();
if !gbm_failure && error.downcast_ref::<RenderingCrash>().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<std::ffi::OsString> {
for (name, value) in command.get_envs() {
if name == key {
@@ -73,12 +105,21 @@ fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ff
inherits.then(|| std::env::var_os(key)).flatten()
}
pub(crate) fn is_gbm_diagnostic(line: &[u8]) -> 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<u8>,
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;
@@ -0,0 +1,42 @@
//! Resolve system collectors from Windows' system directory, never the working directory.
use super::command_runner::run_controlled;
use crate::collection::CollectionControl;
use std::{
io,
path::{Path, PathBuf},
process::{Command, Output},
};
pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl,
}
impl<'a> CollectorCommands<'a> {
pub fn new(control: &'a dyn CollectionControl) -> Self {
Self { control }
}
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
let system = std::env::var_os("SystemRoot")?;
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
path.is_file().then_some(path)
}
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
match self.resolve(name) {
Some(path) => self.run_path(&path, args),
None => Ok(None),
}
}
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.run_path(path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let mut command = Command::new(path);
command.args(args);
match run_controlled(command, self.control, 256 * 1024) {
Ok(output) => Ok(Some(output)),
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
Err(error) => Err(error),
}
}
}
@@ -0,0 +1,198 @@
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
use crate::collection::CollectionControl;
use std::{
io::{self, Read, Write},
os::windows::io::AsRawHandle,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
};
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
pub(crate) enum ChildInput<'a> {
Null,
Terminal,
// Preserve the borrowed input type shared by callers without a Windows launcher.
#[allow(dead_code)]
Frame(&'a [u8]),
}
#[derive(Debug)]
pub(crate) struct ObservedOutput {
pub output: Output,
}
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
run_observed(
command,
control,
Some(limit),
&mut |_| {},
&mut io::sink(),
ChildInput::Null,
)
.map(|observed| observed.output)
}
pub(crate) fn run_observed(
mut command: Command,
control: &dyn CollectionControl,
output_limit: Option<usize>,
observer: &mut dyn FnMut(&[u8]),
stderr_sink: &mut dyn Write,
stdin: ChildInput<'_>,
) -> io::Result<ObservedOutput> {
control.check()?;
// Windows desktop processes must not open a console for each helper.
use std::os::windows::process::CommandExt;
if !matches!(stdin, ChildInput::Terminal) {
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
command.stdout(if output_limit.is_some() {
Stdio::piped()
} else {
Stdio::inherit()
});
command.stderr(Stdio::piped());
command.stdin(match stdin {
ChildInput::Terminal => Stdio::inherit(),
ChildInput::Null => Stdio::null(),
ChildInput::Frame(_) => Stdio::piped(),
});
let mut child = ControlledChild(command.spawn()?);
let input = if let ChildInput::Frame(frame) = stdin {
let mut pipe = child.0.stdin.take().expect("piped stdin");
let frame = frame.to_vec();
Some(thread::spawn(move || pipe.write_all(&frame)))
} else {
None
};
let mut stdout = child.0.stdout.take();
let mut stderr = child.0.stderr.take().expect("piped stderr");
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
loop {
control.check()?;
if let Some(pipe) = &mut stdout {
let length = read_available(pipe, &mut buffer)?;
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
let length = read_available(&mut stderr, &mut buffer)?;
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
if let Some(status) = child.0.try_wait()? {
// Drain the remaining buffered output after the process exits.
if let Some(pipe) = &mut stdout {
loop {
let length = read_available(pipe, &mut buffer)?;
if length == 0 {
break;
}
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
}
loop {
let length = read_available(&mut stderr, &mut buffer)?;
if length == 0 {
break;
}
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
}
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
result?;
}
return Ok(ObservedOutput {
output: Output {
status,
stdout: output,
stderr: Vec::new(),
},
});
}
thread::sleep(Duration::from_millis(10));
}
}
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
let mut available = 0;
let success = unsafe {
PeekNamedPipe(
pipe.as_raw_handle(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
&mut available,
std::ptr::null_mut(),
)
};
if success == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(109) {
return Ok(0);
} // ERROR_BROKEN_PIPE
return Err(error);
}
let length = buffer.len().min(available as usize);
if length == 0 {
return Ok(0);
}
pipe.read(&mut buffer[..length])
}
struct ControlledChild(Child);
impl Drop for ControlledChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captures_output_and_rejects_excess_output() {
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo hello"]);
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
assert!(result.status.success());
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo too much"]);
assert_eq!(
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
io::ErrorKind::InvalidData
);
}
#[test]
fn cancels_a_running_helper() {
let start = std::time::Instant::now();
let mut command = Command::new("powershell.exe");
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
let control = || {
if start.elapsed() > Duration::from_millis(150) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
assert_eq!(
run_controlled(command, &control, 1024).unwrap_err().kind(),
io::ErrorKind::Interrupted
);
assert!(start.elapsed() < Duration::from_secs(3));
}
}
@@ -0,0 +1,12 @@
use tokio::process::Command;
/// Windows authentication runs in the interactive user's GUI process.
pub trait CommandExt {
fn into_non_root(self) -> anyhow::Result<Command>;
}
impl CommandExt for Command {
fn into_non_root(self) -> anyhow::Result<Command> {
Ok(self)
}
}
@@ -0,0 +1,309 @@
//! Launch a native worker with the admitted user's primary token and environment.
use std::{
ffi::{OsStr, c_void},
io,
os::windows::{
ffi::OsStrExt,
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
},
path::Path,
ptr,
};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
Security::{ImpersonateLoggedOnUser, RevertToSelf},
System::{
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
JobObjects::*,
Threading::*,
},
};
pub struct UserProcess {
process: OwnedHandle,
job: Option<OwnedHandle>,
pid: u32,
}
struct Environment(*mut c_void);
impl Drop for Environment {
fn drop(&mut self) {
unsafe {
DestroyEnvironmentBlock(self.0);
}
}
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
let value: Vec<_> = value.encode_wide().collect();
if value.contains(&0) {
return Err(invalid("Windows process strings cannot contain NUL"));
}
Ok(value)
}
fn quote(argument: &[u16], output: &mut Vec<u16>) {
output.push(b'"' as u16);
let mut backslashes = 0;
for &character in argument {
if character == b'\\' as u16 {
backslashes += 1;
continue;
}
let count = if character == b'"' as u16 {
backslashes * 2 + 1
} else {
backslashes
};
output.extend(std::iter::repeat_n(b'\\' as u16, count));
output.push(character);
backslashes = 0;
}
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
output.push(b'"' as u16);
}
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
let mut output = Vec::new();
quote(program, &mut output);
for argument in arguments {
output.push(b' ' as u16);
quote(&wide(OsStr::new(argument))?, &mut output);
}
output.push(0);
if output.len() > 32767 {
return Err(invalid("Windows worker command line is too long"));
}
Ok(output)
}
fn key(entry: &[u16]) -> &[u16] {
let end = entry
.iter()
.enumerate()
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
.map(|(index, _)| index)
.unwrap_or(entry.len());
&entry[..end]
}
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
// Environment names follow Windows' ordinal, case-insensitive ordering.
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
.cmp(&CSTR_EQUAL)
}
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
let mut pointer = ptr::null_mut();
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
return Err(io::Error::last_os_error());
}
let environment = Environment(pointer);
let mut entries = Vec::new();
unsafe {
let mut current = environment.0.cast::<u16>();
while *current != 0 {
let mut length = 0;
while *current.add(length) != 0 {
length += 1;
}
entries.push(std::slice::from_raw_parts(current, length).to_vec());
current = current.add(length + 1);
}
}
for (name, value) in variables {
if name.is_empty() || name.contains('=') {
return Err(invalid("Invalid worker environment name"));
}
let name = wide(OsStr::new(name))?;
let value = wide(OsStr::new(value))?;
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
let mut entry = name;
entry.push(b'=' as u16);
entry.extend(value);
entries.push(entry);
}
entries.sort_by(|left, right| compare(key(left), key(right)));
let mut block = Vec::new();
for entry in entries {
block.extend(entry);
block.push(0);
}
if block.is_empty() {
block.push(0);
}
block.push(0);
Ok(block)
}
impl UserProcess {
/// No service handles or service environment are inherited. The user token
/// determines the Windows session, including an existing interactive desktop.
pub fn launch(
token: BorrowedHandle<'_>,
program: &Path,
arguments: &[String],
variables: &[(&str, &str)],
) -> io::Result<Self> {
if !program.is_absolute() {
return Err(invalid("Windows worker executable must be absolute"));
}
let mut executable = wide(program.as_os_str())?;
let mut command = command_line(&executable, arguments)?;
executable.push(0);
let mut environment = user_environment(token, variables)?;
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
let mut directory = wide(directory.as_os_str())?;
directory.push(0);
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
if job.is_null() {
return Err(io::Error::last_os_error());
}
let job = unsafe { OwnedHandle::from_raw_handle(job) };
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
..Default::default()
},
..Default::default()
};
if unsafe {
SetInformationJobObject(
job.as_raw_handle(),
JobObjectExtendedLimitInformation,
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
std::mem::size_of_val(&limits) as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
let startup = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
lpDesktop: desktop.as_mut_ptr(),
..Default::default()
};
let mut information = PROCESS_INFORMATION::default();
// Read/execute the requested image as its user, as Unix exec-after-setuid
// does. The service's filesystem access must not authorize a private image.
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
return Err(io::Error::last_os_error());
}
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
let revert = Revert;
let created = unsafe {
CreateProcessAsUserW(
token.as_raw_handle(),
executable.as_ptr(),
command.as_mut_ptr(),
ptr::null(),
ptr::null(),
0,
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
environment.as_mut_ptr().cast(),
directory.as_ptr(),
&startup,
&mut information,
)
};
let error = (created == 0).then(io::Error::last_os_error);
drop(revert);
if let Some(error) = error {
return Err(error);
}
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
let error = io::Error::last_os_error();
// The suspended child is not owned by the job on this failure path.
unsafe {
TerminateProcess(process.as_raw_handle(), 1);
WaitForSingleObject(process.as_raw_handle(), 5000);
}
return Err(error);
}
let child = Self {
process,
job: Some(job),
pid: information.dwProcessId,
};
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
Ok(child)
}
pub fn id(&self) -> u32 {
self.pid
}
pub fn has_exited(&self) -> io::Result<bool> {
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
WAIT_OBJECT_0 => Ok(true),
WAIT_TIMEOUT => Ok(false),
_ => Err(io::Error::last_os_error()),
}
}
pub fn stop(&mut self) -> io::Result<()> {
if self.job.take().is_none() {
return Ok(());
}
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
WAIT_OBJECT_0 => Ok(()),
WAIT_TIMEOUT => Err(io::Error::new(
io::ErrorKind::TimedOut,
"Windows worker did not terminate",
)),
_ => Err(io::Error::last_os_error()),
}
}
}
impl Drop for UserProcess {
fn drop(&mut self) {
if let Err(error) = self.stop() {
log::warn!("Could not stop Windows worker: {error}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
#[test]
fn command_line_round_trips_through_windows_parser() {
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
let arguments = [
"proxy-worker",
"",
"space value",
"quoted\"value",
"two\\\\\"quotes",
"trailing\\",
"雪",
"&|<>",
]
.map(String::from);
let command = command_line(&program, &arguments).unwrap();
let mut count = 0;
unsafe {
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
assert!(!parsed.is_null());
let result = std::slice::from_raw_parts(parsed, count as usize)
.iter()
.map(|&value| {
let mut length = 0;
while *value.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
})
.collect::<Vec<_>>();
LocalFree(parsed.cast());
assert_eq!(result[0], String::from_utf16_lossy(&program));
assert_eq!(result[1..], arguments);
}
}
}
+2
View File
@@ -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<u64> },
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StopNonTunnelAttachment { connection_id: uuid::Uuid },
@@ -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
@@ -55,6 +55,8 @@ pub enum ServiceResult {
offset: usize,
xml: String,
complete: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
windows_updates: Option<crate::hip::WindowsUpdateStatus>,
},
HipApprovalStatus(HipApprovalStatus),
NoSubmittedHipReport,
@@ -11,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;
@@ -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<String> {
let output = CollectorCommands::new(control)
.run(name, args)?
@@ -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();
@@ -0,0 +1,148 @@
//! Windows network identity from IP Helper and adapter DNS configuration.
use super::*;
use std::os::windows::io::AsRawSocket;
use windows_sys::Win32::{
NetworkManagement::IpHelper::{
DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1, FreeInterfaceDnsSettings, FreeMibTable,
GetInterfaceDnsSettings, GetIpForwardTable2,
},
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, IP_UNICAST_IF, IPPROTO_IP, IPPROTO_IPV6, IPV6_UNICAST_IF, SOCKADDR_INET,
SOCKET_ERROR, WSAGetLastError, setsockopt,
},
};
pub(super) fn scope_resolver_socket(
socket: &tokio::net::UdpSocket,
interface: &Interface,
endpoint: SocketAddr,
) -> anyhow::Result<()> {
ensure!(interface.index != 0, "Resolver interface index is missing");
// IP_UNICAST_IF uses network byte order; IPV6_UNICAST_IF uses host byte order.
let (level, option, index) = if endpoint.is_ipv4() {
(IPPROTO_IP, IP_UNICAST_IF, interface.index.to_be())
} else {
(IPPROTO_IPV6, IPV6_UNICAST_IF, interface.index)
};
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
level,
option,
(&index as *const u32).cast(),
std::mem::size_of::<u32>() as i32,
)
};
if result == SOCKET_ERROR {
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }).into());
}
Ok(())
}
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
control.check()?;
let mut table = std::ptr::null_mut();
let status = unsafe { GetIpForwardTable2(AF_UNSPEC, &mut table) };
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32).into());
}
let interfaces = netdev::get_interfaces();
let result = unsafe {
let rows = std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize);
rows
.iter()
.filter_map(|row| {
let destination = address(&row.DestinationPrefix.Prefix)?;
let gateway = address(&row.NextHop)?;
let interface = interfaces
.iter()
.find(|interface| interface.index == row.InterfaceIndex)?;
Some(RouteContext {
destination: format!("{destination}/{}", row.DestinationPrefix.PrefixLength),
gateway: gateway.to_string(),
interface: interface.name.clone(),
table: "main".into(),
metric: row.Metric.to_string(),
})
})
.collect()
};
unsafe {
FreeMibTable(table.cast());
}
control.check()?;
Ok(result)
}
unsafe fn address(address: &SOCKADDR_INET) -> Option<IpAddr> {
unsafe {
match address.si_family {
AF_INET => Some(std::net::Ipv4Addr::from(address.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()),
AF_INET6 => Some(std::net::Ipv6Addr::from(address.Ipv6.sin6_addr.u.Byte).into()),
_ => None,
}
}
}
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
control.check()?;
let mut resolvers = netdev::get_interfaces()
.into_iter()
.filter(|interface| !interface.dns_servers.is_empty())
.map(|interface| {
Ok(ResolverContext {
interface: Some(interface.name.clone()),
servers: interface.dns_servers.iter().map(ToString::to_string).collect(),
domains: resolver_domains(&interface.name)?,
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
resolvers.sort();
control.check()?;
Ok(resolvers)
}
fn resolver_domains(interface: &str) -> anyhow::Result<Vec<String>> {
let id = uuid::Uuid::parse_str(interface.trim_matches(['{', '}']))?;
let (data1, data2, data3, data4) = id.as_fields();
let guid = windows_sys::core::GUID {
data1,
data2,
data3,
data4: *data4,
};
let mut settings = DNS_INTERFACE_SETTINGS {
Version: DNS_INTERFACE_SETTINGS_VERSION1,
..Default::default()
};
let status = unsafe { GetInterfaceDnsSettings(guid, &mut settings) };
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32).into());
}
let mut domains = Vec::new();
for pointer in [settings.Domain, settings.SearchList] {
if pointer.is_null() {
continue;
}
let text = unsafe {
let mut length = 0;
while *pointer.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
};
for domain in text
.split(|ch: char| ch == ',' || ch.is_whitespace())
.filter(|domain| !domain.is_empty())
{
let domain = domain.to_ascii_lowercase();
if !domains.contains(&domain) {
domains.push(domain);
}
}
}
unsafe {
FreeInterfaceDnsSettings(&mut settings);
}
Ok(domains)
}
@@ -45,7 +45,7 @@ fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) ->
Ok(builder.interface(binding.interface()))
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
if let std::net::SocketAddr::V6(source) = binding.source() {
anyhow::ensure!(
@@ -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)
}
@@ -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"));
+2 -2
View File
@@ -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<LockInfo, LockFileError> {
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
gpservice_lock_info_at(service_lock_file()).await
}
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
+28 -14
View File
@@ -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<reqwest::Error>,
}
impl GpError {
pub(crate) fn take_body_read_error(&mut self) -> Option<reqwest::Error> {
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<String, GpError>
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: "<failed to read response>".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(|| "<none>", |v| v.to_str().unwrap_or("<invalid header>"))
.to_string();
let (body, source) = match res.text().await {
Ok(body) => (if body.is_empty() { "<empty>".to_string() } else { body }, None),
Err(error) => ("<failed to read response>".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 }
}
+2
View File
@@ -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());
+59
View File
@@ -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");
}
}
@@ -13,6 +13,9 @@ pub async fn shutdown_signal() {
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
+176
View File
@@ -0,0 +1,176 @@
//! Windows user identity and private local IPC.
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
use std::{io, ptr};
mod pipes;
pub use pipes::{PacketPipe, connect_service_admission, connect_service_worker, create_service_admission_pipe};
use tokio::net::windows::named_pipe::NamedPipeServer;
use windows_sys::Win32::{
Foundation::{CloseHandle, LocalFree},
Security::{Authorization::ConvertSidToStringSidW, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser},
System::Threading::{GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION},
};
pub fn current_user_sid() -> io::Result<String> {
unsafe {
let mut token = ptr::null_mut();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let result = token_user_sid(token);
CloseHandle(token);
result
}
}
/// An authenticated pipe client's primary token, retained for its user-session worker.
/// Windows user identity is a SID and token; it is never represented as a Unix UID.
pub struct PipeClientIdentity {
sid: String,
token: OwnedHandle,
}
impl PipeClientIdentity {
pub fn sid(&self) -> &str {
&self.sid
}
pub fn primary_token(&self) -> BorrowedHandle<'_> {
self.token.as_handle()
}
/// Call after reading the client's admission request. Impersonation stays on
/// this thread and ends before returning; no asynchronous work can run in it.
pub fn from_pipe(pipe: &NamedPipeServer) -> io::Result<Self> {
use windows_sys::Win32::{
Security::{
DuplicateTokenEx, RevertToSelf, SecurityImpersonation, TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TokenPrimary,
},
System::{
Pipes::ImpersonateNamedPipeClient,
Threading::{GetCurrentThread, OpenThreadToken},
},
};
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
// Continuing a service thread as its client would corrupt its privilege
// boundary. Windows documents terminating if RevertToSelf fails.
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
unsafe {
if ImpersonateNamedPipeClient(pipe.as_raw_handle()) == 0 {
return Err(io::Error::last_os_error());
}
let _revert = Revert;
let mut token = ptr::null_mut();
if OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, 1, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let token = OwnedHandle::from_raw_handle(token);
let sid = token_user_sid(token.as_raw_handle())?;
let mut primary = ptr::null_mut();
if DuplicateTokenEx(
token.as_raw_handle(),
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,
ptr::null(),
SecurityImpersonation,
TokenPrimary,
&mut primary,
) == 0
{
return Err(io::Error::last_os_error());
}
Ok(Self {
sid,
token: OwnedHandle::from_raw_handle(primary),
})
}
}
}
/// Resolve a local IPC peer from its OS process token.
pub fn process_user_sid(pid: u32) -> io::Result<String> {
unsafe {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if process.is_null() {
return Err(io::Error::last_os_error());
}
let mut token = ptr::null_mut();
if OpenProcessToken(process, TOKEN_QUERY, &mut token) == 0 {
let error = io::Error::last_os_error();
CloseHandle(process);
return Err(error);
}
CloseHandle(process);
let result = token_user_sid(token);
CloseHandle(token);
result
}
}
unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result<String> {
unsafe {
let mut length = 0;
GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut length);
// TOKEN_USER contains pointers; retain pointer alignment in its backing allocation.
let mut buffer = vec![0usize; (length as usize).div_ceil(std::mem::size_of::<usize>())];
if GetTokenInformation(token, TokenUser, buffer.as_mut_ptr().cast(), length, &mut length) == 0 {
return Err(io::Error::last_os_error());
}
let user = &*buffer.as_ptr().cast::<TOKEN_USER>();
let mut text = ptr::null_mut();
if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 {
return Err(io::Error::last_os_error());
}
let mut length = 0;
while *text.add(length) != 0 {
length += 1;
}
let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
LocalFree(text.cast());
Ok(sid)
}
}
/// Only the owning user and SYSTEM can access authentication callbacks.
pub fn create_user_pipe(name: &str, first_instance: bool) -> io::Result<NamedPipeServer> {
pipes::user_pipe(&current_user_sid()?, name, first_instance)
}
/// Query a registered service without requiring access to its SYSTEM process token.
pub fn service_process_id(name: &str) -> io::Result<u32> {
use windows_sys::Win32::System::Services::*;
let name: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
unsafe {
let manager = OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT);
if manager.is_null() {
return Err(io::Error::last_os_error());
}
let service = OpenServiceW(manager, name.as_ptr(), SERVICE_QUERY_STATUS);
if service.is_null() {
let error = io::Error::last_os_error();
CloseServiceHandle(manager);
return Err(error);
}
let mut status = SERVICE_STATUS_PROCESS::default();
let mut length = 0;
let success = QueryServiceStatusEx(
service,
SC_STATUS_PROCESS_INFO,
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
std::mem::size_of_val(&status) as u32,
&mut length,
);
let result = if success == 0 {
Err(io::Error::last_os_error())
} else {
Ok(status.dwProcessId)
};
CloseServiceHandle(service);
CloseServiceHandle(manager);
result
}
}
+202
View File
@@ -0,0 +1,202 @@
//! Local service admission and worker pipes with explicit user access.
use super::PipeClientIdentity;
use std::{
fs::OpenOptions,
io,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle},
},
ptr,
time::Duration,
};
use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer, ServerOptions};
use windows_sys::Win32::{
Foundation::{ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0, WAIT_TIMEOUT},
Security::{Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, SECURITY_ATTRIBUTES},
Storage::FileSystem::*,
System::{
IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED},
Pipes::*,
Threading::{CreateEventW, WaitForSingleObject},
},
};
// Generic write also grants FILE_CREATE_PIPE_INSTANCE. Clients receive only
// data/metadata access; creating another instance remains SYSTEM-only.
const CLIENT_ACCESS: u32 = FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES;
fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(Some(0)).collect()
}
fn with_security<T>(sddl: &str, operation: impl FnOnce(&SECURITY_ATTRIBUTES) -> io::Result<T>) -> io::Result<T> {
struct Descriptor(*mut std::ffi::c_void);
impl Drop for Descriptor {
fn drop(&mut self) {
unsafe {
LocalFree(self.0);
}
}
}
let mut pointer = ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(wide(sddl).as_ptr(), 1, &mut pointer, ptr::null_mut())
} == 0
{
return Err(io::Error::last_os_error());
}
let descriptor = Descriptor(pointer);
operation(&SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: 0,
})
}
fn server(sddl: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
with_security(sddl, |attributes| unsafe {
ServerOptions::new()
.first_pipe_instance(first)
.reject_remote_clients(true)
.create_with_security_attributes_raw(name, (attributes as *const SECURITY_ATTRIBUTES).cast_mut().cast())
})
}
pub(super) fn user_pipe(sid: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
server(&format!("D:P(A;;GA;;;SY)(A;;GA;;;{sid})"), name, first)
}
pub fn create_service_admission_pipe(first: bool) -> io::Result<NamedPipeServer> {
server(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;AU)"),
common::paths::SERVICE_PIPE,
first,
)
}
fn client(name: &str, message: bool, impersonation: bool) -> io::Result<NamedPipeClient> {
let file = OpenOptions::new()
.read(true)
.write(true)
.access_mode(CLIENT_ACCESS)
.custom_flags(FILE_FLAG_OVERLAPPED)
.security_qos_flags(if impersonation {
SECURITY_IMPERSONATION
} else {
SECURITY_IDENTIFICATION
})
.open(name)?;
let pipe = unsafe { NamedPipeClient::from_raw_handle(file.into_raw_handle()) }?;
let mut pid = 0;
if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut pid) } == 0 {
return Err(io::Error::last_os_error());
}
if pid == 0 || pid != super::service_process_id(common::paths::SERVICE_NAME)? {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Pipe does not belong to the registered VPN service",
));
}
if message {
let mode = PIPE_READMODE_MESSAGE;
if unsafe { SetNamedPipeHandleState(pipe.as_raw_handle(), &mode, ptr::null(), ptr::null()) } == 0 {
return Err(io::Error::last_os_error());
}
}
Ok(pipe)
}
/// Verify the service before the first request permits it to impersonate this user.
pub fn connect_service_admission() -> io::Result<NamedPipeClient> {
client(common::paths::SERVICE_PIPE, false, true)
}
pub fn connect_service_worker(name: &str, message: bool) -> io::Result<NamedPipeClient> {
client(name, message, false)
}
impl PipeClientIdentity {
pub fn create_control_pipe(&self, name: &str) -> io::Result<NamedPipeServer> {
server(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
name,
true,
)
}
pub fn create_packet_pipe(&self, name: &str) -> io::Result<PacketPipe> {
let name = wide(name);
with_security(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
|attributes| {
let handle = unsafe {
CreateNamedPipeW(
name.as_ptr(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS,
1,
256 * 1024,
256 * 1024,
0,
attributes,
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(PacketPipe(unsafe { OwnedHandle::from_raw_handle(handle) }))
},
)
}
}
/// Raw Win32 overlapped I/O, deliberately never registered with Tokio/Mio IOCP.
pub struct PacketPipe(OwnedHandle);
impl PacketPipe {
pub fn connect(&mut self, expected_pid: u32, timeout: Duration) -> io::Result<()> {
let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
if event.is_null() {
return Err(io::Error::last_os_error());
}
let event = unsafe { OwnedHandle::from_raw_handle(event) };
let mut overlap = OVERLAPPED {
hEvent: event.as_raw_handle(),
..Default::default()
};
if unsafe { ConnectNamedPipe(self.0.as_raw_handle(), &mut overlap) } == 0 {
let error = io::Error::last_os_error();
match error.raw_os_error().map(|code| code as u32) {
Some(ERROR_PIPE_CONNECTED) => {}
Some(ERROR_IO_PENDING) => {
let status = unsafe {
WaitForSingleObject(
event.as_raw_handle(),
timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
)
};
let mut bytes = 0;
if status != WAIT_OBJECT_0 {
// Complete cancellation before OVERLAPPED/event storage is released.
unsafe {
CancelIoEx(self.0.as_raw_handle(), &overlap);
GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 1);
}
if status == WAIT_TIMEOUT {
return Err(io::Error::new(io::ErrorKind::TimedOut, "Packet worker did not connect"));
}
return Err(io::Error::last_os_error());
}
if unsafe { GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 0) } == 0 {
return Err(io::Error::last_os_error());
}
}
_ => return Err(error),
}
}
let mut pid = 0;
if unsafe { GetNamedPipeClientProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
return Err(io::Error::last_os_error());
}
if pid != expected_pid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Unexpected packet pipe client",
));
}
Ok(())
}
pub fn into_handle(self) -> OwnedHandle {
self.0
}
}
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?fixture fixture-pi?>
<policy>
<!--fixture-comment-->
<portal-userauthcookie>fixture-user-cookie</portal-userauthcookie>
<portal-prelogonuserauthcookie><![CDATA[fixture-prelogon-cookie]]></portal-prelogonuserauthcookie>
<portal-csc-auth-cookie>fixture-csc-cookie</portal-csc-auth-cookie>
<username>fixture-username</username>
<saml-request>fixture-saml</saml-request>
<property name="password" value="fixture-property-password"/>
<cookie name="fixture-cookie-name"/>
<settings auth_token="fixture-attribute-token"/>
<download href="https://user:[email protected]/client?auth=fixture-query-token"/>
<hip-collection>
<hip-report-interval>3600</hip-report-interval>
<collect-hip-data>yes</collect-hip-data>
<custom-checks>
<mac-os><plist><entry name="com.paloaltonetworks.GlobalProtect.settings"><key><member>HipID</member></key></entry><entry name="com.1password.1password"><key><member>Version</member></key></entry></plist></mac-os>
<windows><registry-key><entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"><registry-value><member>Domain</member><member>NV Domain</member></registry-value></entry></registry-key></windows>
</custom-checks>
</hip-collection>
<domain>Corp.Example.test</domain>
</policy>
+13 -6
View File
@@ -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();
+123
View File
@@ -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<Vec<String>>);
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",
"<html><body>fixture-error-secret</body></html>",
)
.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 = "<jnlp><application-desc><argument>fixture-login-cookie</argument></application-desc></jnlp>";
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());
}
+87
View File
@@ -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<PipeClientIdentity> {
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();
}
+7 -1
View File
@@ -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
+12
View File
@@ -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(())
}
+53
View File
@@ -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<String> {
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), "");
}
}
}
+120
View File
@@ -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<String> {
linux_domain(|program, args| read(commands, program, args))
}
#[cfg(target_os = "freebsd")]
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
read(commands, "hostname", &["-d"])
}
#[cfg(target_os = "openbsd")]
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
read(commands, "hostname", &[]).map(|hostname| hostname_domain(&hostname))
}
#[cfg(unix)]
fn read(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<String> {
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<String>) -> io::Result<String> {
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(""), "");
}
}
+340 -44
View File
@@ -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<Option<String>> {
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<String> {
}
/// 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<String> {
/// 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<String> {
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, &params)),
("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<String> {
}
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
Ok(generate_report_details(input, control)?.xml)
}
pub fn generate_report_details(
input: &ReportInput,
control: &dyn CollectionControl,
) -> anyhow::Result<gpapi::hip::HipReport> {
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<String, String> {
@@ -338,6 +379,8 @@ struct HostInfo {
clamav: Option<ClamAvInfo>,
sentinel: Option<SentinelInfo>,
ufw: Option<UfwInfo>,
windows_categories: Option<String>,
windows_updates: Option<gpapi::hip::WindowsUpdateStatus>,
}
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<HostInfo> {
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<NetworkInterface> {
#[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<String> {
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<HostInfo> {
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<Option<UfwInfo>> {
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<String>) -> Option<String> {
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::<io::Error>().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<String, String> = 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<String, String> = 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<String, String> = 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<String, String> = 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<String, String> = 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("<domain>emulated-domain.internal</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"
);
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::<Vec<_>>();
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("<drive-name>C:\\</drive-name>"));
assert!(report.contains("<enc-state>encrypted</enc-state>"));
assert!(report.contains("<missing-patches />"));
}
#[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, &params)
.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,
+96
View File
@@ -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<WindowsReport> {
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<super::NetworkInterface> {
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<String> {
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::<DSROLE_PRIMARY_DOMAIN_INFO_BASIC>()).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<String> {
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<u16> = "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(), "");
}
}
+323
View File
@@ -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<AntiMalware>,
pub disk_backup: Vec<Backup>,
pub disk_encryption: Vec<Encryption>,
pub firewall: Vec<ProductState>,
pub patch_management: Vec<ProductState>,
pub missing_patches: Option<Vec<MissingPatch>>,
pub patches_checked_at: Option<u64>,
pub unavailable: Vec<String>,
}
#[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<bool>,
pub definition_version: Option<String>,
pub engine_version: Option<String>,
pub definition_date: Option<String>,
pub last_scan: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
pub(super) struct Backup {
pub product: Product,
pub last_backup: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
pub(super) struct Encryption {
pub product: Product,
pub drives: Vec<Drive>,
}
#[derive(Deserialize)]
pub(super) struct Drive {
pub name: String,
pub conversion_status: Option<u32>,
}
#[derive(Default, Deserialize)]
#[serde(default)]
pub(super) struct ProductState {
pub product: Product,
pub enabled: Option<bool>,
}
#[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<String>,
}
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<String> {
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<bool>) -> &'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<Item = Element>) -> 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!("<categories>{xml}</categories>").as_bytes()).unwrap();
assert_eq!(root.children.len(), 5);
assert!(xml.contains("Agent &amp; Endpoint"));
assert!(xml.contains("<enc-state>unencrypted</enc-state>"));
assert!(xml.contains("<last-full-scan-time>n/a</last-full-scan-time>"));
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("<missing-patches />"));
report.missing_patches = Some(vec![MissingPatch {
title: "Security update".into(),
kb: "123".into(),
..Default::default()
}]);
let xml = report.render().unwrap();
assert!(xml.contains("<kb-article-id>123</kb-article-id>"));
assert!(xml.contains("<is-installed>no</is-installed>"));
}
}
+7 -99
View File
@@ -2,7 +2,7 @@
<hip-report name="hip-report">
<md5-sum>{{ md5 }}</md5-sum>
<user-name>{{ user_name }}</user-name>
<domain>{{ host_info.domain }}.internal</domain>
<domain>{{ host_info.domain }}</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
@@ -14,7 +14,7 @@
<client-version>{{ client_version }}</client-version>
<os>{{ host_info.os_version }}</os>
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
<domain>{{ host_info.domain }}.internal</domain>
<domain>{{ host_info.domain }}</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<network-interface>
@@ -39,103 +39,11 @@
</network-interface>
</entry>
{% if host_info.os_vendor == "Microsoft" -%}
<entry name="antivirus">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="anti-spyware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\\</drive-name>
<enc-state>full</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% if let Some(categories) = &host_info.windows_categories -%}
{{ categories|safe }}
{% else -%}
{% include "windows_emulation.xml" %}
{% endif -%}
{% elif host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
@@ -0,0 +1,77 @@
<entry name="anti-malware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="3" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="3" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
+17 -1
View File
@@ -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"] }
+5
View File
@@ -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;
+249
View File
@@ -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<IpNet>,
pub mtu: Option<u32>,
pub includes: Vec<IpNet>,
pub excludes: Vec<IpNet>,
pub servers: Vec<IpAddr>,
pub domains: Vec<String>,
pub split_dns: Vec<String>,
}
fn invalid(message: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message.into())
}
impl Configuration {
pub fn parse(environment: &[(String, Option<String>)]) -> io::Result<Self> {
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::<u32>().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::<IpNet>().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::<io::Result<Vec<IpAddr>>>()?;
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<String> {
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<Vec<IpNet>> {
let count = values
.get(key)
.map(|value| {
value
.parse::<u32>()
.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<String>)> {
[
("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::<Vec<_>>(),
["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::<Vec<_>>(),
["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::<Vec<_>>(),
["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());
}
}
}
+18
View File
@@ -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' }
}
+178
View File
@@ -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<Snapshot>,
tag: Option<String>,
}
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<u16> {
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<Self> {
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<Self> {
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<String> = 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::<Vec<_>>()}),
)?;
}
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::<Vec<_>>());
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(())
}
+317
View File
@@ -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<String>,
}
pub(super) struct Installed {
routes: Vec<InstalledRoute>,
journal: Journal,
addresses: Vec<MIB_UNICASTIPADDRESS_ROW>,
interfaces: Vec<MIB_IPINTERFACE_ROW>,
}
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::<MIB_IPFORWARD_ROW2>::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<MIB_IPFORWARD_ROW2> {
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<Self> {
// 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::<io::Result<Vec<_>>>()?;
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<IpAddr> {
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<Self> {
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<MIB_IPFORWARD_ROW2> {
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(&current) })
}
pub(super) fn recover_route(saved: &Route) -> io::Result<()> {
remove_owned_route(&saved.row()?)
}
+64
View File
@@ -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<Connection>,
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<Self> {
recovery::Journal::begin(recovery_key)?;
Ok(Self {
connection: None,
recovery_key: recovery_key.into(),
})
}
pub fn configure(&mut self, reason: &str, environment: &[(String, Option<String>)]) -> 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()
}
+70
View File
@@ -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<Self> {
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<Option<Self>> {
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<Vec<(String, Route)>> {
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<String> {
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,
}
}
}
+454
View File
@@ -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<Self, Box<dyn std::error::Error>> {
let path =
PathBuf::from(std::env::var_os("GP_TEST_WINTUN_DLL").ok_or("GP_TEST_WINTUN_DLL is required")?).canonicalize()?;
let path: Vec<u16> = 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<u16> = format!("GP Connect Test {}", uuid::Uuid::new_v4().simple())
.encode_utf16()
.chain(Some(0))
.collect();
let kind: Vec<u16> = "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<u32>) -> Vec<String> {
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<String> {
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<dyn std::error::Error>> {
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<String>)> {
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<MIB_IPFORWARD_ROW2>,
}
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<dyn std::error::Error>> {
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(())
}
+4
View File
@@ -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"] }
+7
View File
@@ -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}"
+31
View File
@@ -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");
}
+10 -6
View File
@@ -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.
+61 -8
View File
@@ -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<unsafe extern "C" fn(*mut c_void, *const c_char, *const VpnOptionRaw) -> 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<String>);
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:\n<response><mtu>1400</mtu><akey-c2s><val>fixture-secret</val></akey-c2s><hs-key><bits>128</bits><val>fixture-handshake-key</val></hs-key></response>\n";
vpn_log(2, message.as_ptr());
vpn_log(
2,
c"GlobalProtect getconfig.esp response:\n<malformed>fixture-secret".as_ptr(),
);
let output = CAPTURE.0.lock().unwrap();
assert!(output.contains("<mtu>1400</mtu>"));
assert!(output.contains("[redacted]"));
assert!(output.contains("[XML omitted:"));
assert!(!output.contains("fixture-secret"));
assert!(!output.contains("fixture-handshake-key"));
}
}
+61 -46
View File
@@ -1,16 +1,15 @@
#include <openconnect.h>
#include "vpn.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>
#ifndef _WIN32
#include <unistd.h>
#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,
+19 -9
View File
@@ -1,3 +1,10 @@
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
typedef SOCKET vpn_command_handle;
#else
typedef int vpn_command_handle;
#endif
#include <openconnect.h>
#include <stdarg.h>
#include <stdio.h>
@@ -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__)
+63 -8
View File
@@ -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<i32>,
command_fd: Option<ffi::CommandHandle>,
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<Arc<NetworkConfigurationHandler>>,
interface: Option<CString>,
script_tun: bool,
#[cfg(unix)]
script_tun_launch: Option<ScriptTunLaunch>,
#[cfg(windows)]
script_tun_pipe: Option<OwnedHandle>,
certificate: Option<CString>,
sslkey: Option<CString>,
@@ -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<CString>,
@@ -381,7 +400,10 @@ pub struct VpnBuilder {
script_is_path: bool,
interface: Option<String>,
script_tun: bool,
#[cfg(unix)]
script_tun_launch: Option<ScriptTunLaunch>,
#[cfg(windows)]
script_tun_pipe: Option<OwnedHandle>,
user_agent: Option<String>,
os: Option<String>,
@@ -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<Vpn, VpnError> {
#[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) };
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more