diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index a29f37c..9b274b7 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -263,13 +263,10 @@ impl Cli { fn build_os_profile(&self) -> OsProfile { let mut builder = OsProfile::builder(ClientOs::from(self.os)); - if let Some(host_id) = self.host_id.as_deref() { - builder = builder.host_id_override(host_id); - } if let Some(client_version) = self.client_version.as_deref() { builder = builder.client_version(client_version); } - builder.build() + gpapi::os_profile::desktop::collect_profile(builder, self.host_id.as_deref()) } fn external_browser_requested(&self) -> bool { diff --git a/apps/gpclient/src/cli.rs b/apps/gpclient/src/cli.rs index 32a990c..1010798 100644 --- a/apps/gpclient/src/cli.rs +++ b/apps/gpclient/src/cli.rs @@ -243,7 +243,7 @@ impl Cli { CliCommand::Hip(args) => HipHandler::new(args).handle().await, CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"), CliCommand::DetectInternalHost { address, hostname } => { - let internal = gpapi::session::network::native::detect_in_helper(*address, hostname)?; + let internal = gpapi::session::desktop::network::native::detect_in_helper(*address, hostname)?; println!("{}", serde_json::to_string(&internal)?); Ok(()) } @@ -252,7 +252,7 @@ impl Cli { port, disable_ipv6, } => { - let addresses = gpapi::session::network::native::lookup_in_helper(host, *port, *disable_ipv6)?; + let addresses = gpapi::session::desktop::network::native::lookup_in_helper(host, *port, *disable_ipv6)?; println!("{}", serde_json::to_string(&addresses)?); Ok(()) } diff --git a/apps/gpclient/src/connect/args.rs b/apps/gpclient/src/connect/args.rs index 493f06b..0d5de04 100644 --- a/apps/gpclient/src/connect/args.rs +++ b/apps/gpclient/src/connect/args.rs @@ -203,10 +203,7 @@ pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option< if let Some(local_hostname) = args.local_hostname.as_deref() { builder = builder.computer_name_override(local_hostname.to_string()); } - if let Some(host_id) = host_id { - builder = builder.host_id_override(host_id); - } - builder.build() + gpapi::os_profile::desktop::collect_profile(builder, host_id) } pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option { @@ -489,14 +486,9 @@ mod tests { ("ipv4", GatewayIpPreference::Ipv4), ("ipv6", GatewayIpPreference::Ipv6), ] { - let cli = ConnectArgsTestCli::try_parse_from([ - "test", - "portal.example.com", - "--ip-preference", - value, - "--disable-ipv6", - ]) - .unwrap(); + let cli = + ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--ip-preference", value, "--disable-ipv6"]) + .unwrap(); assert_eq!(cli.args.ip_preference, expected); assert!(cli.args.disable_ipv6); } diff --git a/apps/gpclient/src/connect/gateway.rs b/apps/gpclient/src/connect/gateway.rs index 3560826..5c8652b 100644 --- a/apps/gpclient/src/connect/gateway.rs +++ b/apps/gpclient/src/connect/gateway.rs @@ -360,22 +360,26 @@ impl ConnectHandler<'_> { match login { GatewayLogin::Authenticated(authentication) => { let descriptor = Gateway::new(gateway.to_string(), gateway.to_string()); - client.register_session( - descriptor.clone(), - authentication.clone(), - &mut self.sessions.borrow_mut(), - ); + self + .sessions + .borrow_mut() + .register_login(descriptor.clone(), authentication.clone(), &client); self.check_cancelled()?; - if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only { - client - .bind_non_tunnel(self.args.disable_ipv6, None, &cancellation) - .await - .map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?; - client.update_registered_session(&descriptor, &authentication, &mut self.sessions.borrow_mut()); - } + let binding = if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only { + Some( + self + .sessions + .borrow_mut() + .bind_non_tunnel(&descriptor, &client, self.args.disable_ipv6, None, &cancellation) + .await + .map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?, + ) + } else { + None + }; return Ok(GatewayLoginSession { authentication, - extension_auth: SessionExtensionAuth::new(cred.clone(), client), + extension_auth: SessionExtensionAuth::new(cred.clone(), client).with_binding(binding), }); } GatewayLogin::Mfa(message, input_str) => { diff --git a/apps/gpclient/src/connect/internal.rs b/apps/gpclient/src/connect/internal.rs index b818e6d..8e0e9a0 100644 --- a/apps/gpclient/src/connect/internal.rs +++ b/apps/gpclient/src/connect/internal.rs @@ -2,14 +2,14 @@ use std::sync::Arc; use anyhow::{Context, bail, ensure}; use gpapi::{ + collection::CollectionControl, credential::AuthCookieCredential, gateway::{Gateway, GatewayLoginContext, GatewaySelection}, portal::PortalConfig, - process::collection::CollectionControl, session::{ MaintenanceState, SessionEndReason, SessionMode, - network::PhysicalNetwork, - non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions}, + desktop::network::PhysicalNetwork, + desktop::non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions}, }, }; use log::{info, warn}; diff --git a/apps/gpclient/src/connect/mod.rs b/apps/gpclient/src/connect/mod.rs index e78999e..ab625ba 100644 --- a/apps/gpclient/src/connect/mod.rs +++ b/apps/gpclient/src/connect/mod.rs @@ -19,8 +19,8 @@ use gpapi::{ gateway::GatewaySelection, gp_params::GpParams, os_profile::OsProfile, - portal::{PreloginOptions, prelogin, retrieve_config}, - session::GatewaySessions, + portal::{PreloginOptions, discovery::discover, prelogin}, + session::desktop::GatewaySessions, utils::request::RequestIdentityError, }; use inquire::{Password, PasswordDisplayMode, Select}; @@ -282,7 +282,7 @@ impl<'a> ConnectHandler<'a> { let cached = self.cached_portal_credential(portal); let cached_config = match cached { - Some(cred) => match retrieve_config(portal, &cred, &gp_params, &self.cancellation).await { + Some(cred) => match discover(portal, &cred, &gp_params, &self.cancellation).await { Ok(config) => Some((cred, config)), Err(error) => { self.check_cancelled()?; @@ -301,7 +301,7 @@ impl<'a> ConnectHandler<'a> { .await?; prelogin = replacement; self.check_cancelled()?; - let config = retrieve_config(portal, &cred, &gp_params, &self.cancellation).await?; + let config = discover(portal, &cred, &gp_params, &self.cancellation).await?; (cred, config) } }; diff --git a/apps/gpclient/src/dashboard/layout.rs b/apps/gpclient/src/dashboard/layout.rs index 290a044..0a4a95a 100644 --- a/apps/gpclient/src/dashboard/layout.rs +++ b/apps/gpclient/src/dashboard/layout.rs @@ -1,6 +1,8 @@ //! Dashboard presentation only; connection ownership and sampling stay outside this module. use crossterm::event::KeyCode; -use gpapi::session::tunnel::{TunnelList, TunnelPhase, TunnelState, TunnelStatisticsSnapshot, TunnelStatisticsState}; +use gpapi::session::desktop::tunnel::{ + TunnelList, TunnelPhase, TunnelState, TunnelStatisticsSnapshot, TunnelStatisticsState, +}; use ratatui::{ Frame, buffer::Buffer, @@ -338,7 +340,7 @@ pub(super) fn render_tunnel( #[cfg(test)] mod tests { - use gpapi::session::tunnel::{TunnelStatistics, TunnelStatisticsView, TunnelTransport}; + use gpapi::session::desktop::tunnel::{TunnelStatistics, TunnelStatisticsView, TunnelTransport}; use ratatui::{Terminal, backend::TestBackend}; use super::*; diff --git a/apps/gpclient/src/dashboard/screen.rs b/apps/gpclient/src/dashboard/screen.rs index 75f0533..7462829 100644 --- a/apps/gpclient/src/dashboard/screen.rs +++ b/apps/gpclient/src/dashboard/screen.rs @@ -15,7 +15,7 @@ use crossterm::{ execute, terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, }; -use gpapi::session::tunnel::TunnelPhase; +use gpapi::session::desktop::tunnel::TunnelPhase; use log::Level; use nix::unistd::{getpgrp, tcgetpgrp}; use ratatui::{ @@ -317,7 +317,7 @@ fn footer_text(logs: bool, ending: &str, scrollable: bool, width: u16) -> Paragr fn notice_for_status( notice: Option, phase: TunnelPhase, - transport: gpapi::session::tunnel::TunnelTransport, + transport: gpapi::session::desktop::tunnel::TunnelTransport, ) -> Notice { notice.unwrap_or_else(|| Notice { level: Level::Info, @@ -345,7 +345,7 @@ mod tests { #[test] fn status_transitions_cannot_overwrite_an_existing_warning() { - use gpapi::session::tunnel::TunnelTransport; + use gpapi::session::desktop::tunnel::TunnelTransport; let warning = Notice { level: Level::Warn, message: "ESP unavailable; using SSL".into(), diff --git a/apps/gpclient/src/hip.rs b/apps/gpclient/src/hip.rs index b733351..ac91c32 100644 --- a/apps/gpclient/src/hip.rs +++ b/apps/gpclient/src/hip.rs @@ -3,8 +3,8 @@ use std::time::Duration; use clap::Args; use gpapi::{ clap::args::Os, + collection::CollectionBudget, os_profile::{ClientOs, OsProfileBuilder}, - process::collection::CollectionBudget, }; use gphip::{ReportContext, ReportInput, generate_report_with_control}; @@ -51,11 +51,12 @@ impl<'a> HipHandler<'a> { if let Some(os_version) = self.args.os_version.as_deref() { builder = builder.os_version(os_version); } - if let Some(host_id) = self.args.host_id.as_deref() { - builder = builder.host_id_override(host_id); - } let input = ReportInput { - profile: builder.build_with_control(&budget)?, + profile: gpapi::os_profile::desktop::collect_profile_with_control( + builder, + self.args.host_id.as_deref(), + &budget, + )?, context: ReportContext::Connected { cookie: self.args.cookie.clone(), client_ip: self.args.client_ip.clone(), diff --git a/apps/gpclient/src/session.rs b/apps/gpclient/src/session.rs index 1e972c4..507bdd3 100644 --- a/apps/gpclient/src/session.rs +++ b/apps/gpclient/src/session.rs @@ -182,9 +182,10 @@ mod tests { #[test] fn builds_session_context_from_os_profile() { - let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Mac) - .client_version("6.3.1-12".to_string()) - .build(); + let profile = gpapi::os_profile::desktop::collect_profile( + OsProfile::builder(gpapi::os_profile::ClientOs::Mac).client_version("6.3.1-12".to_string()), + None, + ); let expected_user_agent = profile.user_agent().to_string(); let ctx = build_session_context(SessionContextInput { diff --git a/apps/gpgui-helper/src-tauri/src/updater.rs b/apps/gpgui-helper/src-tauri/src/updater.rs index 1fc4748..f2ed2ea 100644 --- a/apps/gpgui-helper/src-tauri/src/updater.rs +++ b/apps/gpgui-helper/src-tauri/src/updater.rs @@ -635,7 +635,7 @@ mod tests { vpnc_script: None, auth_executable: String::new(), host_info: HostInfo { - host_identity: HostIdentity::collect(), + host_identity: gpapi::os_profile::desktop::collect_identity(), }, }, }; diff --git a/apps/gpservice/src/hip_approval.rs b/apps/gpservice/src/hip_approval.rs index e61294d..77a6a52 100644 --- a/apps/gpservice/src/hip_approval.rs +++ b/apps/gpservice/src/hip_approval.rs @@ -87,14 +87,14 @@ pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result anyhow::Result { - let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)); + let budget = gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)); resolve_with_control(approval_id, desktop_uid, &budget) } pub fn resolve_with_control( approval_id: &str, desktop_uid: u32, - control: &dyn gpapi::process::collection::CollectionControl, + control: &dyn gpapi::collection::CollectionControl, ) -> anyhow::Result { control.check()?; ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner"); @@ -199,7 +199,7 @@ fn install_at( } fn resolve_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result { - let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)); + let budget = gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)); resolve_at_with_control(base, approval_id, desktop_uid, file_owner, &budget) } @@ -208,7 +208,7 @@ fn resolve_at_with_control( approval_id: &str, desktop_uid: u32, file_owner: u32, - control: &dyn gpapi::process::collection::CollectionControl, + control: &dyn gpapi::collection::CollectionControl, ) -> anyhow::Result { control.check()?; let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?; diff --git a/apps/gpservice/src/hip_preview.rs b/apps/gpservice/src/hip_preview.rs index 4adc942..3f98408 100644 --- a/apps/gpservice/src/hip_preview.rs +++ b/apps/gpservice/src/hip_preview.rs @@ -158,12 +158,12 @@ fn generate( request.host_id.as_ref().is_none_or(|id| id.len() <= 256), "Invalid HIP host ID" ); - let budget = gpapi::process::collection::CollectionBudget::new(PREVIEW_TIMEOUT); + let budget = gpapi::collection::CollectionBudget::new(PREVIEW_TIMEOUT); let check = || { if cancellation.is_cancelled() { return Err(io::Error::new(io::ErrorKind::Interrupted, "HIP preview cancelled")); } - gpapi::process::collection::CollectionControl::check(&budget) + gpapi::collection::CollectionControl::check(&budget) }; check()?; let profile = crate::hip_source::profile( @@ -227,7 +227,7 @@ mod tests { }, edited_report: None, desktop_uid: None, - identity: HostIdentity::from_parts( + identity: gpapi::os_profile::desktop::identity_from_parts( "device".into(), "host".into(), "serial".into(), diff --git a/apps/gpservice/src/hip_source.rs b/apps/gpservice/src/hip_source.rs index 76f2acd..a0afb9b 100644 --- a/apps/gpservice/src/hip_source.rs +++ b/apps/gpservice/src/hip_source.rs @@ -125,7 +125,7 @@ pub(crate) fn generate( profile: &OsProfile, edited: Option<&str>, request: &HipRequest, - control: &dyn gpapi::process::collection::CollectionControl, + control: &dyn gpapi::collection::CollectionControl, preview: bool, ) -> anyhow::Result { control.check()?; @@ -177,9 +177,9 @@ pub(crate) fn profile( os_version: Option, host_id: Option, hostname: Option, - control: &dyn gpapi::process::collection::CollectionControl, + control: &dyn gpapi::collection::CollectionControl, ) -> io::Result { - let identity = HostIdentity::from_parts( + let identity = gpapi::os_profile::desktop::identity_from_parts( hostname.unwrap_or_else(|| identity.computer().into()), host_id.unwrap_or_else(|| identity.host_id().into()), identity.serialno().into(), @@ -192,7 +192,7 @@ pub(crate) fn profile( if let Some(os_version) = os_version { builder = builder.os_version(os_version); } - builder.build_with_control(control) + gpapi::os_profile::desktop::collect_profile_with_control(builder, None, control) } fn generation_error(error: anyhow::Error) -> io::Error { @@ -209,7 +209,7 @@ mod tests { fn fixture_profile() -> OsProfile { profile( - &HostIdentity::from_parts( + &gpapi::os_profile::desktop::identity_from_parts( "device".into(), "host".into(), "serial".into(), @@ -220,7 +220,7 @@ mod tests { Some("negotiated-version".into()), None, None, - &gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)), + &gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)), ) .unwrap() } @@ -235,7 +235,7 @@ mod tests { #[test] fn profile_retains_negotiated_identity_and_os_version() { - let identity = HostIdentity::from_parts( + let identity = gpapi::os_profile::desktop::identity_from_parts( "original".into(), "original-id".into(), "serial".into(), @@ -248,7 +248,7 @@ mod tests { Some("negotiated-os".into()), Some("negotiated-host".into()), Some("negotiated-name".into()), - &gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)), + &gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)), ) .unwrap(); assert_eq!(profile.os_version(), "negotiated-os"); diff --git a/apps/gpservice/src/session_registry.rs b/apps/gpservice/src/session_registry.rs index 9543047..8169a64 100644 --- a/apps/gpservice/src/session_registry.rs +++ b/apps/gpservice/src/session_registry.rs @@ -833,7 +833,10 @@ mod tests { } let valid = gphip::generate_report(&gphip::ReportInput { - profile: gpapi::os_profile::OsProfile::builder(gpapi::os_profile::ClientOs::Linux).build(), + profile: gpapi::os_profile::desktop::collect_profile( + gpapi::os_profile::OsProfile::builder(gpapi::os_profile::ClientOs::Linux), + None, + ), context: gphip::ReportContext::Preview, }) .unwrap(); diff --git a/apps/gpservice/src/vpn_task.rs b/apps/gpservice/src/vpn_task.rs index 81b739a..04aa3b9 100644 --- a/apps/gpservice/src/vpn_task.rs +++ b/apps/gpservice/src/vpn_task.rs @@ -420,7 +420,7 @@ enum LifecycleEvent { MembersChanged { attempt: u64, members: Vec, - failures: Vec, + failures: Vec, }, Ended { attempt: u64, @@ -679,7 +679,7 @@ impl VpnTask { &self, attempt: u64, members: Vec, - failures: Vec, + failures: Vec, ) { let Some(active) = &self.active else { return; @@ -855,12 +855,12 @@ pub(crate) fn test_connect_request(info: ConnectInfo) -> ConnectRequest { } else { "fixture" }; - let binding = gpapi::session::network::GatewayBinding::new( + let binding = gpapi::session::desktop::network::GatewayBinding::new( endpoint, std::net::SocketAddr::new(source, 0), interface.into(), 1, - gpapi::session::ClientAddresses { + gpapi::session::desktop::ClientAddresses { ipv4: match source { std::net::IpAddr::V4(ip) => Some(ip), _ => None, @@ -873,8 +873,8 @@ pub(crate) fn test_connect_request(info: ConnectInfo) -> ConnectRequest { "0".repeat(64), ) .unwrap(); - let plan = gpapi::session::ConnectionPlan::new( - vec![gpapi::session::AuthenticatedGateway { + let plan = gpapi::session::desktop::ConnectionPlan::new( + vec![gpapi::session::desktop::AuthenticatedGateway { gateway: info.gateway().clone(), binding: Some(binding), authentication: gpapi::session::GatewayAuthentication::new("authcookie=token&user=user".into(), "tunnel".into()) diff --git a/apps/gpservice/src/vpn_task/non_tunnel.rs b/apps/gpservice/src/vpn_task/non_tunnel.rs index db2f58f..aa3bcb6 100644 --- a/apps/gpservice/src/vpn_task/non_tunnel.rs +++ b/apps/gpservice/src/vpn_task/non_tunnel.rs @@ -1,10 +1,10 @@ use std::{sync::Arc, time::Duration}; use anyhow::Context; -use gpapi::process::collection::CollectionControl; +use gpapi::collection::CollectionControl; use gpapi::session::{ GatewaySessionSummary, MaintenanceState, SessionEndReason, - non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions}, + desktop::non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions}, }; use log::warn; use tokio::sync::{mpsc, watch}; diff --git a/apps/gpservice/src/vpn_task/ownership_tests.rs b/apps/gpservice/src/vpn_task/ownership_tests.rs index 933872e..aa56fca 100644 --- a/apps/gpservice/src/vpn_task/ownership_tests.rs +++ b/apps/gpservice/src/vpn_task/ownership_tests.rs @@ -11,7 +11,10 @@ use gpapi::{ transport::ServiceResult, vpn_state::{ConnectInfo, VpnState}, }, - session::{ClientAddresses, GatewayAuthentication, GatewaySession, GatewaySessions, transport::GatewayTransport}, + session::{ + GatewayAuthentication, desktop::ClientAddresses, desktop::GatewaySession, desktop::GatewaySessions, + transport::GatewayTransport, + }, }; use openssl::{ asn1::Asn1Time, @@ -70,7 +73,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response( let mut member = fixture.plan().members()[0].clone(); member.authentication = GatewayAuthentication::new("authcookie=fixture&user=fixture".into(), "internal".into()).unwrap(); - let plan = gpapi::session::ConnectionPlan::new(vec![member], vec![], fixture.plan().policy()).unwrap(); + let plan = gpapi::session::desktop::ConnectionPlan::new(vec![member], vec![], fixture.plan().policy()).unwrap(); let request = gpapi::service::request::ConnectRequest::new(fixture.info().clone(), plan); let mut prepared = PreparedConnection::lifecycle_fixture(request); let mut params = GpParams::builder(prepared.resources.profile.clone()); diff --git a/apps/gpservice/src/vpn_task/preparation.rs b/apps/gpservice/src/vpn_task/preparation.rs index bceca1a..7865018 100644 --- a/apps/gpservice/src/vpn_task/preparation.rs +++ b/apps/gpservice/src/vpn_task/preparation.rs @@ -2,11 +2,13 @@ use std::{sync::Arc, time::Duration}; use anyhow::Context; use gpapi::{ + collection::{CollectionBudget, CollectionControl}, gp_params::GpParams, os_profile::OsProfile, - process::collection::{CollectionBudget, CollectionControl}, service::request::ConnectRequest, - session::{GatewaySession, GatewaySessions, network::PhysicalNetwork, transport::GatewayTransport}, + session::{ + desktop::GatewaySession, desktop::GatewaySessions, desktop::network::PhysicalNetwork, transport::GatewayTransport, + }, }; use tokio_util::sync::CancellationToken; @@ -149,14 +151,17 @@ impl PreparedConnection { /// Lifecycle-only fixtures own no issued server sessions. Protocol ownership /// checks use actual gateway transports rather than this actor-state fixture. pub(crate) fn lifecycle_fixture(request: ConnectRequest) -> Self { - let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux) - .host_identity(gpapi::os_profile::HostIdentity::from_parts( - "fixture".into(), - "fixture-host".into(), - "fixture-serial".into(), - "02:00:00:00:00:01".into(), - )) - .build(); + let profile = gpapi::os_profile::desktop::collect_profile( + OsProfile::builder(gpapi::os_profile::ClientOs::Linux).host_identity( + gpapi::os_profile::desktop::identity_from_parts( + "fixture".into(), + "fixture-host".into(), + "fixture-serial".into(), + "02:00:00:00:00:01".into(), + ), + ), + None, + ); Self { request, resources: Arc::new(ConnectionResources { @@ -217,14 +222,17 @@ mod tests { #[tokio::test] async fn ordinary_tunnel_preparation_needs_no_physical_binding_or_resolver() { let gateway = Gateway::new("fixture".into(), "does-not-resolve.invalid".into()); - let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux) - .host_identity(gpapi::os_profile::HostIdentity::from_parts( - "fixture".into(), - "fixture-host".into(), - "fixture-serial".into(), - "02:00:00:00:00:01".into(), - )) - .build(); + let profile = gpapi::os_profile::desktop::collect_profile( + OsProfile::builder(gpapi::os_profile::ClientOs::Linux).host_identity( + gpapi::os_profile::desktop::identity_from_parts( + "fixture".into(), + "fixture-host".into(), + "fixture-serial".into(), + "02:00:00:00:00:01".into(), + ), + ), + None, + ); let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![])) .with_os_profile(&profile) .with_disable_ipv6(true); diff --git a/apps/gpservice/src/vpn_task/runtime.rs b/apps/gpservice/src/vpn_task/runtime.rs index b29940b..9cd31c7 100644 --- a/apps/gpservice/src/vpn_task/runtime.rs +++ b/apps/gpservice/src/vpn_task/runtime.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; use anyhow::{Context, ensure}; use gpapi::{ - process::collection::{CollectionBudget, CollectionControl}, + collection::{CollectionBudget, CollectionControl}, service::request::ConnectRequest, session::SessionMode, }; @@ -77,8 +77,8 @@ pub(super) fn spawn( .all(|member| member.authentication.mode() == SessionMode::NonTunnel) { match super::non_tunnel::run(&mut input, source, guard, cancellation.clone(), events.clone()).await { - Ok(gpapi::session::non_tunnel::SessionExit::Disconnected) => {} - Ok(gpapi::session::non_tunnel::SessionExit::Failed(reason)) => { + Ok(gpapi::session::desktop::non_tunnel::SessionExit::Disconnected) => {} + Ok(gpapi::session::desktop::non_tunnel::SessionExit::Failed(reason)) => { let message = match reason { gpapi::session::SessionEndReason::InvalidCookie => { "Internal gateway authentication expired; connect again" @@ -312,7 +312,7 @@ async fn run_tunnel( prepared: &PreparedTunnel, approval: &crate::hip_source::HipApproval, lifecycle: &LifecycleHandle, - sessions: &mut gpapi::session::GatewaySessions, + sessions: &mut gpapi::session::desktop::GatewaySessions, cancellation: CancellationToken, events: mpsc::Sender, ) { diff --git a/apps/gpservice/src/vpn_task/script_tun.rs b/apps/gpservice/src/vpn_task/script_tun.rs index 42b14a9..3b8757e 100644 --- a/apps/gpservice/src/vpn_task/script_tun.rs +++ b/apps/gpservice/src/vpn_task/script_tun.rs @@ -60,7 +60,7 @@ pub(super) async fn run( events: mpsc::Sender, session_id: uuid::Uuid, registry: Arc, - sessions: &mut gpapi::session::GatewaySessions, + sessions: &mut gpapi::session::desktop::GatewaySessions, ) -> anyhow::Result<()> { let attempt = identity.attempt; let (native_tx, native) = mpsc::channel(64); @@ -219,12 +219,12 @@ async fn supervise( fn observed_network( config: openconnect::tunnel::Configuration, -) -> anyhow::Result { +) -> anyhow::Result { ensure!( !config.truncated && !config.dns.truncated && !config.search_domains.truncated, "VPN configuration is truncated" ); - Ok(gpapi::session::tunnel::NegotiatedNetwork { + Ok(gpapi::session::desktop::tunnel::NegotiatedNetwork { addresses: [config.ipv4, config.ipv6.or(config.netmask6)] .into_iter() .flatten() diff --git a/apps/gpservice/src/ws_connection.rs b/apps/gpservice/src/ws_connection.rs index f5f6769..e22051d 100644 --- a/apps/gpservice/src/ws_connection.rs +++ b/apps/gpservice/src/ws_connection.rs @@ -41,7 +41,7 @@ pub(crate) struct ConnectionControl { connection_id: Uuid, tx: mpsc::Sender, close_tx: watch::Sender>, - statistics: watch::Sender>, + statistics: watch::Sender>, statistics_enabled: Arc, committed: Arc, } @@ -102,13 +102,15 @@ impl ConnectionControl { self.statistics.send_replace(None); } - pub fn publish_statistics(&self, snapshot: gpapi::session::tunnel::TunnelStatisticsSnapshot) { + pub fn publish_statistics(&self, snapshot: gpapi::session::desktop::tunnel::TunnelStatisticsSnapshot) { if self.statistics_enabled() && !self.is_closed() { self.statistics.send_replace(Some(snapshot)); } } - pub fn subscribe_statistics(&self) -> watch::Receiver> { + pub fn subscribe_statistics( + &self, + ) -> watch::Receiver> { self.statistics.subscribe() } @@ -750,7 +752,7 @@ mod tests { .unwrap(); assert!(matches!(reply, ServerMessage::Reply { id, - result: ServiceResult::TunnelStatisticsSnapshot(gpapi::session::tunnel::TunnelStatisticsSnapshot::Unavailable { reason: gpapi::session::tunnel::TunnelUnavailableReason::NoTunnel }), + result: ServiceResult::TunnelStatisticsSnapshot(gpapi::session::desktop::tunnel::TunnelStatisticsSnapshot::Unavailable { reason: gpapi::session::desktop::tunnel::TunnelUnavailableReason::NoTunnel }), } if id == statistics_id)); let update_id = Uuid::new_v4(); diff --git a/apps/gpservice/src/ws_server.rs b/apps/gpservice/src/ws_server.rs index e346c96..8e15160 100644 --- a/apps/gpservice/src/ws_server.rs +++ b/apps/gpservice/src/ws_server.rs @@ -9,7 +9,7 @@ use gpapi::{ vpn_env::{HostInfo, VpnEnv}, vpn_state::VpnState, }, - session::tunnel::{TunnelStatisticsSnapshot, TunnelUnavailableReason}, + session::desktop::tunnel::{TunnelStatisticsSnapshot, TunnelUnavailableReason}, utils::lock_file::LockFile, }; use log::{info, warn}; @@ -397,7 +397,7 @@ fn build_snapshot(vpn_state: VpnState) -> VpnEnv { vpnc_script: find_vpnc_script(), auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(), host_info: HostInfo { - host_identity: HostIdentity::collect(), + host_identity: gpapi::os_profile::desktop::collect_identity(), }, } } @@ -488,7 +488,7 @@ mod tests { #[tokio::test] async fn statistics_demand_is_per_attachment_and_does_not_consume_revisions() { use gpapi::service::transport::ServiceResult; - use gpapi::session::tunnel::TunnelStatisticsState; + use gpapi::session::desktop::tunnel::TunnelStatisticsState; let (context, registry) = context(); let (a, a_session, a_generation, _a_rx) = attach(&context, ®istry).await; let (b, b_session, b_generation, _b_rx) = attach(&context, ®istry).await; @@ -564,7 +564,7 @@ mod tests { #[test] fn snapshot_budget_trims_observation_without_changing_existing_metadata() { - use gpapi::session::tunnel::{TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport}; + use gpapi::session::desktop::tunnel::{TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport}; let mut snapshot = build_snapshot(VpnState::Disconnected); let mut configuration = TunnelConfiguration::default(); configuration.included_routes.items = vec!["r".repeat(1000); 15]; diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 9190e4c..849ff48 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -6,11 +6,11 @@ edition.workspace = true license = "MIT" [dependencies] -nix = { version = "0.31", features = ["fs", "signal", "process"] } +nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true } common = { path = "../common" } anyhow.workspace = true base64.workspace = true -dns-lookup.workspace = true +dns-lookup = { workspace = true, optional = true } log.workspace = true reqwest.workspace = true native-tls = "0.2" @@ -21,25 +21,25 @@ xmltree.workspace = true serde.workspace = true specta = { workspace = true, features = ["derive", "uuid"] } urlencoding.workspace = true -tokio = { workspace = true, features = ["fs", "process", "signal", "macros"] } +tokio = { workspace = true, features = ["fs", "macros", "rt", "time"] } tokio-util.workspace = true serde_json.workspace = true -whoami.workspace = true +whoami = { workspace = true, optional = true } tempfile.workspace = true thiserror.workspace = true chacha20poly1305 = { version = "0.11", features = ["zeroize"] } url.workspace = true regex.workspace = true -uzers.workspace = true +uzers = { workspace = true, optional = true } serde_urlencoded.workspace = true md5.workspace = true sha2.workspace = true uuid = { workspace = true, features = ["v4", "v5", "serde"] } chrono.workspace = true humantime.workspace = true -netdev.workspace = true -socket2 = { version = "0.6", features = ["all"] } -os_info = { version = "3", default-features = false } +netdev = { workspace = true, optional = true } +socket2 = { version = "0.6", features = ["all"], optional = true } +os_info = { version = "3", default-features = false, optional = true } snow.workspace = true zeroize = { workspace = true, features = ["serde"] } getrandom = "0.4" @@ -52,7 +52,7 @@ clap-verbosity-flag = { workspace = true, optional = true } env_logger = { workspace = true, optional = true } log-reload = { version = "0.1", optional = true } -[target.'cfg(target_os="macos")'.dependencies] +[target.'cfg(any(target_os="macos", target_os="ios"))'.dependencies] security-framework = "3" oslog = { version = "0.2", default-features = false, optional = true } @@ -60,7 +60,7 @@ 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(not(target_os = "macos"))'.dependencies] +[target.'cfg(not(any(target_os = "macos", target_os = "ios")))'.dependencies] openssl.workspace = true version-compare = "0.2" @@ -70,7 +70,9 @@ proptest.workspace = true tokio = { workspace = true, features = ["test-util"] } [features] -tauri = ["dep:tauri", "dep:gtk"] -clap = ["dep:clap", "dep:clap-verbosity-flag"] +default = ["desktop"] +desktop = ["tokio/process", "tokio/signal", "dep:nix", "dep:uzers", "dep:netdev", "dep:os_info", "dep:whoami", "dep:dns-lookup", "dep:socket2"] +tauri = ["desktop", "dep:tauri", "dep:gtk"] +clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"] webview-auth = [] -logger = ["dep:env_logger", "dep:log-reload", "dep:oslog"] +logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"] diff --git a/crates/gpapi/src/auth.rs b/crates/gpapi/src/auth.rs index 794b3a2..5f84ca7 100644 --- a/crates/gpapi/src/auth.rs +++ b/crates/gpapi/src/auth.rs @@ -12,6 +12,16 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string}; pub type AuthDataParseResult = anyhow::Result; +/// Validates an explicit GlobalProtect SAML completion status. +/// A missing status means the page has not supplied an authentication result. +pub fn validate_saml_auth_status(status: Option<&str>) -> Result<(), AuthDataParseError> { + match status { + Some("1") => Ok(()), + Some(status) => Err(AuthDataParseError::AuthenticationFailed(status.to_owned())), + None => Err(AuthDataParseError::NotFound), + } +} + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))] pub enum AuthWindowTheme { @@ -121,21 +131,15 @@ impl SamlAuthData { } pub fn from_html(html: &str) -> AuthDataParseResult { - match parse_xml_tag(html, "saml-auth-status") { - Some(status) if status == "1" => { - let username = parse_xml_tag(html, "saml-username"); - let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie"); - let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie"); + validate_saml_auth_status(parse_xml_tag(html, "saml-auth-status").as_deref())?; + let username = parse_xml_tag(html, "saml-username"); + let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie"); + let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie"); - let auth_data = - SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?; - auth_data.log_summary("html"); - - Ok(auth_data) - } - Some(status) => Err(AuthDataParseError::AuthenticationFailed(status)), - None => Err(AuthDataParseError::NotFound), - } + let auth_data = + SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?; + auth_data.log_summary("html"); + Ok(auth_data) } pub fn from_gpcallback(data: &str) -> anyhow::Result { @@ -217,6 +221,26 @@ fn parse_xml_tag(html: &str, tag: &str) -> Option { mod tests { use super::*; + #[test] + fn saml_status_distinguishes_rejection_from_an_unfinished_page() { + assert!(validate_saml_auth_status(Some("1")).is_ok()); + assert!(matches!( + validate_saml_auth_status(None), + Err(AuthDataParseError::NotFound) + )); + for status in ["0", "2", "", "unknown"] { + assert!(matches!( + validate_saml_auth_status(Some(status)), + Err(AuthDataParseError::AuthenticationFailed(_)) + )); + let html = format!("{status}"); + assert!(matches!( + SamlAuthData::from_html(&html), + Err(AuthDataParseError::AuthenticationFailed(_)) + )); + } + } + #[test] fn auth_data_from_gpcallback_cas() { let auth_data = "globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string"; diff --git a/crates/gpapi/src/clap/args.rs b/crates/gpapi/src/clap/args.rs index 0c192cb..0a9b3f7 100644 --- a/crates/gpapi/src/clap/args.rs +++ b/crates/gpapi/src/clap/args.rs @@ -2,7 +2,7 @@ use clap::{ValueEnum, builder::PossibleValue}; use crate::{ gp_params::CscMode, - os_profile::{ClientOs, runtime_client_os}, + os_profile::{ClientOs, desktop::runtime_client_os}, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] @@ -31,6 +31,7 @@ impl Default for Os { ClientOs::Linux => Os::Linux, ClientOs::Windows => Os::Windows, ClientOs::Mac => Os::Mac, + ClientOs::Ios => unreachable!("The desktop CLI is not available on iOS"), } } } diff --git a/crates/gpapi/src/collection.rs b/crates/gpapi/src/collection.rs new file mode 100644 index 0000000..d92f6fb --- /dev/null +++ b/crates/gpapi/src/collection.rs @@ -0,0 +1,41 @@ +use std::{ + io, + time::{Duration, Instant}, +}; + +/// Invocation control borrowed by collection; interruption must never be treated +/// as an unavailable optional product. +pub trait CollectionControl { + fn check(&self) -> io::Result<()>; +} + +impl io::Result<()>> CollectionControl for F { + fn check(&self) -> io::Result<()> { + self() + } +} + +pub struct CollectionBudget { + deadline: Instant, +} + +impl CollectionBudget { + pub fn new(timeout: Duration) -> Self { + Self { + deadline: Instant::now() + timeout, + } + } +} + +impl CollectionControl for CollectionBudget { + fn check(&self) -> io::Result<()> { + if Instant::now() >= self.deadline { + Err(io::Error::new( + io::ErrorKind::TimedOut, + "Device information collection timed out", + )) + } else { + Ok(()) + } + } +} diff --git a/crates/gpapi/src/error.rs b/crates/gpapi/src/error.rs index 76164a2..e87323c 100644 --- a/crates/gpapi/src/error.rs +++ b/crates/gpapi/src/error.rs @@ -3,6 +3,11 @@ use thiserror::Error; mod server_tls; pub use server_tls::{ServerTlsError, ServerTlsErrorKind}; +/// An explicit server rejection, distinct from transport, TLS, and parsing failures. +#[derive(Error, Debug)] +#[error("Authentication was rejected")] +pub struct AuthenticationRejected; + #[derive(Error, Debug)] pub enum PortalError { #[error("Prelogin error: {0}")] diff --git a/crates/gpapi/src/error/server_tls.rs b/crates/gpapi/src/error/server_tls.rs index c221d43..514afdc 100644 --- a/crates/gpapi/src/error/server_tls.rs +++ b/crates/gpapi/src/error/server_tls.rs @@ -4,10 +4,10 @@ use serde::{Deserialize, Serialize}; use super::PortalError; -#[cfg(target_os = "macos")] -#[path = "server_tls/macos.rs"] +#[cfg(any(target_os = "macos", target_os = "ios"))] +#[path = "server_tls/apple.rs"] mod backend; -#[cfg(not(target_os = "macos"))] +#[cfg(not(any(target_os = "macos", target_os = "ios")))] #[path = "server_tls/openssl.rs"] mod backend; @@ -303,7 +303,7 @@ mod tests { portal::{PreloginOptions, prelogin}, }; let (address, worker) = server(true); - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let params = GpParams::builder(profile).build(); let error = prelogin(&address, ¶ms, PreloginOptions::default()) .await @@ -324,7 +324,7 @@ mod tests { portal::{PreloginOptions, prelogin}, }; let (address, worker) = server(true); - let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build()) + let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot())) .ignore_tls_errors(true) .build(); let result = prelogin(&address, ¶ms, PreloginOptions::default()).await; @@ -365,7 +365,7 @@ mod tests { assert_eq!(classify(&error), None); } - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "ios"))] #[test] fn wrapped_macos_io_status_retains_the_client_certificate_requirement() { let error = std::io::Error::other(std::io::Error::other(security_framework::base::Error::from(-9863))); @@ -376,6 +376,7 @@ mod tests { assert_eq!(classify(&std::io::Error::other("alert certificate required")), None); } + #[cfg(feature = "desktop")] #[test] fn rendering_recovery_retains_client_certificate_requirement() { use crate::process::rendering_recovery::{RecoveryState, RenderingCrash}; @@ -409,7 +410,7 @@ mod tests { os_profile::{ClientOs, OsProfile}, portal::{PreloginOptions, prelogin}, }; - let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build()) + let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot())) .ignore_tls_errors(true) .build(); let credential = crate::credential::PasswordCredential::new("alice", "password").into(); @@ -465,7 +466,8 @@ mod tests { SslVerifyMode::PEER }; let (address, worker) = server_with_client_auth(true, verify); - let mut builder = GpParams::builder(OsProfile::builder(ClientOs::Linux).build()); + let mut builder = + GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot())); builder.ignore_tls_errors(true); if required { builder diff --git a/crates/gpapi/src/error/server_tls/macos.rs b/crates/gpapi/src/error/server_tls/apple.rs similarity index 100% rename from crates/gpapi/src/error/server_tls/macos.rs rename to crates/gpapi/src/error/server_tls/apple.rs diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index 30d7909..77efcf1 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -17,11 +17,7 @@ use crate::{ gateway::GatewayLoginContext, gp_params::GpParams, params::gateway_login::{self, GatewayLoginInput}, - session::{ - GatewayAuthentication, - network::GatewayBinding, - transport::{bound_client, gateway_origin}, - }, + session::GatewayAuthentication, utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; @@ -41,29 +37,12 @@ pub struct GatewayLoginClient { origin: reqwest::Url, client: Client, params: GpParams, - binding: Option, login_endpoint: Option, login_url: Option, - maintenance_client: Option, + peer_certificate: Option>, } impl GatewayLoginClient { - pub fn register_session( - &self, - gateway: crate::gateway::Gateway, - authentication: GatewayAuthentication, - sessions: &mut crate::session::GatewaySessions, - ) { - sessions.register(crate::session::GatewaySession { - gateway, - transport: self.authenticated_transport(authentication), - addresses: self - .binding - .as_ref() - .map(|binding| binding.addresses()) - .unwrap_or_default(), - }); - } pub fn new(gateway: &str, params: GpParams) -> anyhow::Result { let origin = reqwest::Url::parse(&normalize_server(gateway)?)?; let client = Client::try_from(¶ms)?; @@ -71,78 +50,19 @@ impl GatewayLoginClient { origin, client, params, - binding: None, login_endpoint: None, login_url: None, - maintenance_client: None, + peer_certificate: None, }) } - /// Only called after an authenticated non-tunnel response and registration in - /// the caller's cleanup ledger. Tunnel login never inspects physical routing. - pub async fn bind_non_tunnel( - &mut self, - disable_ipv6: bool, - detection: Option<&crate::session::network::InternalHostDetection>, - cancellation: &tokio_util::sync::CancellationToken, - ) -> anyhow::Result<()> { - let origin = gateway_origin(self.origin.as_str())?; - let response_url = self - .login_url - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?; - anyhow::ensure!( - response_url.origin() == origin.origin(), - "Redirected non-tunnel authentication is unsupported" - ); - let endpoint = self - .login_endpoint - .ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?; - let network = crate::session::network::PhysicalNetwork::capture_controlled(cancellation).await?; - let binding = network - .bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation) - .await?; - network - .validate_internal_binding(&binding, detection, cancellation) - .await?; - let client = bound_client(origin.as_str(), &self.params, &binding)?; - self.binding = Some(binding); - self.maintenance_client = Some(client); - Ok(()) + pub(crate) fn login_endpoint(&self) -> Option { + self.login_endpoint + } + pub(crate) fn params(&self) -> &GpParams { + &self.params } - pub fn update_registered_session( - &self, - gateway: &crate::gateway::Gateway, - authentication: &GatewayAuthentication, - sessions: &mut crate::session::GatewaySessions, - ) { - sessions.update(crate::session::GatewaySession { - gateway: gateway.clone(), - transport: self.authenticated_transport(authentication.clone()), - addresses: self - .binding - .as_ref() - .map(|binding| binding.addresses()) - .unwrap_or_default(), - }); - } - - pub fn authenticated_transport( - &self, - authentication: GatewayAuthentication, - ) -> crate::session::transport::GatewayTransport { - crate::session::transport::GatewayTransport::from_authenticated_login( - self.maintenance_client.as_ref().unwrap_or(&self.client).clone(), - self.origin.clone(), - authentication, - self.params.os_profile().clone(), - ) - } - - pub fn binding(&self) -> Option<&GatewayBinding> { - self.binding.as_ref() - } pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> { self.params.client_identity() } @@ -153,6 +73,16 @@ impl GatewayLoginClient { &self.origin } + /// DER certificate from the TLS connection that returned the login response. + /// Callers must retain normal certificate verification when using it as a pin. + pub fn authenticated_url(&self) -> Option<&reqwest::Url> { + self.login_url.as_ref() + } + + pub fn peer_certificate(&self) -> Option<&[u8]> { + self.peer_certificate.as_deref() + } + pub fn respond_mfa(&mut self, input: &str, otp: &str) { self.params.set_input_str(input); self.params.set_otp(otp); @@ -190,6 +120,7 @@ impl GatewayLoginClient { // Once the full response is available, retain issued authentication or finish // cleanup-only logout before the caller observes cancellation. let response = parse_login_response(response, &self.client, &self.origin, &self.params).await?; + self.peer_certificate = response.peer_certificate; self.login_endpoint = response.endpoint; self.login_url = Some(response.url); Ok(response.login) @@ -206,12 +137,14 @@ impl GatewayLoginClient { } struct LoginResponse { + peer_certificate: Option>, login: GatewayLogin, endpoint: Option, url: reqwest::Url, } struct ReceivedLogin { + peer_certificate: Option>, body: String, endpoint: Option, url: reqwest::Url, @@ -260,17 +193,26 @@ async fn receive_gateway_login( } })?; + let peer_certificate = res + .extensions() + .get::() + .and_then(|info| info.peer_certificate()) + .map(<[u8]>::to_vec); let endpoint = res.remote_addr(); let url = res.url().clone(); let res = parse_gp_response(res).await.map_err(|err| { if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) { return anyhow::anyhow!(tls); } + if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { + return anyhow::anyhow!(crate::error::AuthenticationRejected); + } warn!("Gateway login response failed: {}", err.reason); anyhow::anyhow!("Gateway login error: {}", err.reason) })?; Ok(ReceivedLogin { + peer_certificate, body: res, endpoint, url, @@ -284,6 +226,7 @@ async fn parse_login_response( gp_params: &GpParams, ) -> anyhow::Result { let ReceivedLogin { + peer_certificate, body: res, endpoint, url, @@ -302,6 +245,7 @@ async fn parse_login_response( }; return Ok(LoginResponse { + peer_certificate, login: GatewayLogin::Mfa(message, input_str), endpoint, url, @@ -335,6 +279,7 @@ async fn parse_login_response( }; debug!("Gateway login succeeded, mode: {:?}", authentication.mode()); Ok(LoginResponse { + peer_certificate, login: GatewayLogin::Authenticated(authentication), endpoint, url, @@ -477,7 +422,11 @@ mod tests { } fn test_params() -> GpParams { - GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build() + GpParams::builder( + crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux) + .build(crate::os_profile::test_snapshot()), + ) + .build() } #[tokio::test] @@ -578,7 +527,6 @@ mod tests { assert!( matches!(client.login(&credential, None, &CancellationToken::new()).await.unwrap(), GatewayLogin::Authenticated(authentication) if authentication.mode() == crate::session::SessionMode::Tunnel) ); - assert!(client.binding().is_none()); assert!(matches!( client.extend_lifetime(&credential).await.unwrap(), GatewayLogin::Authenticated(_) @@ -619,7 +567,6 @@ mod tests { .unwrap(), GatewayLogin::Authenticated(_) )); - assert!(client.binding().is_none()); assert_eq!(server.await.unwrap().len(), 1); } @@ -642,7 +589,6 @@ mod tests { .unwrap(), GatewayLogin::Authenticated(_) )); - assert!(client.binding().is_none()); assert_eq!( server.await.unwrap()[0].0, "http://unresolvable.invalid/ssl-vpn/login.esp" @@ -660,8 +606,11 @@ mod tests { response(""), ]) .await; - let params = - GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build(); + let params = GpParams::builder( + crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux) + .build(crate::os_profile::test_snapshot()), + ) + .build(); let credential = crate::credential::PasswordCredential::new("alice", "password").into(); let mut client = GatewayLoginClient { client, diff --git a/crates/gpapi/src/gateway/mod.rs b/crates/gpapi/src/gateway/mod.rs index fe6c590..f80c430 100644 --- a/crates/gpapi/src/gateway/mod.rs +++ b/crates/gpapi/src/gateway/mod.rs @@ -1,9 +1,11 @@ mod login; mod parse_gateways; +#[cfg(feature = "desktop")] pub mod session; pub use login::*; pub(crate) use parse_gateways::*; +#[cfg(feature = "desktop")] pub use session::*; use serde::{Deserialize, Serialize}; @@ -24,7 +26,9 @@ pub struct Gateway { pub(crate) address: String, #[serde(default)] pub(crate) kind: GatewayKind, + #[serde(default)] pub(crate) priority: u32, + #[serde(default)] pub(crate) priority_rules: Vec, } diff --git a/crates/gpapi/src/gateway/session.rs b/crates/gpapi/src/gateway/session.rs index 72be078..21375b2 100644 --- a/crates/gpapi/src/gateway/session.rs +++ b/crates/gpapi/src/gateway/session.rs @@ -21,17 +21,26 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime"; pub struct SessionExtensionAuth { credential: Credential, client: GatewayLoginClient, + binding: Option, } impl SessionExtensionAuth { pub fn new(credential: Credential, client: GatewayLoginClient) -> Self { - Self { credential, client } + Self { + credential, + client, + binding: None, + } + } + pub fn with_binding(mut self, binding: Option) -> Self { + self.binding = binding; + self } pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> { self.client.client_identity() } - pub fn binding(&self) -> Option<&crate::session::network::GatewayBinding> { - self.client.binding() + pub fn binding(&self) -> Option<&crate::session::desktop::network::GatewayBinding> { + self.binding.as_ref() } } @@ -170,14 +179,14 @@ mod tests { fn build_session_args() -> SessionRequestArgs { let profile = OsProfile::builder(ClientOs::Mac) - .host_identity(HostIdentity::new( + .host_identity(HostIdentity::from_parts( "test-mac".to_string(), "host-id".to_string(), "serial".to_string(), "aa:bb:cc:dd:ee:ff".to_string(), )) .client_version("6.3.1-12".to_string()) - .build(); + .build(crate::os_profile::test_snapshot()); SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string()) .with_user_agent(profile.user_agent().to_string()) .with_disable_ipv6(true) diff --git a/crates/gpapi/src/gp_params.rs b/crates/gpapi/src/gp_params.rs index 843f7c5..cf4e53b 100644 --- a/crates/gpapi/src/gp_params.rs +++ b/crates/gpapi/src/gp_params.rs @@ -162,6 +162,7 @@ impl GpParams { pub(crate) fn client_builder(&self) -> anyhow::Result { let mut builder = Client::builder() + .tls_info(true) .danger_accept_invalid_certs(self.ignore_tls_errors) .user_agent(self.user_agent()); if let Some(identity) = &self.prepared_identity { @@ -322,10 +323,9 @@ mod tests { assert!(params.client_identity().is_none()); assert!(params.certificate.is_none()); } - use crate::os_profile::runtime_client_os; fn profile(client_os: ClientOs) -> OsProfile { - OsProfile::builder(client_os).build() + OsProfile::builder(client_os).build(crate::os_profile::test_snapshot()) } #[test] @@ -346,7 +346,7 @@ mod tests { fn builder_keeps_explicit_client_version() { let profile = OsProfile::builder(ClientOs::Mac) .client_version("6.2.9-1".to_string()) - .build(); + .build(crate::os_profile::test_snapshot()); let params = GpParams::builder(profile).build(); assert_eq!(params.client_version(), Some("6.2.9-1")); @@ -355,7 +355,7 @@ mod tests { #[test] fn builder_uses_os_profile_version_when_unspecified() { let params = GpParams::builder(profile(ClientOs::Mac)).build(); - let default_os_version = ClientOs::Mac.default_os_version(); + let default_os_version = crate::os_profile::defaults::os_version(ClientOs::Mac); assert_eq!(params.os_version(), Some(default_os_version.as_str())); } @@ -370,13 +370,18 @@ mod tests { #[test] fn delegates_identity_to_os_profile() { - let identity = HostIdentity::new( + let identity = HostIdentity::from_parts( "test-computer".to_string(), "test-host-id".to_string(), "test-serial".to_string(), "aa:bb:cc:dd:ee:ff".to_string(), ); - let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).host_identity(identity).build()).build(); + let params = GpParams::builder( + OsProfile::builder(ClientOs::Linux) + .host_identity(identity) + .build(crate::os_profile::test_snapshot()), + ) + .build(); assert!(!params.host_id().is_empty()); assert_eq!(params.host_identity().host_id(), "test-host-id"); @@ -388,7 +393,7 @@ mod tests { fn builder_accepts_pre_built_os_profile() { let profile = OsProfile::builder(ClientOs::Mac) .computer_name_override("MyMac") - .build(); + .build(crate::os_profile::test_snapshot()); let expected_os_version = profile.os_version().to_string(); let params = GpParams::builder(profile).build(); @@ -404,7 +409,7 @@ mod tests { fn delegates_computer_to_os_profile() { let profile = OsProfile::builder(ClientOs::Mac) .computer_name_override("MyComputer") - .build(); + .build(crate::os_profile::test_snapshot()); let params = GpParams::builder(profile).build(); assert_eq!(params.computer(), "MyComputer"); @@ -421,7 +426,7 @@ mod tests { #[test] fn delegates_host_identity_to_os_profile() { - let identity = HostIdentity::new( + let identity = HostIdentity::from_parts( "delegated-computer".to_string(), "delegated-host".to_string(), "delegated-serial".to_string(), @@ -430,7 +435,7 @@ mod tests { let params = GpParams::builder( OsProfile::builder(ClientOs::Linux) .host_identity(identity.clone()) - .build(), + .build(crate::os_profile::test_snapshot()), ) .build(); @@ -445,7 +450,7 @@ mod tests { #[test] fn builder_uses_provided_os_profile() { - let identity = HostIdentity::new( + let identity = HostIdentity::from_parts( "identity-host".to_string(), "host-7".to_string(), "serial-7".to_string(), @@ -455,13 +460,16 @@ mod tests { .computer_name_override("linux-host") .client_version("6.0.0-1".to_string()) .host_identity(identity) - .build(); + .build(crate::os_profile::test_snapshot()); let params = GpParams::builder(profile).build(); let profile = params.os_profile(); assert_eq!(profile.client_os(), ClientOs::Linux); assert_eq!(profile.computer(), "linux-host"); - assert_eq!(profile.os_version(), ClientOs::Linux.default_os_version()); + assert_eq!( + profile.os_version(), + crate::os_profile::defaults::os_version(ClientOs::Linux) + ); assert_eq!(profile.client_version(), "6.0.0-1"); assert_eq!(profile.host_identity().host_id(), "host-7"); assert_eq!(profile.host_identity().serialno(), "serial-7"); @@ -475,7 +483,7 @@ mod tests { #[test] fn try_from_gp_params_constructs_reqwest_client() { - let params = GpParams::builder(profile(runtime_client_os())).build(); + let params = GpParams::builder(profile(ClientOs::Mac)).build(); let client = Client::try_from(¶ms); assert!(client.is_ok(), "Client construction should succeed with default params"); @@ -483,7 +491,7 @@ mod tests { #[test] fn try_from_gp_params_with_ignore_tls_errors() { - let params = GpParams::builder(profile(runtime_client_os())) + let params = GpParams::builder(profile(ClientOs::Mac)) .ignore_tls_errors(true) .build(); let client = Client::try_from(¶ms); @@ -497,9 +505,9 @@ mod tests { #[test] fn try_from_gp_params_with_custom_user_agent() { let params = GpParams::builder( - OsProfile::builder(runtime_client_os()) + OsProfile::builder(ClientOs::Mac) .user_agent("custom-agent/1.0") - .build(), + .build(crate::os_profile::test_snapshot()), ) .build(); let client = Client::try_from(¶ms); @@ -511,7 +519,7 @@ mod tests { fn try_from_gp_params_with_invalid_certificate_returns_error() { // When a certificate path is provided but the file does not exist or is malformed, // Client construction should fail rather than silently succeed. - let params = GpParams::builder(profile(runtime_client_os())) + let params = GpParams::builder(profile(ClientOs::Mac)) .certificate("/nonexistent/path/to/cert.pem".to_string()) .build(); let client = Client::try_from(¶ms); @@ -526,7 +534,7 @@ mod tests { #[test] fn user_agent_delegates_to_os_profile_for_default_build() { - let params = GpParams::builder(profile(runtime_client_os())).build(); + let params = GpParams::builder(profile(ClientOs::Mac)).build(); assert_eq!( params.user_agent(), @@ -537,14 +545,21 @@ mod tests { #[test] fn builder_uses_profile_user_agent() { - let params = GpParams::builder(OsProfile::builder(runtime_client_os()).user_agent("custom").build()).build(); + let params = GpParams::builder( + OsProfile::builder(ClientOs::Mac) + .user_agent("custom") + .build(crate::os_profile::test_snapshot()), + ) + .build(); assert_eq!(params.user_agent(), "custom"); } #[test] fn builder_os_profile_without_user_agent_delegates_to_profile() { - let profile = OsProfile::builder(ClientOs::Mac).client_version("6.1.0").build(); + let profile = OsProfile::builder(ClientOs::Mac) + .client_version("6.1.0") + .build(crate::os_profile::test_snapshot()); let expected_ua = profile.user_agent().to_string(); let params = GpParams::builder(profile).build(); @@ -557,7 +572,7 @@ mod tests { let profile = OsProfile::builder(ClientOs::Mac) .client_version("6.1.0") .user_agent("override") - .build(); + .build(crate::os_profile::test_snapshot()); let params = GpParams::builder(profile).build(); assert_eq!(params.user_agent(), "override"); @@ -566,9 +581,9 @@ mod tests { #[test] fn try_from_gp_params_succeeds_with_delegated_user_agent() { let params = GpParams::builder( - OsProfile::builder(runtime_client_os()) + OsProfile::builder(ClientOs::Mac) .user_agent("delegated-agent/2.0") - .build(), + .build(crate::os_profile::test_snapshot()), ) .build(); let client = Client::try_from(¶ms); @@ -602,7 +617,7 @@ mod tests { client_os in arb_client_os(), user_agent_override in proptest::option::of("[a-zA-Z0-9/_.-]{1,30}"), ) { - let identity = HostIdentity::new( + let identity = HostIdentity::from_parts( "prop-computer".to_string(), "prop-host".to_string(), "prop-serial".to_string(), @@ -616,7 +631,7 @@ mod tests { if let Some(ref ua) = user_agent_override { profile_builder = profile_builder.user_agent(ua); } - let params = GpParams::builder(profile_builder.build()).build(); + let params = GpParams::builder(profile_builder.build(crate::os_profile::test_snapshot())).build(); prop_assert_eq!( params.user_agent(), @@ -634,7 +649,7 @@ mod tests { proptest! { #[test] fn builder_uses_profile_user_agent(ua in "[^\\s]{1,50}") { - let profile = OsProfile::builder(runtime_client_os()).user_agent(&ua).build(); + let profile = OsProfile::builder(ClientOs::Mac).user_agent(&ua).build(crate::os_profile::test_snapshot()); let params = GpParams::builder(profile).build(); prop_assert_eq!(params.user_agent(), ua.as_str()); diff --git a/crates/gpapi/src/lib.rs b/crates/gpapi/src/lib.rs index 89ec54a..fc303db 100644 --- a/crates/gpapi/src/lib.rs +++ b/crates/gpapi/src/lib.rs @@ -1,16 +1,22 @@ pub mod auth; +pub mod collection; +#[cfg(feature = "desktop")] pub mod cookie_store; pub mod credential; +#[cfg(feature = "desktop")] pub mod device_anchor; pub mod error; pub mod gateway; pub mod gp_params; +#[cfg(feature = "desktop")] pub mod hip; pub mod log_format; pub mod os_profile; pub mod params; pub mod portal; +#[cfg(feature = "desktop")] pub mod process; +#[cfg(feature = "desktop")] pub mod service; pub mod session; pub mod utils; @@ -21,4 +27,5 @@ pub mod logger; #[cfg(feature = "clap")] pub mod clap; +#[cfg(feature = "desktop")] pub mod script_tun; diff --git a/crates/gpapi/src/os_profile/client_os.rs b/crates/gpapi/src/os_profile/client_os.rs new file mode 100644 index 0000000..f2cecf2 --- /dev/null +++ b/crates/gpapi/src/os_profile/client_os.rs @@ -0,0 +1,163 @@ +use super::*; +// ─── ClientOs ──────────────────────────────────────────────────────────────── + +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type)] +pub enum ClientOs { + Linux, + Windows, + Mac, + Ios, +} + +impl From<&str> for ClientOs { + fn from(os: &str) -> Self { + match os { + "Linux" => ClientOs::Linux, + "Windows" => ClientOs::Windows, + "Mac" => ClientOs::Mac, + "iOS" => ClientOs::Ios, + _ => ClientOs::Linux, + } + } +} + +impl ClientOs { + pub fn as_str(&self) -> &'static str { + match self { + ClientOs::Linux => "Linux", + ClientOs::Windows => "Windows", + ClientOs::Mac => "Mac", + ClientOs::Ios => "iOS", + } + } + + pub fn to_openconnect_os(&self) -> &str { + match self { + ClientOs::Linux => "linux", + ClientOs::Windows => "win", + ClientOs::Mac => "mac-intel", + ClientOs::Ios => "apple-ios", + } + } + + pub fn default_client_version(&self) -> &'static str { + match self { + ClientOs::Linux => GP_CLIENT_VERSION_LINUX, + ClientOs::Windows => GP_CLIENT_VERSION_WINDOWS, + ClientOs::Mac => GP_CLIENT_VERSION_MACOS, + ClientOs::Ios => "6.3.5-28", + } + } + + pub(crate) fn default_csc_support(&self) -> bool { + match self { + ClientOs::Linux | ClientOs::Ios => false, + ClientOs::Mac | ClientOs::Windows => true, + } + } +} + +// ─── PreloginParamLocation ─────────────────────────────────────────────────── + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PreloginParamLocation { + Body, + Query, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PreloginBrowserMode { + Embedded, + External, +} + +// ─── WebviewUserAgent ─────────────────────────────────────────────────────── + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WebviewUserAgent { + Native { + prefix: String, + transform: WebviewUserAgentTransform, + }, + Projected { + prefix: String, + default_user_agent: String, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WebviewUserAgentTransform { + None, + LinuxPanGpuiVersion, +} + +// ─── Target behavior ──────────────────────────────────────────────────────── + +pub(super) mod target { + use super::*; + + pub(in crate::os_profile) fn prelogin_param_location(client_os: ClientOs) -> PreloginParamLocation { + match client_os { + ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => PreloginParamLocation::Body, + ClientOs::Windows => PreloginParamLocation::Query, + } + } + + pub(in crate::os_profile) fn saml_password(client_os: ClientOs) -> &'static str { + match client_os { + ClientOs::Linux => "SAMLPASS", + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => "", + } + } + + pub(in crate::os_profile) fn external_browser_os_value(client_os: ClientOs) -> &'static str { + match client_os { + ClientOs::Linux => "4", + ClientOs::Mac => "3", + ClientOs::Windows => "2", + ClientOs::Ios => "0", + } + } + + pub(in crate::os_profile) fn supports_macos_plist_csc(client_os: ClientOs) -> bool { + matches!(client_os, ClientOs::Mac) + } + + pub(in crate::os_profile) fn supports_linux_process_csc(client_os: ClientOs) -> bool { + matches!(client_os, ClientOs::Linux) + } + + pub(in crate::os_profile) fn supports_windows_registry_csc(client_os: ClientOs) -> bool { + matches!(client_os, ClientOs::Windows) + } + + pub(in crate::os_profile) fn kerberos_support_in_query(client_os: ClientOs) -> bool { + match client_os { + ClientOs::Linux | ClientOs::Ios => false, + ClientOs::Mac | ClientOs::Windows => true, + } + } + + pub(in crate::os_profile) fn os_vendor(client_os: ClientOs) -> &'static str { + match client_os { + ClientOs::Linux => "Linux", + ClientOs::Mac | ClientOs::Ios => "Apple", + ClientOs::Windows => "Microsoft", + } + } + + pub(in crate::os_profile) fn webview_user_agent_default(client_os: ClientOs) -> &'static str { + match client_os { + ClientOs::Linux => DEFAULT_LINUX_WEBVIEW_USER_AGENT, + ClientOs::Mac | ClientOs::Ios => DEFAULT_MACOS_WEBVIEW_USER_AGENT, + ClientOs::Windows => DEFAULT_WINDOWS_WEBVIEW_USER_AGENT, + } + } + + pub(in crate::os_profile) fn webview_user_agent_transform(client_os: ClientOs) -> WebviewUserAgentTransform { + match client_os { + ClientOs::Linux => WebviewUserAgentTransform::LinuxPanGpuiVersion, + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => WebviewUserAgentTransform::None, + } + } +} diff --git a/crates/gpapi/src/os_profile/defaults.rs b/crates/gpapi/src/os_profile/defaults.rs new file mode 100644 index 0000000..1b4f731 --- /dev/null +++ b/crates/gpapi/src/os_profile/defaults.rs @@ -0,0 +1,26 @@ +use super::ClientOs; +pub(super) const DEFAULT_MACOS_VERSION: &str = "13.4.0"; +pub(super) const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS"; +pub(super) const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro"; +pub(super) const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0"; +pub(super) const DEFAULT_LINUX_WEBVIEW_USER_AGENT: &str = + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1"; +pub(super) const DEFAULT_MACOS_WEBVIEW_USER_AGENT: &str = + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)"; +pub(super) const DEFAULT_WINDOWS_WEBVIEW_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0"; + +pub(crate) fn os_version(os: ClientOs) -> String { + match os { + ClientOs::Linux => format!("Linux {DEFAULT_LINUX_DISTRO}"), + ClientOs::Mac => format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"), + ClientOs::Windows => format!("Microsoft {DEFAULT_WINDOWS_DISTRO} , 64-bit"), + ClientOs::Ios => "Apple iOS".into(), + } +} +pub(crate) fn software_version(os: ClientOs) -> String { + match os { + ClientOs::Mac => DEFAULT_MACOS_VERSION.into(), + ClientOs::Windows => DEFAULT_WINDOWS_VERSION.into(), + ClientOs::Linux | ClientOs::Ios => String::new(), + } +} diff --git a/crates/gpapi/src/os_profile/desktop/macos.rs b/crates/gpapi/src/os_profile/desktop/macos.rs new file mode 100644 index 0000000..d87f221 --- /dev/null +++ b/crates/gpapi/src/os_profile/desktop/macos.rs @@ -0,0 +1,136 @@ +use super::{ + ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon, primary_mac_colon, + resolve_host_id, +}; +use crate::collection::CollectionControl; +use crate::process::collection::CollectorCommands; +use std::io; + +pub(super) struct RuntimeNativeHostIdentity; + +impl RuntimeNativeHostIdentity { + pub(super) fn runtime_os() -> ClientOs { + ClientOs::Mac + } + + pub(super) fn collect_with_control( + host_id_override: Option<&str>, + control: &dyn CollectionControl, + ) -> io::Result { + let commands = CollectorCommands::new(control); + let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon); + control.check()?; + let host_id = resolve_host_id(host_id_override, || { + native_mac + .clone() + .unwrap_or_else(|| derive_mac_address(&fallback_hostname())) + }); + let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname); + let serial_number = collect_macos_serial_number(&commands)?; + control.check()?; + Ok(NativeHostIdentitySnapshot { + host_id, + computer, + serial_number, + mac_address: native_mac, + }) + } +} + +fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result> { + Ok( + commands + .run(program, args)? + .filter(|output| output.status.success()) + .and_then(|output| String::from_utf8(output.stdout).ok()), + ) +} + +fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result> { + for name in ["ComputerName", "LocalHostName"] { + if let Some(value) = output(commands, "scutil", &["--get", name])? + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + { + return Ok(Some(value)); + } + } + Ok(None) +} + +fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result> { + if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? { + for name in ["Wi-Fi", "AirPort"] { + if let Some(mac) = parse_hardware_port_mac(&stdout, name) { + return Ok(Some(mac)); + } + } + } + macos_system_profiler_wifi_mac(commands) +} + +fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option { + let mut in_port = false; + for line in stdout.lines() { + if let Some(port) = line.strip_prefix("Hardware Port: ") { + in_port = port == name; + continue; + } + if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") { + return normalize_mac_colon(mac); + } + } + None +} + +fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result> { + let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else { + return Ok(None); + }; + let mut in_wifi = false; + for line in stdout.lines() { + let trimmed = line.trim(); + if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") { + in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:"; + continue; + } + if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") { + return Ok(normalize_mac_colon(mac)); + } + } + Ok(None) +} + +fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result> { + let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else { + return Ok(None); + }; + Ok(stdout.lines().find_map(|line| { + line + .split_once("IOPlatformSerialNumber") + .and_then(|(_, value)| value.split_once('=')) + .map(|(_, value)| value.trim().trim_matches('"').to_string()) + .filter(|value| !value.is_empty()) + })) +} + +impl RuntimeNativeHostIdentity { + pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> { + let commands = crate::process::collection::CollectorCommands::new(control); + let version = commands + .run("sw_vers", &["-productVersion"])? + .filter(|output| output.status.success()) + .and_then(|output| String::from_utf8(output.stdout).ok()) + .map(|version| version.trim().to_string()) + .filter(|version| !version.is_empty()) + .unwrap_or_else(|| super::DEFAULT_MACOS_VERSION.into()); + control.check()?; + Ok((format!("Apple Mac OS X {version}"), version)) + } + pub(super) fn fallback_versions() -> (String, String) { + ( + super::defaults::os_version(ClientOs::Mac), + super::defaults::software_version(ClientOs::Mac), + ) + } +} diff --git a/crates/gpapi/src/os_profile/desktop/mod.rs b/crates/gpapi/src/os_profile/desktop/mod.rs new file mode 100644 index 0000000..525cdb2 --- /dev/null +++ b/crates/gpapi/src/os_profile/desktop/mod.rs @@ -0,0 +1,242 @@ +use super::*; +use crate::collection::{CollectionBudget, CollectionControl}; +use std::{io, time::Duration}; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +mod unix; +#[cfg(target_os = "windows")] +mod windows; +#[cfg(target_os = "macos")] +use macos::RuntimeNativeHostIdentity; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +use unix::RuntimeNativeHostIdentity; +#[cfg(target_os = "windows")] +use windows::RuntimeNativeHostIdentity; +#[cfg(not(any( + target_os = "macos", + target_os = "windows", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" +)))] +compile_error!("gpapi desktop collection is unsupported on this target; disable the desktop feature"); +pub fn collect_identity() -> HostIdentity { + collect_with_host_id(None) +} + +pub fn collect_identity_with_control(control: &dyn CollectionControl) -> io::Result { + collect_with_host_id_and_control(None, control) +} + +pub(super) fn collect_with_host_id(host_id: Option<&str>) -> HostIdentity { + match collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) { + Ok(identity) => identity, + Err(error) => { + log::warn!("Host identity collection was unavailable: {error}"); + default_with_host_id(host_id) + } + } +} + +/// Best-effort convenience callers retain the established derived identity +/// when native collection is unavailable. Controlled HIP callers get errors. +pub(super) fn default_with_host_id(host_id: Option<&str>) -> HostIdentity { + identity_from_parts( + fallback_hostname(), + resolve_host_id(host_id, fallback_host_id), + String::new(), + primary_mac_colon().unwrap_or_default(), + ) +} + +pub(super) fn collect_with_host_id_and_control( + host_id: Option<&str>, + control: &dyn CollectionControl, +) -> io::Result { + control.check()?; + let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity(); + control.check()?; + Ok(identity) +} + +pub fn identity_from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> HostIdentity { + let host_id = non_empty(host_id, fallback_host_id()); + let computer = non_empty(computer, fallback_hostname()); + let serial_number = non_empty(serialno, derive_serial_number(&host_id)); + let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id)); + + HostIdentity::from_parts(computer, host_id, serial_number, mac_address) +} +pub(super) fn fallback_hostname() -> String { + whoami::hostname().unwrap_or_else(|_| String::from("localhost")) +} + +#[derive(Debug, Clone)] +struct NativeHostIdentitySnapshot { + host_id: String, + computer: String, + serial_number: Option, + mac_address: Option, +} + +impl NativeHostIdentitySnapshot { + fn into_host_identity(self) -> HostIdentity { + let host_id = non_empty(self.host_id, fallback_host_id()); + identity_from_parts( + self.computer, + host_id.clone(), + self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)), + self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)), + ) + } +} + +fn non_empty(value: String, fallback: String) -> String { + if value.trim().is_empty() { fallback } else { value } +} + +fn fallback_host_id() -> String { + derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"]) +} + +fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String { + host_id_override + .filter(|value| !value.trim().is_empty()) + .map(str::to_string) + .unwrap_or_else(collect) +} + +fn derive_serial_number(host_id: &str) -> String { + serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| { + let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]); + serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial") + }) +} + +fn derive_mac_address(host_id: &str) -> String { + let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]); + let compact = uuid.replace('-', ""); + let bytes = compact + .as_bytes() + .chunks(2) + .take(6) + .map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase()) + .collect::>(); + + bytes.join(":") +} + +fn normalize_mac_colon(value: &str) -> Option { + let compact = value + .trim() + .replace('-', ":") + .split(':') + .map(|part| part.to_lowercase()) + .collect::>(); + let valid = compact.len() == 6 + && compact + .iter() + .all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit())); + + valid.then(|| compact.join(":")) +} + +fn primary_mac_colon() -> Option { + netdev::get_default_interface() + .ok() + .and_then(|iface| iface.mac_addr.map(|mac| mac.address())) + .and_then(|mac| normalize_mac_colon(&mac)) +} + +fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String { + use uuid::Uuid; + + let namespace = Uuid::NAMESPACE_DNS; + let name = format!("{}-{}", seed, parts.join("-")); + + Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string() +} + +pub fn runtime_client_os() -> ClientOs { + RuntimeNativeHostIdentity::runtime_os() +} + +/// Strict native collection, followed by deterministic profile projection. +pub fn collect_profile_with_control( + builder: OsProfileBuilder, + host_id_override: Option<&str>, + control: &dyn CollectionControl, +) -> io::Result { + control.check()?; + let identity = match &builder.host_identity { + Some(identity) => identity.clone(), + None => collect_with_host_id_and_control(host_id_override, control)?, + }; + 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 { + RuntimeNativeHostIdentity::versions(control)? + } else { + (defaults::os_version(runtime_os), defaults::software_version(runtime_os)) + }; + control.check()?; + Ok(builder.build(HostSnapshot { + runtime_os, + identity, + os_version, + software_version, + })) +} + +/// Existing desktop best-effort policy; strict HIP callers use the controlled entry point. +pub fn collect_profile(builder: OsProfileBuilder, host_id_override: Option<&str>) -> OsProfile { + match collect_profile_with_control( + builder.clone(), + host_id_override, + &CollectionBudget::new(Duration::from_secs(60)), + ) { + Ok(profile) => profile, + Err(error) => { + log::warn!("OS profile collection was unavailable: {error}"); + let identity = builder + .host_identity + .clone() + .unwrap_or_else(|| default_with_host_id(host_id_override)); + let runtime_os = runtime_client_os(); + let (os_version, software_version) = RuntimeNativeHostIdentity::fallback_versions(); + builder.build(HostSnapshot { + runtime_os, + identity, + os_version, + software_version, + }) + } + } +} +pub fn default_computer_name(client_os: &ClientOs) -> String { + projection::project(runtime_client_os(), *client_os, &collect_identity(), None) + .computer() + .into() +} +pub fn default_os_version(client_os: &ClientOs) -> String { + if *client_os == runtime_client_os() { + RuntimeNativeHostIdentity::versions(&CollectionBudget::new(Duration::from_secs(60))) + .unwrap_or_else(|_| RuntimeNativeHostIdentity::fallback_versions()) + .0 + } else { + defaults::os_version(*client_os) + } +} +pub fn default_software_version(client_os: &ClientOs) -> String { + if *client_os == runtime_client_os() { + RuntimeNativeHostIdentity::versions(&CollectionBudget::new(Duration::from_secs(60))) + .unwrap_or_else(|_| RuntimeNativeHostIdentity::fallback_versions()) + .1 + } else { + defaults::software_version(*client_os) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/gpapi/src/os_profile/desktop/tests.rs b/crates/gpapi/src/os_profile/desktop/tests.rs new file mode 100644 index 0000000..85bce65 --- /dev/null +++ b/crates/gpapi/src/os_profile/desktop/tests.rs @@ -0,0 +1,180 @@ +use super::*; + +#[test] +fn controlled_identity_collection_propagates_cancellation() { + let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); + let error = collect_identity_with_control(&control).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::Interrupted); + let error = collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::Interrupted); +} + +#[test] +fn collect_produces_non_empty_identity() { + let identity = collect_identity(); + + assert!(!identity.computer().is_empty()); + assert!(!identity.host_id().is_empty()); + assert!(!identity.serialno().is_empty()); + assert!(!identity.mac_addr().is_empty()); + assert_mac(identity.mac_addr(), ':'); +} + +#[test] +fn collect_with_host_id_uses_provided_host_id() { + let identity = collect_with_host_id(Some("provided-host-id")); + + assert_eq!(identity.host_id(), "provided-host-id"); + assert!(!identity.computer().is_empty()); + assert!(!identity.serialno().is_empty()); + assert!(!identity.mac_addr().is_empty()); +} + +#[test] +fn collect_with_blank_host_id_falls_back_to_runtime_host_id() { + let identity = collect_with_host_id(Some(" ")); + + assert!(!identity.host_id().is_empty()); + assert_ne!(identity.host_id(), " "); +} + +#[test] +fn resolve_host_id_does_not_collect_when_override_is_provided() { + let host_id = resolve_host_id(Some("provided-host-id"), || { + panic!("runtime host id should not be collected") + }); + + assert_eq!(host_id, "provided-host-id"); +} + +#[test] +fn host_identity_normalizes_mac_to_lowercase_colon_format() { + let identity = identity_from_parts( + "computer".to_string(), + "host-id".to_string(), + "serial-number".to_string(), + "AA-BB-CC-DD-EE-FF".to_string(), + ); + + assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff"); +} + +#[test] +fn native_snapshot_uses_host_id_as_derivation_seed() { + let native = + RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap(); + + assert!(!native.host_id.is_empty()); +} + +#[test] +fn serialization_keeps_globalprotect_field_names() { + let identity = identity_from_parts( + "computer".to_string(), + "host-id".to_string(), + "serial-number".to_string(), + "aa:bb:cc:dd:ee:ff".to_string(), + ); + let value = serde_json::to_value(identity).unwrap(); + + assert_eq!(value["hostId"], "host-id"); + assert_eq!(value["computer"], "computer"); + assert!(value.get("osVersion").is_none()); + assert!(value.get("softwareVersion").is_none()); + assert_eq!(value["serialno"], "serial-number"); + assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff"); +} + +#[test] +fn native_identity_falls_back_to_derived_values_when_missing() { + let native = NativeHostIdentitySnapshot { + host_id: "native-host-id".to_string(), + computer: "native-computer".to_string(), + serial_number: None, + mac_address: None, + }; + + let identity = native.into_host_identity(); + + assert_eq!(identity.computer(), "native-computer"); + assert_eq!(identity.host_id(), "native-host-id"); + assert!(identity.serialno().starts_with("VMware-")); + assert_mac(identity.mac_addr(), ':'); +} + +#[test] +fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() { + let identity = identity_from_parts( + "computer".to_string(), + "5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(), + String::new(), + "aa:bb:cc:dd:ee:ff".to_string(), + ); + + assert_eq!( + identity.serialno(), + "VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef" + ); +} + +#[test] +fn empty_host_id_falls_back_to_non_empty_value() { + let identity = identity_from_parts(String::new(), String::new(), String::new(), String::new()); + + assert!(!identity.host_id().is_empty()); + assert!(!identity.computer().is_empty()); + assert!(!identity.serialno().is_empty()); + assert!(!identity.mac_addr().is_empty()); +} + +fn assert_mac(value: &str, separator: char) { + let parts: Vec<&str> = value.split(separator).collect(); + assert_eq!(parts.len(), 6, "MAC should have 6 octets"); + for part in &parts { + assert_eq!(part.len(), 2); + assert!(part.chars().all(|c| c.is_ascii_hexdigit())); + } +} + +#[test] +fn builder_delegates_default_identity_to_host_identity() { + let expected = collect_identity(); + let profile = collect_profile( + OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()), + None, + ); + + assert_eq!(profile.host_identity(), &expected); +} + +#[test] +fn builder_host_id_override_uses_supplied_runtime_identity_seed() { + let profile = collect_profile(OsProfileBuilder::new(runtime_client_os()), Some("provided-host-id")); + + assert_eq!(profile.host_identity().host_id(), "provided-host-id"); +} + +#[test] +fn builder_host_id_override_is_used_as_projected_identity_seed() { + let client_os = match runtime_client_os() { + ClientOs::Linux => ClientOs::Mac, + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => ClientOs::Linux, + }; + + let first = collect_profile(OsProfileBuilder::new(client_os), Some("provided-host-id")); + let second = collect_profile(OsProfileBuilder::new(client_os), Some("provided-host-id")); + + assert_eq!(first.host_identity().host_id(), "provided-host-id"); + assert_eq!(first.host_id(), second.host_id()); + assert_ne!(first.host_id(), "provided-host-id"); +} + +#[test] +fn controlled_profile_collection_propagates_cancellation_and_deadline() { + let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); + let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Mac), None, &cancelled).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::Interrupted); + let expired = CollectionBudget::new(Duration::ZERO); + let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::TimedOut); +} diff --git a/crates/gpapi/src/os_profile/desktop/unix.rs b/crates/gpapi/src/os_profile/desktop/unix.rs new file mode 100644 index 0000000..b6665c1 --- /dev/null +++ b/crates/gpapi/src/os_profile/desktop/unix.rs @@ -0,0 +1,136 @@ +use super::{ + ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id, + serial_number, +}; +use log::debug; + +pub(super) struct RuntimeNativeHostIdentity; + +impl RuntimeNativeHostIdentity { + pub(super) fn runtime_os() -> ClientOs { + ClientOs::Linux + } + + pub(super) fn collect_with_control( + host_id_override: Option<&str>, + control: &dyn super::CollectionControl, + ) -> super::io::Result { + control.check()?; + let identity = Self::collect(host_id_override); + control.check()?; + Ok(identity) + } + + fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot { + if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) { + debug!("Runtime host-id source: explicit override ({})", host_id); + } + let host_id = resolve_host_id(host_id_override, Self::host_id); + NativeHostIdentitySnapshot { + host_id, + computer: fallback_hostname(), + serial_number: collect_linux_serial_number(), + mac_address: primary_mac_colon(), + } + } + + fn host_id() -> String { + if let Some(host_id) = collect_linux_product_uuid() { + debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id); + return host_id; + } + + let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| { + let hostname = fallback_hostname(); + ("hostname", hostname) + }); + let host_id = derive_uuid_from_seed(&source, &[]); + debug!("Runtime host-id source: derived from {} ({})", source_name, host_id); + host_id + } +} + +fn collect_linux_product_uuid() -> Option { + read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value)) +} + +fn normalize_uuid(value: &str) -> Option { + uuid::Uuid::parse_str(value.trim()) + .ok() + .map(|uuid| uuid.hyphenated().to_string()) +} + +fn collect_linux_fallback_seed() -> Option<(&'static str, String)> { + ["/etc/machine-id", "/var/lib/dbus/machine-id"] + .iter() + .find_map(|path| read_linux_identity_file(path).map(|value| (*path, value))) +} + +fn read_linux_identity_file(path: &str) -> Option { + std::fs::read_to_string(path) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| is_usable_linux_identity_value(value)) +} + +fn is_usable_linux_identity_value(value: &str) -> bool { + !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M." +} + +fn collect_linux_serial_number() -> Option { + resolve_linux_serial_number( + read_linux_identity_file("/sys/class/dmi/id/product_serial"), + collect_linux_product_uuid, + ) +} + +fn resolve_linux_serial_number( + product_serial: Option, + product_uuid: impl FnOnce() -> Option, +) -> Option { + product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalize_uuid_preserves_real_uuid_identity() { + assert_eq!( + normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"), + Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string()) + ); + assert_eq!(normalize_uuid("not-a-uuid"), None); + } + + #[test] + fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() { + let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string()); + + assert_eq!( + resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()), + Some("product-serial".to_string()) + ); + assert_eq!( + resolve_linux_serial_number(None, || uuid), + Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string()) + ); + } +} + +impl RuntimeNativeHostIdentity { + pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> { + control.check()?; + Ok(Self::fallback_versions()) + } + pub(super) fn fallback_versions() -> (String, String) { + ( + format!( + "Linux {}", + whoami::distro().unwrap_or_else(|_| super::DEFAULT_LINUX_DISTRO.into()) + ), + String::new(), + ) + } +} diff --git a/crates/gpapi/src/os_profile/desktop/windows.rs b/crates/gpapi/src/os_profile/desktop/windows.rs new file mode 100644 index 0000000..3ddb825 --- /dev/null +++ b/crates/gpapi/src/os_profile/desktop/windows.rs @@ -0,0 +1,107 @@ +use std::process::Command; + +use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id}; + +pub(super) struct RuntimeNativeHostIdentity; + +impl RuntimeNativeHostIdentity { + pub(super) fn runtime_os() -> ClientOs { + ClientOs::Windows + } + + pub(super) fn collect_with_control( + host_id_override: Option<&str>, + control: &dyn super::CollectionControl, + ) -> super::io::Result { + control.check()?; + let identity = Self::collect(host_id_override); + control.check()?; + Ok(identity) + } + + fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot { + let host_id = resolve_host_id(host_id_override, Self::host_id); + NativeHostIdentitySnapshot { + host_id, + computer: fallback_hostname(), + serial_number: collect_windows_serial_number(), + mac_address: primary_mac_colon(), + } + } + + fn host_id() -> String { + windows_machine_seed().unwrap_or_else(fallback_hostname) + } +} + +fn collect_windows_serial_number() -> Option { + let output = Command::new("wmic") + .args(["bios", "get", "serialnumber"]) + .output() + .ok()?; + let stdout = String::from_utf8(output.stdout).ok()?; + + stdout + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && *line != "SerialNumber") + .map(str::to_string) + .next() +} + +fn windows_machine_seed() -> Option { + collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid) +} + +fn collect_windows_csproduct_uuid() -> Option { + let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?; + let stdout = String::from_utf8(output.stdout).ok()?; + + stdout + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && *line != "UUID") + .map(str::to_string) + .next() +} + +fn collect_windows_machine_guid() -> Option { + let output = Command::new("reg") + .args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let stdout = String::from_utf8(output.stdout).ok()?; + + stdout.lines().find_map(|line| { + let mut parts = line.split_whitespace(); + if parts.next()? != "MachineGuid" { + return None; + } + + parts.last().map(str::to_string) + }) +} + +impl RuntimeNativeHostIdentity { + pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> { + control.check()?; + Ok(Self::fallback_versions()) + } + pub(super) fn fallback_versions() -> (String, String) { + { + let info = os_info::get(); + let edition = info + .edition() + .map(str::to_owned) + .unwrap_or_else(|| whoami::distro().unwrap_or_else(|_| super::DEFAULT_WINDOWS_DISTRO.into())); + let version = match info.version() { + os_info::Version::Unknown => super::DEFAULT_WINDOWS_VERSION.into(), + version => format!("{}.0", version), + }; + (format!("Microsoft {} , 64-bit", edition), version) + } + } +} diff --git a/crates/gpapi/src/os_profile/host_identity.rs b/crates/gpapi/src/os_profile/host_identity.rs deleted file mode 100644 index 5bdd1e3..0000000 --- a/crates/gpapi/src/os_profile/host_identity.rs +++ /dev/null @@ -1,670 +0,0 @@ -use std::{io, time::Duration}; - -use crate::process::collection::{CollectionBudget, CollectionControl}; -use serde::{Deserialize, Serialize}; -use specta::Type; - -use super::{ClientOs, serial_number}; -use platform::RuntimeNativeHostIdentity; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct HostIdentity { - computer: String, - host_id: String, - #[serde(rename = "serialno")] - serial_number: String, - #[serde(rename = "macAddr")] - mac_address: String, -} - -impl HostIdentity { - pub fn collect() -> Self { - Self::collect_with_host_id(None) - } - - pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result { - Self::collect_with_host_id_and_control(None, control) - } - - pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self { - match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) { - Ok(identity) => identity, - Err(error) => { - log::warn!("Host identity collection was unavailable: {error}"); - Self::default_with_host_id(host_id) - } - } - } - - /// Best-effort convenience callers retain the established derived identity - /// when native collection is unavailable. Controlled HIP callers get errors. - pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self { - Self::from_parts( - fallback_hostname(), - resolve_host_id(host_id, fallback_host_id), - String::new(), - primary_mac_colon().unwrap_or_default(), - ) - } - - pub(crate) fn collect_with_host_id_and_control( - host_id: Option<&str>, - control: &dyn CollectionControl, - ) -> io::Result { - control.check()?; - let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity(); - control.check()?; - Ok(identity) - } - - #[cfg(test)] - pub(crate) fn new(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self { - Self::from_parts(computer, host_id, serialno, mac_addr) - } - - /// Construct a host identity from an already collected or negotiated snapshot. - pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self { - let host_id = non_empty(host_id, fallback_host_id()); - let computer = non_empty(computer, fallback_hostname()); - let serial_number = non_empty(serialno, derive_serial_number(&host_id)); - let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id)); - - Self { - computer, - host_id, - serial_number, - mac_address, - } - } - - pub fn computer(&self) -> &str { - &self.computer - } - - pub fn host_id(&self) -> &str { - &self.host_id - } - - pub fn serialno(&self) -> &str { - &self.serial_number - } - - pub fn mac_addr(&self) -> &str { - &self.mac_address - } - - pub fn with_computer(mut self, computer: String) -> Self { - if !computer.trim().is_empty() { - self.computer = computer; - } - self - } - - pub(crate) fn runtime_os() -> ClientOs { - RuntimeNativeHostIdentity::runtime_os() - } -} - -pub(super) fn fallback_hostname() -> String { - whoami::hostname().unwrap_or_else(|_| String::from("localhost")) -} - -#[derive(Debug, Clone)] -struct NativeHostIdentitySnapshot { - host_id: String, - computer: String, - serial_number: Option, - mac_address: Option, -} - -impl NativeHostIdentitySnapshot { - fn into_host_identity(self) -> HostIdentity { - let host_id = non_empty(self.host_id, fallback_host_id()); - HostIdentity::from_parts( - self.computer, - host_id.clone(), - self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)), - self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)), - ) - } -} - -fn non_empty(value: String, fallback: String) -> String { - if value.trim().is_empty() { fallback } else { value } -} - -fn fallback_host_id() -> String { - derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"]) -} - -fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String { - host_id_override - .filter(|value| !value.trim().is_empty()) - .map(str::to_string) - .unwrap_or_else(collect) -} - -fn derive_serial_number(host_id: &str) -> String { - serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| { - let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]); - serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial") - }) -} - -fn derive_mac_address(host_id: &str) -> String { - let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]); - let compact = uuid.replace('-', ""); - let bytes = compact - .as_bytes() - .chunks(2) - .take(6) - .map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase()) - .collect::>(); - - bytes.join(":") -} - -fn normalize_mac_colon(value: &str) -> Option { - let compact = value - .trim() - .replace('-', ":") - .split(':') - .map(|part| part.to_lowercase()) - .collect::>(); - let valid = compact.len() == 6 - && compact - .iter() - .all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit())); - - valid.then(|| compact.join(":")) -} - -fn primary_mac_colon() -> Option { - netdev::get_default_interface() - .ok() - .and_then(|iface| iface.mac_addr.map(|mac| mac.address())) - .and_then(|mac| normalize_mac_colon(&mac)) -} - -fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String { - use uuid::Uuid; - - let namespace = Uuid::NAMESPACE_DNS; - let name = format!("{}-{}", seed, parts.join("-")); - - Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string() -} - -#[cfg(target_os = "macos")] -mod platform { - use super::{ - ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon, - primary_mac_colon, resolve_host_id, - }; - use crate::process::collection::{CollectionControl, CollectorCommands}; - use std::io; - - pub(super) struct RuntimeNativeHostIdentity; - - impl RuntimeNativeHostIdentity { - pub(super) fn runtime_os() -> ClientOs { - ClientOs::Mac - } - - pub(super) fn collect_with_control( - host_id_override: Option<&str>, - control: &dyn CollectionControl, - ) -> io::Result { - let commands = CollectorCommands::new(control); - let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon); - control.check()?; - let host_id = resolve_host_id(host_id_override, || { - native_mac - .clone() - .unwrap_or_else(|| derive_mac_address(&fallback_hostname())) - }); - let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname); - let serial_number = collect_macos_serial_number(&commands)?; - control.check()?; - Ok(NativeHostIdentitySnapshot { - host_id, - computer, - serial_number, - mac_address: native_mac, - }) - } - } - - fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result> { - Ok( - commands - .run(program, args)? - .filter(|output| output.status.success()) - .and_then(|output| String::from_utf8(output.stdout).ok()), - ) - } - - fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result> { - for name in ["ComputerName", "LocalHostName"] { - if let Some(value) = output(commands, "scutil", &["--get", name])? - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) - { - return Ok(Some(value)); - } - } - Ok(None) - } - - fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result> { - if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? { - for name in ["Wi-Fi", "AirPort"] { - if let Some(mac) = parse_hardware_port_mac(&stdout, name) { - return Ok(Some(mac)); - } - } - } - macos_system_profiler_wifi_mac(commands) - } - - fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option { - let mut in_port = false; - for line in stdout.lines() { - if let Some(port) = line.strip_prefix("Hardware Port: ") { - in_port = port == name; - continue; - } - if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") { - return normalize_mac_colon(mac); - } - } - None - } - - fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result> { - let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else { - return Ok(None); - }; - let mut in_wifi = false; - for line in stdout.lines() { - let trimmed = line.trim(); - if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") { - in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:"; - continue; - } - if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") { - return Ok(normalize_mac_colon(mac)); - } - } - Ok(None) - } - - fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result> { - let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else { - return Ok(None); - }; - Ok(stdout.lines().find_map(|line| { - line - .split_once("IOPlatformSerialNumber") - .and_then(|(_, value)| value.split_once('=')) - .map(|(_, value)| value.trim().trim_matches('"').to_string()) - .filter(|value| !value.is_empty()) - })) - } -} - -#[cfg(target_os = "windows")] -mod platform { - use std::process::Command; - - use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id}; - - pub(super) struct RuntimeNativeHostIdentity; - - impl RuntimeNativeHostIdentity { - pub(super) fn runtime_os() -> ClientOs { - ClientOs::Windows - } - - pub(super) fn collect_with_control( - host_id_override: Option<&str>, - control: &dyn super::CollectionControl, - ) -> super::io::Result { - control.check()?; - let identity = Self::collect(host_id_override); - control.check()?; - Ok(identity) - } - - fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot { - let host_id = resolve_host_id(host_id_override, Self::host_id); - NativeHostIdentitySnapshot { - host_id, - computer: fallback_hostname(), - serial_number: collect_windows_serial_number(), - mac_address: primary_mac_colon(), - } - } - - fn host_id() -> String { - windows_machine_seed().unwrap_or_else(fallback_hostname) - } - } - - fn collect_windows_serial_number() -> Option { - let output = Command::new("wmic") - .args(["bios", "get", "serialnumber"]) - .output() - .ok()?; - let stdout = String::from_utf8(output.stdout).ok()?; - - stdout - .lines() - .map(str::trim) - .filter(|line| !line.is_empty() && *line != "SerialNumber") - .map(str::to_string) - .next() - } - - fn windows_machine_seed() -> Option { - collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid) - } - - fn collect_windows_csproduct_uuid() -> Option { - let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?; - let stdout = String::from_utf8(output.stdout).ok()?; - - stdout - .lines() - .map(str::trim) - .filter(|line| !line.is_empty() && *line != "UUID") - .map(str::to_string) - .next() - } - - fn collect_windows_machine_guid() -> Option { - let output = Command::new("reg") - .args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"]) - .output() - .ok()?; - if !output.status.success() { - return None; - } - let stdout = String::from_utf8(output.stdout).ok()?; - - stdout.lines().find_map(|line| { - let mut parts = line.split_whitespace(); - if parts.next()? != "MachineGuid" { - return None; - } - - parts.last().map(str::to_string) - }) - } -} - -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -mod platform { - use super::{ - ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id, - serial_number, - }; - use log::debug; - - pub(super) struct RuntimeNativeHostIdentity; - - impl RuntimeNativeHostIdentity { - pub(super) fn runtime_os() -> ClientOs { - ClientOs::Linux - } - - pub(super) fn collect_with_control( - host_id_override: Option<&str>, - control: &dyn super::CollectionControl, - ) -> super::io::Result { - control.check()?; - let identity = Self::collect(host_id_override); - control.check()?; - Ok(identity) - } - - fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot { - if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) { - debug!("Runtime host-id source: explicit override ({})", host_id); - } - let host_id = resolve_host_id(host_id_override, Self::host_id); - NativeHostIdentitySnapshot { - host_id, - computer: fallback_hostname(), - serial_number: collect_linux_serial_number(), - mac_address: primary_mac_colon(), - } - } - - fn host_id() -> String { - if let Some(host_id) = collect_linux_product_uuid() { - debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id); - return host_id; - } - - let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| { - let hostname = fallback_hostname(); - ("hostname", hostname) - }); - let host_id = derive_uuid_from_seed(&source, &[]); - debug!("Runtime host-id source: derived from {} ({})", source_name, host_id); - host_id - } - } - - fn collect_linux_product_uuid() -> Option { - read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value)) - } - - fn normalize_uuid(value: &str) -> Option { - uuid::Uuid::parse_str(value.trim()) - .ok() - .map(|uuid| uuid.hyphenated().to_string()) - } - - fn collect_linux_fallback_seed() -> Option<(&'static str, String)> { - ["/etc/machine-id", "/var/lib/dbus/machine-id"] - .iter() - .find_map(|path| read_linux_identity_file(path).map(|value| (*path, value))) - } - - fn read_linux_identity_file(path: &str) -> Option { - std::fs::read_to_string(path) - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| is_usable_linux_identity_value(value)) - } - - fn is_usable_linux_identity_value(value: &str) -> bool { - !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M." - } - - fn collect_linux_serial_number() -> Option { - resolve_linux_serial_number( - read_linux_identity_file("/sys/class/dmi/id/product_serial"), - collect_linux_product_uuid, - ) - } - - fn resolve_linux_serial_number( - product_serial: Option, - product_uuid: impl FnOnce() -> Option, - ) -> Option { - product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid))) - } - - #[cfg(test)] - mod tests { - use super::*; - - #[test] - fn normalize_uuid_preserves_real_uuid_identity() { - assert_eq!( - normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"), - Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string()) - ); - assert_eq!(normalize_uuid("not-a-uuid"), None); - } - - #[test] - fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() { - let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string()); - - assert_eq!( - resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()), - Some("product-serial".to_string()) - ); - assert_eq!( - resolve_linux_serial_number(None, || uuid), - Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string()) - ); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn controlled_identity_collection_propagates_cancellation() { - let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); - let error = HostIdentity::collect_with_control(&control).unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::Interrupted); - let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::Interrupted); - } - - #[test] - fn collect_produces_non_empty_identity() { - let identity = HostIdentity::collect(); - - assert!(!identity.computer().is_empty()); - assert!(!identity.host_id().is_empty()); - assert!(!identity.serialno().is_empty()); - assert!(!identity.mac_addr().is_empty()); - assert_mac(identity.mac_addr(), ':'); - } - - #[test] - fn collect_with_host_id_uses_provided_host_id() { - let identity = HostIdentity::collect_with_host_id(Some("provided-host-id")); - - assert_eq!(identity.host_id(), "provided-host-id"); - assert!(!identity.computer().is_empty()); - assert!(!identity.serialno().is_empty()); - assert!(!identity.mac_addr().is_empty()); - } - - #[test] - fn collect_with_blank_host_id_falls_back_to_runtime_host_id() { - let identity = HostIdentity::collect_with_host_id(Some(" ")); - - assert!(!identity.host_id().is_empty()); - assert_ne!(identity.host_id(), " "); - } - - #[test] - fn resolve_host_id_does_not_collect_when_override_is_provided() { - let host_id = resolve_host_id(Some("provided-host-id"), || { - panic!("runtime host id should not be collected") - }); - - assert_eq!(host_id, "provided-host-id"); - } - - #[test] - fn host_identity_normalizes_mac_to_lowercase_colon_format() { - let identity = HostIdentity::new( - "computer".to_string(), - "host-id".to_string(), - "serial-number".to_string(), - "AA-BB-CC-DD-EE-FF".to_string(), - ); - - assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff"); - } - - #[test] - fn native_snapshot_uses_host_id_as_derivation_seed() { - let native = - RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap(); - - assert!(!native.host_id.is_empty()); - } - - #[test] - fn serialization_keeps_globalprotect_field_names() { - let identity = HostIdentity::new( - "computer".to_string(), - "host-id".to_string(), - "serial-number".to_string(), - "aa:bb:cc:dd:ee:ff".to_string(), - ); - let value = serde_json::to_value(identity).unwrap(); - - assert_eq!(value["hostId"], "host-id"); - assert_eq!(value["computer"], "computer"); - assert!(value.get("osVersion").is_none()); - assert!(value.get("softwareVersion").is_none()); - assert_eq!(value["serialno"], "serial-number"); - assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff"); - } - - #[test] - fn native_identity_falls_back_to_derived_values_when_missing() { - let native = NativeHostIdentitySnapshot { - host_id: "native-host-id".to_string(), - computer: "native-computer".to_string(), - serial_number: None, - mac_address: None, - }; - - let identity = native.into_host_identity(); - - assert_eq!(identity.computer(), "native-computer"); - assert_eq!(identity.host_id(), "native-host-id"); - assert!(identity.serialno().starts_with("VMware-")); - assert_mac(identity.mac_addr(), ':'); - } - - #[test] - fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() { - let identity = HostIdentity::new( - "computer".to_string(), - "5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(), - String::new(), - "aa:bb:cc:dd:ee:ff".to_string(), - ); - - assert_eq!( - identity.serialno(), - "VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef" - ); - } - - #[test] - fn empty_host_id_falls_back_to_non_empty_value() { - let identity = HostIdentity::new(String::new(), String::new(), String::new(), String::new()); - - assert!(!identity.host_id().is_empty()); - assert!(!identity.computer().is_empty()); - assert!(!identity.serialno().is_empty()); - assert!(!identity.mac_addr().is_empty()); - } - - fn assert_mac(value: &str, separator: char) { - let parts: Vec<&str> = value.split(separator).collect(); - assert_eq!(parts.len(), 6, "MAC should have 6 octets"); - for part in &parts { - assert_eq!(part.len(), 2); - assert!(part.chars().all(|c| c.is_ascii_hexdigit())); - } - } -} diff --git a/crates/gpapi/src/os_profile/identity.rs b/crates/gpapi/src/os_profile/identity.rs new file mode 100644 index 0000000..106d692 --- /dev/null +++ b/crates/gpapi/src/os_profile/identity.rs @@ -0,0 +1,56 @@ +use serde::{Deserialize, Serialize}; +use specta::Type; +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct HostIdentity { + computer: String, + host_id: String, + #[serde(rename = "serialno")] + serial_number: String, + #[serde(rename = "macAddr")] + mac_address: String, +} + +impl HostIdentity { + /// Values already collected by the caller. Missing observations stay empty. + pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self { + Self { + computer, + host_id, + serial_number: serialno, + mac_address: mac_addr, + } + } + /// Identity supplied by an application; no hardware attributes are invented. + pub fn application(computer: String, installation_id: String) -> Self { + Self { + computer, + host_id: installation_id, + serial_number: String::new(), + mac_address: String::new(), + } + } + + pub fn computer(&self) -> &str { + &self.computer + } + + pub fn host_id(&self) -> &str { + &self.host_id + } + + pub fn serialno(&self) -> &str { + &self.serial_number + } + + pub fn mac_addr(&self) -> &str { + &self.mac_address + } + + pub fn with_computer(mut self, computer: String) -> Self { + if !computer.trim().is_empty() { + self.computer = computer; + } + self + } +} diff --git a/crates/gpapi/src/os_profile/mod.rs b/crates/gpapi/src/os_profile/mod.rs index 0e4b414..7802d99 100644 --- a/crates/gpapi/src/os_profile/mod.rs +++ b/crates/gpapi/src/os_profile/mod.rs @@ -1,1396 +1,36 @@ -pub mod host_identity; +mod client_os; +pub(crate) mod defaults; +#[cfg(feature = "desktop")] +pub mod desktop; +mod identity; +mod profile; +mod projection; mod serial_number; -pub use host_identity::HostIdentity; - -use crate::process::collection::{CollectionBudget, CollectionControl}; -use std::{io, time::Duration}; - +pub(crate) use client_os::PreloginParamLocation; +use client_os::target; +pub use client_os::{ClientOs, PreloginBrowserMode, WebviewUserAgent, WebviewUserAgentTransform}; use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT}; +use defaults::*; +pub use identity::HostIdentity; +use profile::ProfileHostIdentity; +pub use profile::{HostSnapshot, OsProfile, OsProfileBuilder}; use serde::{Deserialize, Serialize}; use specta::Type; - -const DEFAULT_MACOS_VERSION: &str = "13.4.0"; -const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS"; -const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro"; -const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0"; -const DEFAULT_LINUX_WEBVIEW_USER_AGENT: &str = - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1"; -const DEFAULT_MACOS_WEBVIEW_USER_AGENT: &str = - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)"; -const DEFAULT_WINDOWS_WEBVIEW_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0"; - -// ─── ClientOs ──────────────────────────────────────────────────────────────── - -#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type)] -pub enum ClientOs { - Linux, - Windows, - Mac, -} - -impl From<&str> for ClientOs { - fn from(os: &str) -> Self { - match os { - "Linux" => ClientOs::Linux, - "Windows" => ClientOs::Windows, - "Mac" => ClientOs::Mac, - _ => ClientOs::Linux, - } - } -} - -impl ClientOs { - pub fn as_str(&self) -> &'static str { - match self { - ClientOs::Linux => "Linux", - ClientOs::Windows => "Windows", - ClientOs::Mac => "Mac", - } - } - - pub fn to_openconnect_os(&self) -> &str { - match self { - ClientOs::Linux => "linux", - ClientOs::Windows => "win", - ClientOs::Mac => "mac-intel", - } - } - - pub fn default_client_version(&self) -> &'static str { - match self { - ClientOs::Linux => GP_CLIENT_VERSION_LINUX, - ClientOs::Windows => GP_CLIENT_VERSION_WINDOWS, - ClientOs::Mac => GP_CLIENT_VERSION_MACOS, - } - } - - pub fn default_os_version(&self) -> String { - default_os_version(self) - } - - pub(crate) fn default_csc_support(&self) -> bool { - match self { - ClientOs::Linux => false, - ClientOs::Mac | ClientOs::Windows => true, - } - } -} - -// ─── PreloginParamLocation ─────────────────────────────────────────────────── - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum PreloginParamLocation { - Body, - Query, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PreloginBrowserMode { - Embedded, - External, -} - -// ─── WebviewUserAgent ─────────────────────────────────────────────────────── - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum WebviewUserAgent { - Native { - prefix: String, - transform: WebviewUserAgentTransform, - }, - Projected { - prefix: String, - default_user_agent: String, - }, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WebviewUserAgentTransform { - None, - LinuxPanGpuiVersion, -} - -// ─── Target behavior ──────────────────────────────────────────────────────── - -mod target { - use super::*; - - pub(super) fn os_version(client_os: ClientOs) -> String { - match client_os { - ClientOs::Linux => linux_os_string(), - ClientOs::Windows => windows_os_string(), - ClientOs::Mac => macos_os_string(), - } - } - - pub(super) fn software_version(client_os: ClientOs) -> String { - match client_os { - ClientOs::Linux => String::new(), - ClientOs::Windows => windows_version(), - ClientOs::Mac => macos_version(), - } - } - - pub(super) fn prelogin_param_location(client_os: ClientOs) -> PreloginParamLocation { - match client_os { - ClientOs::Linux | ClientOs::Mac => PreloginParamLocation::Body, - ClientOs::Windows => PreloginParamLocation::Query, - } - } - - pub(super) fn saml_password(client_os: ClientOs) -> &'static str { - match client_os { - ClientOs::Linux => "SAMLPASS", - ClientOs::Mac | ClientOs::Windows => "", - } - } - - pub(super) fn external_browser_os_value(client_os: ClientOs) -> &'static str { - match client_os { - ClientOs::Linux => "4", - ClientOs::Mac => "3", - ClientOs::Windows => "2", - } - } - - pub(super) fn supports_macos_plist_csc(client_os: ClientOs) -> bool { - matches!(client_os, ClientOs::Mac) - } - - pub(super) fn supports_linux_process_csc(client_os: ClientOs) -> bool { - matches!(client_os, ClientOs::Linux) - } - - pub(super) fn supports_windows_registry_csc(client_os: ClientOs) -> bool { - matches!(client_os, ClientOs::Windows) - } - - pub(super) fn kerberos_support_in_query(client_os: ClientOs) -> bool { - match client_os { - ClientOs::Linux => false, - ClientOs::Mac | ClientOs::Windows => true, - } - } - - pub(super) fn os_vendor(client_os: ClientOs) -> &'static str { - match client_os { - ClientOs::Linux => "Linux", - ClientOs::Mac => "Apple", - ClientOs::Windows => "Microsoft", - } - } - - pub(super) fn webview_user_agent_default(client_os: ClientOs) -> &'static str { - match client_os { - ClientOs::Linux => DEFAULT_LINUX_WEBVIEW_USER_AGENT, - ClientOs::Mac => DEFAULT_MACOS_WEBVIEW_USER_AGENT, - ClientOs::Windows => DEFAULT_WINDOWS_WEBVIEW_USER_AGENT, - } - } - - pub(super) fn webview_user_agent_transform(client_os: ClientOs) -> WebviewUserAgentTransform { - match client_os { - ClientOs::Linux => WebviewUserAgentTransform::LinuxPanGpuiVersion, - ClientOs::Mac | ClientOs::Windows => WebviewUserAgentTransform::None, - } - } -} - -// ─── ProfileHostIdentity ──────────────────────────────────────────────────── - -#[derive(Debug, Clone, PartialEq, Eq)] -struct ProfileHostIdentity { - computer: String, - host_id: String, - serial_number: String, - mac_address: String, -} - -impl ProfileHostIdentity { - fn for_client_os(client_os: ClientOs, host_identity: &HostIdentity, computer_override: Option) -> Self { - target_identity::project(client_os, host_identity, computer_override) - } - - fn computer(&self) -> &str { - &self.computer - } - - fn host_id(&self) -> &str { - &self.host_id - } - - fn serialno(&self) -> &str { - &self.serial_number - } - - fn mac_addr(&self) -> &str { - &self.mac_address - } -} - -// ─── OsProfile ─────────────────────────────────────────────────────────────── - -#[derive(Debug, Clone)] -pub struct OsProfile { - client_os: ClientOs, - os_version: String, - software_version: String, - os_vendor: &'static str, - client_version: String, - host_identity: HostIdentity, - profile_identity: ProfileHostIdentity, - user_agent: String, -} - -impl OsProfile { - pub fn builder(client_os: ClientOs) -> OsProfileBuilder { - OsProfileBuilder::new(client_os) - } - - // ─── Identity accessors ────────────────────────────────────────────────── - - pub fn client_os(&self) -> ClientOs { - self.client_os - } - - pub fn computer(&self) -> &str { - self.profile_identity.computer() - } - - pub fn os_version(&self) -> &str { - &self.os_version - } - - pub fn client_version(&self) -> &str { - &self.client_version - } - - pub fn host_identity(&self) -> &HostIdentity { - &self.host_identity - } - - pub fn user_agent(&self) -> &str { - &self.user_agent - } - - pub fn webview_user_agent(&self) -> WebviewUserAgent { - if self.is_native() { - WebviewUserAgent::Native { - prefix: self.user_agent.clone(), - transform: target::webview_user_agent_transform(self.client_os), - } - } else { - WebviewUserAgent::Projected { - prefix: self.user_agent.clone(), - default_user_agent: target::webview_user_agent_default(self.client_os).to_string(), - } - } - } - - pub fn host_id(&self) -> &str { - self.profile_identity.host_id() - } - - pub fn serialno(&self) -> &str { - self.profile_identity.serialno() - } - - pub fn mac_addr(&self) -> &str { - self.profile_identity.mac_addr() - } - - /// Returns true when the target client OS matches the runtime OS. - /// - /// Used to decide whether to consult real OS-level state (e.g. the actual - /// network interface) versus simulated values for emulation. - pub fn is_native(&self) -> bool { - runtime_client_os() == self.client_os - } - - /// Default software version string for the target OS, matching the - /// official client values. - pub fn software_version(&self) -> &str { - &self.software_version - } - - // ─── Behavioral methods ────────────────────────────────────────────────── - - pub(crate) fn prelogin_param_location(&self) -> PreloginParamLocation { - target::prelogin_param_location(self.client_os) - } - - pub(crate) fn portal_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str { - match browser_mode { - PreloginBrowserMode::Embedded => "-10", - PreloginBrowserMode::External => target::external_browser_os_value(self.client_os), - } - } - - pub(crate) fn gateway_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str { - match browser_mode { - PreloginBrowserMode::Embedded => "0", - PreloginBrowserMode::External => target::external_browser_os_value(self.client_os), - } - } - - pub(crate) fn saml_password(&self) -> &'static str { - target::saml_password(self.client_os) - } - - pub(crate) fn gateway_server_uses_resolved_ipv4(&self) -> bool { - true - } - - pub(crate) fn supports_macos_plist_csc(&self) -> bool { - target::supports_macos_plist_csc(self.client_os) - } - - pub(crate) fn supports_linux_process_csc(&self) -> bool { - target::supports_linux_process_csc(self.client_os) - } - - pub(crate) fn supports_windows_registry_csc(&self) -> bool { - target::supports_windows_registry_csc(self.client_os) - } - - pub(crate) fn kerberos_support_in_query(&self) -> bool { - target::kerberos_support_in_query(self.client_os) - } - - pub fn os_vendor(&self) -> &'static str { - self.os_vendor - } -} - -// ─── OsProfileBuilder ──────────────────────────────────────────────────────── - -#[derive(Debug, Clone)] -pub struct OsProfileBuilder { - client_os: ClientOs, - client_version: Option, - os_version_override: Option, - computer_name_override: Option, - host_id_override: Option, - host_identity: Option, - user_agent: Option, -} - -impl OsProfileBuilder { - pub fn new(client_os: ClientOs) -> Self { - Self { - client_os, - client_version: None, - os_version_override: None, - computer_name_override: None, - host_id_override: None, - host_identity: None, - user_agent: None, - } - } - - pub fn computer_name_override(mut self, name: impl Into) -> Self { - self.computer_name_override = Some(name.into()); - self - } - - pub fn client_version(mut self, version: impl Into) -> Self { - self.client_version = Some(version.into()); - self - } - - /// Preserve an explicitly negotiated operating system version. - pub fn os_version(mut self, version: impl Into) -> Self { - let version = version.into(); - self.os_version_override = if version.trim().is_empty() { None } else { Some(version) }; - self - } - - pub fn host_identity(mut self, identity: HostIdentity) -> Self { - self.host_identity = Some(identity); - self - } - - pub fn host_id_override(mut self, host_id: impl Into) -> Self { - let host_id = host_id.into(); - self.host_id_override = if host_id.trim().is_empty() { None } else { Some(host_id) }; - self - } - - pub fn user_agent(mut self, ua: impl Into) -> Self { - let ua = ua.into(); - self.user_agent = if ua.trim().is_empty() { None } else { Some(ua) }; - self - } - - /// Build a best-effort profile with a bounded native collection budget. - /// Use `build_with_control` when interruption or timeout must be reported. - pub fn build(self) -> OsProfile { - match self - .clone() - .build_with_control(&CollectionBudget::new(Duration::from_secs(60))) - { - Ok(profile) => profile, - Err(error) => { - log::warn!("OS profile collection was unavailable: {error}"); - let identity = self - .host_identity - .clone() - .unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref())); - let (os_version, software_version) = match self.client_os { - ClientOs::Mac => ( - format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"), - DEFAULT_MACOS_VERSION.into(), - ), - os => (target::os_version(os), target::software_version(os)), - }; - self.finish(identity, os_version, software_version) - } - } - } - - pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result { - control.check()?; - let host_identity = match (&self.host_identity, &self.host_id_override) { - (Some(identity), _) => identity.clone(), - (None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?, - }; - let (os_version, software_version) = if self.client_os == ClientOs::Mac { - let version = macos_version_with_control(control)?; - (format!("Apple Mac OS X {version}"), version) - } else { - ( - target::os_version(self.client_os), - target::software_version(self.client_os), - ) - }; - control.check()?; - Ok(self.finish(host_identity, os_version, software_version)) - } - - fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile { - let client_version = self - .client_version - .filter(|version| !version.trim().is_empty()) - .unwrap_or_else(|| self.client_os.default_client_version().into()); - let profile_identity = - ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override); - let os_version = self.os_version_override.unwrap_or(default_os_version); - let user_agent = self - .user_agent - .unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})")); - OsProfile { - client_os: self.client_os, - os_version, - software_version, - os_vendor: target::os_vendor(self.client_os), - client_version, - host_identity, - profile_identity, - user_agent, - } - } -} - -// ─── Default helpers ───────────────────────────────────────────────────────── - -pub fn default_computer_name(client_os: &ClientOs) -> String { - ProfileHostIdentity::for_client_os(*client_os, &HostIdentity::collect(), None) - .computer() - .to_string() -} - -pub fn default_os_version(client_os: &ClientOs) -> String { - target::os_version(*client_os) -} - -pub fn default_software_version(client_os: &ClientOs) -> String { - target::software_version(*client_os) -} - -pub fn runtime_client_os() -> ClientOs { - HostIdentity::runtime_os() -} - -fn linux_os_string() -> String { - if runtime_client_os() == ClientOs::Linux { - format!("Linux {}", runtime_distro_or(DEFAULT_LINUX_DISTRO)) - } else { - format!("Linux {}", DEFAULT_LINUX_DISTRO) - } -} - -fn windows_version() -> String { - if runtime_client_os() == ClientOs::Windows { - match os_info::get().version() { - os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION.to_string(), - v => format!("{}.0", v), - } - } else { - DEFAULT_WINDOWS_VERSION.to_string() - } -} - -fn windows_os_string() -> String { - if runtime_client_os() == ClientOs::Windows { - let edition = os_info::get() - .edition() - .map(|e| e.to_string()) - .unwrap_or_else(|| runtime_distro_or(DEFAULT_WINDOWS_DISTRO)); - format!("Microsoft {} , 64-bit", edition) - } else { - format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO) - } -} - -fn runtime_distro_or(fallback: &str) -> String { - whoami::distro().unwrap_or_else(|_| fallback.to_string()) -} - -fn macos_version() -> String { - macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| { - log::warn!("Operating system version collection was unavailable: {error}"); - DEFAULT_MACOS_VERSION.into() - }) -} - -fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result { - control.check()?; - #[cfg(target_os = "macos")] - { - let commands = crate::process::collection::CollectorCommands::new(control); - let version = commands - .run("sw_vers", &["-productVersion"])? - .filter(|output| output.status.success()) - .and_then(|output| String::from_utf8(output.stdout).ok()) - .map(|version| version.trim().to_string()) - .filter(|version| !version.is_empty()); - control.check()?; - Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into())) - } - #[cfg(not(target_os = "macos"))] - Ok(DEFAULT_MACOS_VERSION.into()) -} - -fn macos_os_string() -> String { - format!("Apple Mac OS X {}", macos_version()) -} - -fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String { - use uuid::Uuid; - - let namespace = Uuid::NAMESPACE_DNS; - let name = format!("{}-{}", seed, parts.join("-")); - - Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string() -} - -fn derived_profile_mac(seed: &str, client_os: ClientOs) -> String { - let uuid = derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), "mac"]); - let compact = uuid.replace('-', ""); - let bytes = compact - .as_bytes() - .chunks(2) - .take(6) - .map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase()) - .collect::>(); - - match client_os { - ClientOs::Linux | ClientOs::Windows => bytes.join("-"), - ClientOs::Mac => bytes.join(":"), - } -} - -fn compact_uuid(seed: &str, client_os: ClientOs, suffix: &str) -> String { - derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), suffix]) - .replace('-', "") - .to_uppercase() -} - -mod target_identity { - use super::*; - - pub(super) fn project( - client_os: ClientOs, - host_identity: &HostIdentity, - computer_override: Option, - ) -> ProfileHostIdentity { - if client_os == runtime_client_os() { - return native::project(client_os, host_identity, computer_override); - } - - match client_os { - ClientOs::Linux => linux::project(host_identity, computer_override), - ClientOs::Windows => windows::project(host_identity, computer_override), - ClientOs::Mac => macos::project(host_identity, computer_override), - } - } - - fn computer(host_identity: &HostIdentity, computer_override: Option) -> String { - computer_override - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| host_identity.computer().to_string()) - } - - fn profile_mac_for(client_os: ClientOs, mac_address: &str) -> String { - match client_os { - ClientOs::Linux | ClientOs::Windows => mac_address.replace(':', "-"), - ClientOs::Mac => mac_address.replace('-', ":"), - } - } - - mod native { - use super::*; - - pub(super) fn project( - client_os: ClientOs, - host_identity: &HostIdentity, - computer_override: Option, - ) -> ProfileHostIdentity { - ProfileHostIdentity { - computer: computer(host_identity, computer_override), - host_id: match client_os { - ClientOs::Mac => host_identity.host_id().replace('-', ":"), - ClientOs::Linux | ClientOs::Windows => host_identity.host_id().to_string(), - }, - serial_number: host_identity.serialno().to_string(), - mac_address: profile_mac_for(client_os, host_identity.mac_addr()), - } - } - } - - mod linux { - use super::*; - - pub(super) fn project(host_identity: &HostIdentity, computer_override: Option) -> ProfileHostIdentity { - let seed = host_identity.host_id(); - let host_id = derive_uuid_from_seed(seed, &["os-profile", ClientOs::Linux.as_str(), "host-id"]); - ProfileHostIdentity { - computer: computer(host_identity, computer_override), - serial_number: serial_number::vmware_from_uuid(&host_id).expect("projected Linux host ID should be a UUID"), - host_id, - mac_address: derived_profile_mac(seed, ClientOs::Linux), - } - } - } - - mod windows { - use super::*; - - pub(super) fn project(host_identity: &HostIdentity, computer_override: Option) -> ProfileHostIdentity { - let seed = host_identity.host_id(); - ProfileHostIdentity { - computer: computer(host_identity, computer_override), - host_id: derive_uuid_from_seed(seed, &["os-profile", ClientOs::Windows.as_str(), "host-id"]), - serial_number: serial_number::vmware_from_compact_hex(&compact_uuid(seed, ClientOs::Windows, "serialno")) - .expect("projected Windows serial seed should be compact hex"), - mac_address: derived_profile_mac(seed, ClientOs::Windows), - } - } - } - - mod macos { - use super::*; - - pub(super) fn project(host_identity: &HostIdentity, computer_override: Option) -> ProfileHostIdentity { - let seed = host_identity.host_id(); - let mac_address = derived_profile_mac(seed, ClientOs::Mac); - ProfileHostIdentity { - computer: computer(host_identity, computer_override), - host_id: mac_address.clone(), - serial_number: compact_uuid(seed, ClientOs::Mac, "serialno").chars().take(10).collect(), - mac_address, - } - } - } - - #[cfg(test)] - mod tests { - use super::*; - - fn host_identity() -> HostIdentity { - HostIdentity::new( - "real-computer".to_string(), - "real-host-id".to_string(), - "real-serial".to_string(), - "AA-BB-CC-DD-EE-FF".to_string(), - ) - } - - #[test] - fn native_linux_projection_uses_real_identity_with_dash_mac() { - let profile = native::project(ClientOs::Linux, &host_identity(), None); - - assert_eq!(profile.computer(), "real-computer"); - assert_eq!(profile.host_id(), "real-host-id"); - assert_eq!(profile.serialno(), "real-serial"); - assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff"); - } - - #[test] - fn native_windows_projection_uses_real_identity_with_dash_mac() { - let profile = native::project(ClientOs::Windows, &host_identity(), None); - - assert_eq!(profile.computer(), "real-computer"); - assert_eq!(profile.host_id(), "real-host-id"); - assert_eq!(profile.serialno(), "real-serial"); - assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff"); - } - - #[test] - fn native_macos_projection_uses_real_identity_with_colon_mac() { - let profile = native::project(ClientOs::Mac, &host_identity(), None); - - assert_eq!(profile.computer(), "real-computer"); - assert_eq!(profile.host_id(), "real:host:id"); - assert_eq!(profile.serialno(), "real-serial"); - assert_eq!(profile.mac_addr(), "aa:bb:cc:dd:ee:ff"); - } - } -} +#[cfg(test)] +mod tests; #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn controlled_profile_collection_propagates_cancellation_and_deadline() { - let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); - let error = OsProfileBuilder::new(ClientOs::Mac) - .build_with_control(&cancelled) - .unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::Interrupted); - let expired = CollectionBudget::new(Duration::ZERO); - let error = OsProfileBuilder::new(ClientOs::Linux) - .build_with_control(&expired) - .unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::TimedOut); - } - - #[test] - fn negotiated_os_version_is_used_in_profile_and_user_agent() { - let identity = HostIdentity::from_parts( - "device".into(), - "host".into(), - "serial".into(), - "00:11:22:33:44:55".into(), - ); - let profile = OsProfileBuilder::new(ClientOs::Mac) - .host_identity(identity) - .client_version("6.3.3") - .os_version("negotiated-system-version") - .build(); - assert_eq!(profile.os_version(), "negotiated-system-version"); - assert!(profile.user_agent().contains("negotiated-system-version")); - } - - #[test] - fn csc_support_defaults_match_official_profiles() { - assert!(!ClientOs::Linux.default_csc_support()); - assert!(ClientOs::Mac.default_csc_support()); - assert!(ClientOs::Windows.default_csc_support()); - } - - #[test] - fn prelogin_param_location_matches_official_profiles() { - assert_eq!( - OsProfileBuilder::new(ClientOs::Linux).build().prelogin_param_location(), - PreloginParamLocation::Body - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Mac).build().prelogin_param_location(), - PreloginParamLocation::Body - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .prelogin_param_location(), - PreloginParamLocation::Query - ); - } - - #[test] - fn embedded_portal_default_browser_is_minus_ten_for_all() { - assert_eq!( - OsProfileBuilder::new(ClientOs::Linux) - .build() - .portal_default_browser(PreloginBrowserMode::Embedded), - "-10" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Mac) - .build() - .portal_default_browser(PreloginBrowserMode::Embedded), - "-10" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .portal_default_browser(PreloginBrowserMode::Embedded), - "-10" - ); - } - - #[test] - fn embedded_gateway_default_browser_is_zero_for_all() { - assert_eq!( - OsProfileBuilder::new(ClientOs::Linux) - .build() - .gateway_default_browser(PreloginBrowserMode::Embedded), - "0" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Mac) - .build() - .gateway_default_browser(PreloginBrowserMode::Embedded), - "0" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .gateway_default_browser(PreloginBrowserMode::Embedded), - "0" - ); - } - - #[test] - fn external_default_browser_values_match_official_profiles() { - assert_eq!( - OsProfileBuilder::new(ClientOs::Linux) - .build() - .portal_default_browser(PreloginBrowserMode::External), - "4" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Mac) - .build() - .portal_default_browser(PreloginBrowserMode::External), - "3" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .portal_default_browser(PreloginBrowserMode::External), - "2" - ); - - assert_eq!( - OsProfileBuilder::new(ClientOs::Linux) - .build() - .gateway_default_browser(PreloginBrowserMode::External), - "4" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Mac) - .build() - .gateway_default_browser(PreloginBrowserMode::External), - "3" - ); - assert_eq!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .gateway_default_browser(PreloginBrowserMode::External), - "2" - ); - } - - #[test] - fn saml_password_matches_official_profiles() { - assert_eq!( - OsProfileBuilder::new(ClientOs::Linux).build().saml_password(), - "SAMLPASS" - ); - assert_eq!(OsProfileBuilder::new(ClientOs::Mac).build().saml_password(), ""); - assert_eq!(OsProfileBuilder::new(ClientOs::Windows).build().saml_password(), ""); - } - - #[test] - fn gateway_server_uses_resolved_ipv4_for_all() { - assert!( - OsProfileBuilder::new(ClientOs::Linux) - .build() - .gateway_server_uses_resolved_ipv4() - ); - assert!( - OsProfileBuilder::new(ClientOs::Mac) - .build() - .gateway_server_uses_resolved_ipv4() - ); - assert!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .gateway_server_uses_resolved_ipv4() - ); - } - - #[test] - fn kerberos_support_in_query_matches_official_profiles() { - assert!( - !OsProfileBuilder::new(ClientOs::Linux) - .build() - .kerberos_support_in_query() - ); - assert!(OsProfileBuilder::new(ClientOs::Mac).build().kerberos_support_in_query()); - assert!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .kerberos_support_in_query() - ); - } - - #[test] - fn os_vendor_matches_official_profiles() { - assert_eq!(OsProfileBuilder::new(ClientOs::Linux).build().os_vendor(), "Linux"); - assert_eq!(OsProfileBuilder::new(ClientOs::Mac).build().os_vendor(), "Apple"); - assert_eq!( - OsProfileBuilder::new(ClientOs::Windows).build().os_vendor(), - "Microsoft" - ); - } - - #[test] - fn supports_macos_plist_csc_only_for_mac() { - assert!( - !OsProfileBuilder::new(ClientOs::Linux) - .build() - .supports_macos_plist_csc() - ); - assert!(OsProfileBuilder::new(ClientOs::Mac).build().supports_macos_plist_csc()); - assert!( - !OsProfileBuilder::new(ClientOs::Windows) - .build() - .supports_macos_plist_csc() - ); - } - - #[test] - fn supports_linux_process_csc_only_for_linux() { - assert!( - OsProfileBuilder::new(ClientOs::Linux) - .build() - .supports_linux_process_csc() - ); - assert!( - !OsProfileBuilder::new(ClientOs::Mac) - .build() - .supports_linux_process_csc() - ); - assert!( - !OsProfileBuilder::new(ClientOs::Windows) - .build() - .supports_linux_process_csc() - ); - } - - #[test] - fn supports_windows_registry_csc_only_for_windows() { - assert!( - !OsProfileBuilder::new(ClientOs::Linux) - .build() - .supports_windows_registry_csc() - ); - assert!( - !OsProfileBuilder::new(ClientOs::Mac) - .build() - .supports_windows_registry_csc() - ); - assert!( - OsProfileBuilder::new(ClientOs::Windows) - .build() - .supports_windows_registry_csc() - ); - } - - // ─── User Agent Tests ─────────────────────────────────────────────────────── - - #[test] - fn user_agent_derived_format_without_override() { - let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build(); - - assert_eq!( - profile.user_agent(), - format!("PAN GlobalProtect/6.0.0 ({})", default_os_version(&ClientOs::Linux)) - ); - } - - #[test] - fn user_agent_explicit_override_returns_custom_value() { - let profile = OsProfileBuilder::new(ClientOs::Linux) - .client_version("6.0.0") - .user_agent("custom/1.0") - .build(); - - assert_eq!(profile.user_agent(), "custom/1.0"); - } - - #[test] - fn user_agent_empty_override_falls_back_to_derived() { - let profile = OsProfileBuilder::new(ClientOs::Linux) - .client_version("6.0.0") - .user_agent("") - .build(); - - assert_eq!( - profile.user_agent(), - format!("PAN GlobalProtect/6.0.0 ({})", default_os_version(&ClientOs::Linux)) - ); - } - - #[test] - fn user_agent_whitespace_only_override_falls_back_to_derived() { - let profile = OsProfileBuilder::new(ClientOs::Linux) - .client_version("6.0.0") - .user_agent(" ") - .build(); - - assert_eq!( - profile.user_agent(), - format!("PAN GlobalProtect/6.0.0 ({})", default_os_version(&ClientOs::Linux)) - ); - } - - #[test] - fn user_agent_derived_is_non_empty_for_all_client_os_variants() { - for client_os in [ClientOs::Linux, ClientOs::Windows, ClientOs::Mac] { - let profile = OsProfileBuilder::new(client_os).build(); - assert!( - !profile.user_agent().is_empty(), - "user_agent() should be non-empty for {:?}", - client_os - ); - } - } - - #[test] - fn native_webview_user_agent_uses_native_default() { - let profile = OsProfileBuilder::new(runtime_client_os()).build(); - let user_agent = profile.webview_user_agent(); - - assert_eq!( - user_agent, - WebviewUserAgent::Native { - prefix: profile.user_agent().to_string(), - transform: target::webview_user_agent_transform(runtime_client_os()) - } - ); - } - - #[test] - fn projected_linux_webview_user_agent_uses_linux_default() { - if runtime_client_os() == ClientOs::Linux { - return; - } - - let client_os = ClientOs::Linux; - let profile = OsProfileBuilder::new(client_os).build(); - let user_agent = profile.webview_user_agent(); - - assert_eq!( - user_agent, - WebviewUserAgent::Projected { - prefix: profile.user_agent().to_string(), - default_user_agent: DEFAULT_LINUX_WEBVIEW_USER_AGENT.to_string() - } - ); - } - - #[test] - fn projected_macos_webview_user_agent_uses_macos_default() { - if runtime_client_os() == ClientOs::Mac { - return; - } - - let client_os = ClientOs::Mac; - let profile = OsProfileBuilder::new(client_os).build(); - let user_agent = profile.webview_user_agent(); - - assert_eq!( - user_agent, - WebviewUserAgent::Projected { - prefix: profile.user_agent().to_string(), - default_user_agent: DEFAULT_MACOS_WEBVIEW_USER_AGENT.to_string() - } - ); - } - - #[test] - fn projected_windows_webview_user_agent_uses_windows_default() { - if runtime_client_os() == ClientOs::Windows { - return; - } - - let client_os = ClientOs::Windows; - let profile = OsProfileBuilder::new(client_os).build(); - let user_agent = profile.webview_user_agent(); - - assert_eq!( - user_agent, - WebviewUserAgent::Projected { - prefix: profile.user_agent().to_string(), - default_user_agent: DEFAULT_WINDOWS_WEBVIEW_USER_AGENT.to_string() - } - ); - } - - #[test] - fn os_version_strings_match_profiles() { - assert!(default_os_version(&ClientOs::Linux).starts_with("Linux ")); - assert!(default_os_version(&ClientOs::Mac).starts_with("Apple Mac OS X ")); - assert!(default_os_version(&ClientOs::Windows).starts_with("Microsoft ")); - assert_eq!(default_software_version(&ClientOs::Linux), ""); - assert!(!default_software_version(&ClientOs::Mac).is_empty()); - assert!(!default_software_version(&ClientOs::Windows).is_empty()); - } - - #[test] - fn builder_fills_defaults_when_nothing_specified() { - let profile = OsProfileBuilder::new(ClientOs::Linux).build(); - - assert_eq!(profile.client_os(), ClientOs::Linux); - assert!(!profile.computer().is_empty()); - assert!(profile.os_version().starts_with("Linux ")); - assert_eq!(profile.client_version(), GP_CLIENT_VERSION_LINUX); - assert!(!profile.host_id().is_empty()); - } - - #[test] - fn builder_delegates_default_identity_to_host_identity() { - let expected = HostIdentity::collect(); - let profile = OsProfileBuilder::new(runtime_client_os()) - .host_identity(expected.clone()) - .build(); - - assert_eq!(profile.host_identity(), &expected); - } - - #[test] - fn builder_host_id_override_uses_supplied_runtime_identity_seed() { - let profile = OsProfileBuilder::new(runtime_client_os()) - .host_id_override("provided-host-id") - .build(); - - assert_eq!(profile.host_identity().host_id(), "provided-host-id"); - } - - #[test] - fn builder_host_id_override_is_used_as_projected_identity_seed() { - let client_os = match runtime_client_os() { - ClientOs::Linux => ClientOs::Mac, - ClientOs::Mac | ClientOs::Windows => ClientOs::Linux, - }; - - let first = OsProfileBuilder::new(client_os) - .host_id_override("provided-host-id") - .build(); - let second = OsProfileBuilder::new(client_os) - .host_id_override("provided-host-id") - .build(); - - assert_eq!(first.host_identity().host_id(), "provided-host-id"); - assert_eq!(first.host_id(), second.host_id()); - assert_ne!(first.host_id(), "provided-host-id"); - } - - #[test] - fn builder_uses_explicit_values_when_provided() { - let identity = HostIdentity::new( - "identity-computer".to_string(), - "test-host-id".to_string(), - "test-serial".to_string(), - "aa:bb:cc:dd:ee:ff".to_string(), - ); - let profile = OsProfileBuilder::new(ClientOs::Mac) - .computer_name_override("MyMac") - .client_version("6.2.0-100") - .host_identity(identity.clone()) - .build(); - - assert_eq!(profile.client_os(), ClientOs::Mac); - assert_eq!(profile.computer(), "MyMac"); - assert!(profile.os_version().starts_with("Apple Mac OS X ")); - assert_eq!(profile.client_version(), "6.2.0-100"); - assert_eq!(profile.host_identity(), &identity); - assert!(!profile.host_id().is_empty()); - assert!(!profile.serialno().is_empty()); - assert!(!profile.mac_addr().is_empty()); - } - - #[test] - fn builder_ignores_empty_strings() { - let profile = OsProfileBuilder::new(ClientOs::Windows) - .computer_name_override("") - .client_version("") - .build(); - - // Should fall back to defaults, not use empty strings - assert!(!profile.computer().is_empty()); - assert!(profile.os_version().starts_with("Microsoft ")); - assert_eq!(profile.client_version(), GP_CLIENT_VERSION_WINDOWS); - } - - #[test] - fn identity_accessors_delegate_to_host_identity() { - let identity = HostIdentity::new( - "test-computer".to_string(), - "host-123".to_string(), - "serial-456".to_string(), - "11:22:33:44:55:66".to_string(), - ); - let profile = OsProfileBuilder::new(runtime_client_os()) - .host_identity(identity) - .build(); - - assert!(!profile.host_id().is_empty()); - assert_eq!(profile.serialno(), "serial-456"); - assert!(!profile.mac_addr().is_empty()); - } - - #[test] - fn local_hostname_override_changes_only_projected_computer() { - let identity = HostIdentity::new( - "real-computer".to_string(), - "real-host-id".to_string(), - "real-serial".to_string(), - "11:22:33:44:55:66".to_string(), - ); - - let profile = OsProfileBuilder::new(runtime_client_os()) - .host_identity(identity) - .computer_name_override("profile-computer") - .build(); - - assert_eq!(profile.computer(), "profile-computer"); - assert_eq!(profile.host_identity().computer(), "real-computer"); - } - - #[test] - fn simulated_profile_identity_is_derived_from_real_host_id() { - let client_os = non_native_client_os(); - let identity = HostIdentity::new( - "real-computer".to_string(), - "stable-real-host-id".to_string(), - "real-serial".to_string(), - "11:22:33:44:55:66".to_string(), - ); - - let first = OsProfileBuilder::new(client_os).host_identity(identity.clone()).build(); - let second = OsProfileBuilder::new(client_os).host_identity(identity).build(); - - assert_eq!(first.host_identity().host_id(), "stable-real-host-id"); - assert_ne!(first.host_id(), "stable-real-host-id"); - assert_eq!(first.host_id(), second.host_id()); - assert_eq!(first.serialno(), second.serialno()); - assert_eq!(first.mac_addr(), second.mac_addr()); - } - - #[test] - fn simulated_linux_serial_uses_vmware_style_uuid_bytes() { - if runtime_client_os() == ClientOs::Linux { - return; - } - - let identity = HostIdentity::new( - "real-computer".to_string(), - "stable-real-host-id".to_string(), - "real-serial".to_string(), - "11:22:33:44:55:66".to_string(), - ); - - let profile = OsProfileBuilder::new(ClientOs::Linux).host_identity(identity).build(); - - assert!(profile.serialno().starts_with("VMware-")); - assert_eq!( - profile.serialno().len(), - "VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".len() - ); - } - - #[test] - fn profile_os_versions_are_not_host_identity_fields() { - let identity = HostIdentity::new( - "real-computer".to_string(), - "stable-real-host-id".to_string(), - "real-serial".to_string(), - "11:22:33:44:55:66".to_string(), - ); - let profile = OsProfileBuilder::new(ClientOs::Mac).host_identity(identity).build(); - let value = serde_json::to_value(profile.host_identity()).unwrap(); - - assert!(value.get("osVersion").is_none()); - assert!(value.get("softwareVersion").is_none()); - assert!(profile.os_version().starts_with("Apple Mac OS X ")); - assert!(!profile.software_version().is_empty()); - } - - fn non_native_client_os() -> ClientOs { - match runtime_client_os() { - ClientOs::Linux => ClientOs::Mac, - ClientOs::Mac | ClientOs::Windows => ClientOs::Linux, - } - } - - // ─── Property-Based Tests ───────────────────────────────────────────────── - - mod prop_tests { - use super::*; - use proptest::prelude::*; - - // **Validates: Requirements 1.1, 1.2, 1.3, 1.4, 2.3, 12.1, 12.2** - // - // Property 1: Derived user agent format - // For any valid OsProfile built without a user agent override (with arbitrary - // non-empty client_version), user_agent() returns a non-empty string matching - // the format "PAN GlobalProtect/{client_version} ({profile.os_version})". - proptest! { - #[test] - fn derived_user_agent_format( - cv in "\\S{1,50}", - ) { - let profile = OsProfileBuilder::new(ClientOs::Linux) - .client_version(cv.clone()) - .build(); - - let expected = format!("PAN GlobalProtect/{} ({})", cv, profile.os_version()); - prop_assert_eq!(profile.user_agent(), expected.as_str()); - prop_assert!(!profile.user_agent().is_empty()); - } - } - - // **Validates: Requirements 2.2, 12.3** - // - // Property 2: Override returns verbatim - // For any non-whitespace-only string provided to OsProfileBuilder::user_agent(), - // the resulting OsProfile::user_agent() returns the exact input. - proptest! { - #[test] - fn override_returns_verbatim(ua in "[^\\s][\\s\\S]{0,49}") { - let profile = OsProfileBuilder::new(ClientOs::Linux) - .user_agent(ua.clone()) - .build(); - - prop_assert_eq!(profile.user_agent(), ua.as_str()); - } - } - - // **Validates: Requirements 2.4** - // - // Property 3: Whitespace override falls back to derived - // For any string composed entirely of whitespace characters provided to - // OsProfileBuilder::user_agent(), the resulting OsProfile::user_agent() - // returns the derived format (not the whitespace string). - proptest! { - #[test] - fn whitespace_override_falls_back_to_derived(ws in "[ \\t\\n]{1,20}") { - let profile = OsProfileBuilder::new(ClientOs::Linux) - .client_version("6.0.0") - .user_agent(ws.clone()) - .build(); - - // The result must be the derived format, not the whitespace string - let expected = format!("PAN GlobalProtect/6.0.0 ({})", profile.os_version()); - prop_assert_eq!(profile.user_agent(), expected.as_str()); - prop_assert_ne!(profile.user_agent(), ws.as_str()); - } - } +pub(crate) fn test_snapshot() -> HostSnapshot { + HostSnapshot { + runtime_os: ClientOs::Mac, + identity: HostIdentity::from_parts( + "test-computer".into(), + "test-host-id".into(), + "test-serial".into(), + "aa:bb:cc:dd:ee:ff".into(), + ), + os_version: defaults::os_version(ClientOs::Mac), + software_version: defaults::software_version(ClientOs::Mac), } } diff --git a/crates/gpapi/src/os_profile/profile.rs b/crates/gpapi/src/os_profile/profile.rs new file mode 100644 index 0000000..9086928 --- /dev/null +++ b/crates/gpapi/src/os_profile/profile.rs @@ -0,0 +1,277 @@ +use super::*; +/// Observed host facts supplied by the platform owner. +#[derive(Debug, Clone)] +pub struct HostSnapshot { + pub runtime_os: ClientOs, + pub identity: HostIdentity, + pub os_version: String, + pub software_version: String, +} +// ─── ProfileHostIdentity ──────────────────────────────────────────────────── + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct ProfileHostIdentity { + pub(super) computer: String, + pub(super) host_id: String, + pub(super) serial_number: String, + pub(super) mac_address: String, +} + +impl ProfileHostIdentity { + pub(super) fn for_client_os( + runtime_os: ClientOs, + client_os: ClientOs, + host_identity: &HostIdentity, + computer_override: Option, + ) -> Self { + projection::project(runtime_os, client_os, host_identity, computer_override) + } + + pub(super) fn computer(&self) -> &str { + &self.computer + } + + pub(super) fn host_id(&self) -> &str { + &self.host_id + } + + pub(super) fn serialno(&self) -> &str { + &self.serial_number + } + + pub(super) fn mac_addr(&self) -> &str { + &self.mac_address + } +} + +// ─── OsProfile ─────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone)] +pub struct OsProfile { + runtime_os: ClientOs, + client_os: ClientOs, + os_version: String, + software_version: String, + os_vendor: &'static str, + client_version: String, + host_identity: HostIdentity, + profile_identity: ProfileHostIdentity, + user_agent: String, +} + +impl OsProfile { + pub fn builder(client_os: ClientOs) -> OsProfileBuilder { + OsProfileBuilder::new(client_os) + } + + // ─── Identity accessors ────────────────────────────────────────────────── + + pub fn client_os(&self) -> ClientOs { + self.client_os + } + + pub fn computer(&self) -> &str { + self.profile_identity.computer() + } + + pub fn os_version(&self) -> &str { + &self.os_version + } + + pub fn client_version(&self) -> &str { + &self.client_version + } + + pub fn host_identity(&self) -> &HostIdentity { + &self.host_identity + } + + pub fn user_agent(&self) -> &str { + &self.user_agent + } + + pub fn webview_user_agent(&self) -> WebviewUserAgent { + if self.is_native() { + WebviewUserAgent::Native { + prefix: self.user_agent.clone(), + transform: target::webview_user_agent_transform(self.client_os), + } + } else { + WebviewUserAgent::Projected { + prefix: self.user_agent.clone(), + default_user_agent: target::webview_user_agent_default(self.client_os).to_string(), + } + } + } + + pub fn host_id(&self) -> &str { + self.profile_identity.host_id() + } + + pub fn serialno(&self) -> &str { + self.profile_identity.serialno() + } + + pub fn mac_addr(&self) -> &str { + self.profile_identity.mac_addr() + } + + /// Returns true when the target client OS matches the runtime OS. + /// + /// Used to decide whether to consult real OS-level state (e.g. the actual + /// network interface) versus simulated values for emulation. + pub fn is_native(&self) -> bool { + self.runtime_os == self.client_os + } + + /// Default software version string for the target OS, matching the + /// official client values. + pub fn software_version(&self) -> &str { + &self.software_version + } + + // ─── Behavioral methods ────────────────────────────────────────────────── + + pub(crate) fn prelogin_param_location(&self) -> PreloginParamLocation { + target::prelogin_param_location(self.client_os) + } + + pub(crate) fn portal_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str { + match browser_mode { + PreloginBrowserMode::Embedded => "-10", + PreloginBrowserMode::External => target::external_browser_os_value(self.client_os), + } + } + + pub(crate) fn gateway_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str { + match browser_mode { + PreloginBrowserMode::Embedded => "0", + PreloginBrowserMode::External => target::external_browser_os_value(self.client_os), + } + } + + pub(crate) fn saml_password(&self) -> &'static str { + target::saml_password(self.client_os) + } + + pub(crate) fn gateway_server_uses_resolved_ipv4(&self) -> bool { + true + } + + pub(crate) fn supports_macos_plist_csc(&self) -> bool { + target::supports_macos_plist_csc(self.client_os) + } + + pub(crate) fn supports_linux_process_csc(&self) -> bool { + target::supports_linux_process_csc(self.client_os) + } + + pub(crate) fn supports_windows_registry_csc(&self) -> bool { + target::supports_windows_registry_csc(self.client_os) + } + + pub(crate) fn kerberos_support_in_query(&self) -> bool { + target::kerberos_support_in_query(self.client_os) + } + + pub fn os_vendor(&self) -> &'static str { + self.os_vendor + } +} + +// ─── OsProfileBuilder ──────────────────────────────────────────────────────── + +#[derive(Debug, Clone)] +pub struct OsProfileBuilder { + pub(super) client_os: ClientOs, + pub(super) client_version: Option, + pub(super) os_version_override: Option, + pub(super) computer_name_override: Option, + pub(super) host_identity: Option, + pub(super) user_agent: Option, +} + +impl OsProfileBuilder { + pub fn new(client_os: ClientOs) -> Self { + Self { + client_os, + client_version: None, + os_version_override: None, + computer_name_override: None, + host_identity: None, + user_agent: None, + } + } + + pub fn computer_name_override(mut self, name: impl Into) -> Self { + self.computer_name_override = Some(name.into()); + self + } + + pub fn client_version(mut self, version: impl Into) -> Self { + self.client_version = Some(version.into()); + self + } + + /// Preserve an explicitly negotiated operating system version. + pub fn os_version(mut self, version: impl Into) -> Self { + let version = version.into(); + self.os_version_override = if version.trim().is_empty() { None } else { Some(version) }; + self + } + + pub fn host_identity(mut self, identity: HostIdentity) -> Self { + self.host_identity = Some(identity); + self + } + + pub fn user_agent(mut self, ua: impl Into) -> Self { + let ua = ua.into(); + self.user_agent = if ua.trim().is_empty() { None } else { Some(ua) }; + self + } + + /// Project supplied host facts without inspecting the machine running this code. + pub fn build(self, snapshot: HostSnapshot) -> OsProfile { + let (os_version, software_version) = if self.client_os == snapshot.runtime_os { + (snapshot.os_version, snapshot.software_version) + } else { + ( + defaults::os_version(self.client_os), + defaults::software_version(self.client_os), + ) + }; + let identity = self.host_identity.clone().unwrap_or(snapshot.identity); + self.finish(snapshot.runtime_os, identity, os_version, software_version) + } + + fn finish( + self, + runtime_os: ClientOs, + host_identity: HostIdentity, + default_os_version: String, + software_version: String, + ) -> OsProfile { + let client_version = self + .client_version + .filter(|version| !version.trim().is_empty()) + .unwrap_or_else(|| self.client_os.default_client_version().into()); + let profile_identity = + ProfileHostIdentity::for_client_os(runtime_os, self.client_os, &host_identity, self.computer_name_override); + let os_version = self.os_version_override.unwrap_or(default_os_version); + let user_agent = self + .user_agent + .unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})")); + OsProfile { + client_os: self.client_os, + runtime_os, + os_version, + software_version, + os_vendor: target::os_vendor(self.client_os), + client_version, + host_identity, + profile_identity, + user_agent, + } + } +} diff --git a/crates/gpapi/src/os_profile/projection.rs b/crates/gpapi/src/os_profile/projection.rs new file mode 100644 index 0000000..6eee585 --- /dev/null +++ b/crates/gpapi/src/os_profile/projection.rs @@ -0,0 +1,171 @@ +use super::*; +fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String { + use uuid::Uuid; + + let namespace = Uuid::NAMESPACE_DNS; + let name = format!("{}-{}", seed, parts.join("-")); + + Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string() +} + +fn derived_profile_mac(seed: &str, client_os: ClientOs) -> String { + let uuid = derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), "mac"]); + let compact = uuid.replace('-', ""); + let bytes = compact + .as_bytes() + .chunks(2) + .take(6) + .map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase()) + .collect::>(); + + match client_os { + ClientOs::Linux | ClientOs::Windows => bytes.join("-"), + ClientOs::Mac | ClientOs::Ios => bytes.join(":"), + } +} + +fn compact_uuid(seed: &str, client_os: ClientOs, suffix: &str) -> String { + derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), suffix]) + .replace('-', "") + .to_uppercase() +} + +pub(super) fn project( + runtime_os: ClientOs, + client_os: ClientOs, + host_identity: &HostIdentity, + computer_override: Option, +) -> ProfileHostIdentity { + if client_os == runtime_os { + return native::project(client_os, host_identity, computer_override); + } + + match client_os { + ClientOs::Linux => linux::project(host_identity, computer_override), + ClientOs::Windows => windows::project(host_identity, computer_override), + ClientOs::Mac => macos::project(host_identity, computer_override), + ClientOs::Ios => native::project(client_os, host_identity, computer_override), + } +} + +fn computer(host_identity: &HostIdentity, computer_override: Option) -> String { + computer_override + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| host_identity.computer().to_string()) +} + +fn profile_mac_for(client_os: ClientOs, mac_address: &str) -> String { + match client_os { + ClientOs::Linux | ClientOs::Windows => mac_address.replace(':', "-"), + ClientOs::Mac | ClientOs::Ios => mac_address.replace('-', ":"), + } +} + +mod native { + use super::*; + + pub(super) fn project( + client_os: ClientOs, + host_identity: &HostIdentity, + computer_override: Option, + ) -> ProfileHostIdentity { + ProfileHostIdentity { + computer: computer(host_identity, computer_override), + host_id: match client_os { + ClientOs::Mac => host_identity.host_id().replace('-', ":"), + ClientOs::Linux | ClientOs::Windows | ClientOs::Ios => host_identity.host_id().to_string(), + }, + serial_number: host_identity.serialno().to_string(), + mac_address: profile_mac_for(client_os, host_identity.mac_addr()), + } + } +} + +mod linux { + use super::*; + + pub(super) fn project(host_identity: &HostIdentity, computer_override: Option) -> ProfileHostIdentity { + let seed = host_identity.host_id(); + let host_id = derive_uuid_from_seed(seed, &["os-profile", ClientOs::Linux.as_str(), "host-id"]); + ProfileHostIdentity { + computer: computer(host_identity, computer_override), + serial_number: serial_number::vmware_from_uuid(&host_id).expect("projected Linux host ID should be a UUID"), + host_id, + mac_address: derived_profile_mac(seed, ClientOs::Linux), + } + } +} + +mod windows { + use super::*; + + pub(super) fn project(host_identity: &HostIdentity, computer_override: Option) -> ProfileHostIdentity { + let seed = host_identity.host_id(); + ProfileHostIdentity { + computer: computer(host_identity, computer_override), + host_id: derive_uuid_from_seed(seed, &["os-profile", ClientOs::Windows.as_str(), "host-id"]), + serial_number: serial_number::vmware_from_compact_hex(&compact_uuid(seed, ClientOs::Windows, "serialno")) + .expect("projected Windows serial seed should be compact hex"), + mac_address: derived_profile_mac(seed, ClientOs::Windows), + } + } +} + +mod macos { + use super::*; + + pub(super) fn project(host_identity: &HostIdentity, computer_override: Option) -> ProfileHostIdentity { + let seed = host_identity.host_id(); + let mac_address = derived_profile_mac(seed, ClientOs::Mac); + ProfileHostIdentity { + computer: computer(host_identity, computer_override), + host_id: mac_address.clone(), + serial_number: compact_uuid(seed, ClientOs::Mac, "serialno").chars().take(10).collect(), + mac_address, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn host_identity() -> HostIdentity { + HostIdentity::from_parts( + "real-computer".to_string(), + "real-host-id".to_string(), + "real-serial".to_string(), + "aa:bb:cc:dd:ee:ff".to_string(), + ) + } + + #[test] + fn native_linux_projection_uses_real_identity_with_dash_mac() { + let profile = native::project(ClientOs::Linux, &host_identity(), None); + + assert_eq!(profile.computer(), "real-computer"); + assert_eq!(profile.host_id(), "real-host-id"); + assert_eq!(profile.serialno(), "real-serial"); + assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff"); + } + + #[test] + fn native_windows_projection_uses_real_identity_with_dash_mac() { + let profile = native::project(ClientOs::Windows, &host_identity(), None); + + assert_eq!(profile.computer(), "real-computer"); + assert_eq!(profile.host_id(), "real-host-id"); + assert_eq!(profile.serialno(), "real-serial"); + assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff"); + } + + #[test] + fn native_macos_projection_uses_real_identity_with_colon_mac() { + let profile = native::project(ClientOs::Mac, &host_identity(), None); + + assert_eq!(profile.computer(), "real-computer"); + assert_eq!(profile.host_id(), "real:host:id"); + assert_eq!(profile.serialno(), "real-serial"); + assert_eq!(profile.mac_addr(), "aa:bb:cc:dd:ee:ff"); + } +} diff --git a/crates/gpapi/src/os_profile/tests.rs b/crates/gpapi/src/os_profile/tests.rs new file mode 100644 index 0000000..6d9bb36 --- /dev/null +++ b/crates/gpapi/src/os_profile/tests.rs @@ -0,0 +1,634 @@ +use super::*; + +#[test] +fn negotiated_os_version_is_used_in_profile_and_user_agent() { + let identity = HostIdentity::from_parts( + "device".into(), + "host".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ); + let profile = OsProfileBuilder::new(ClientOs::Mac) + .host_identity(identity) + .client_version("6.3.3") + .os_version("negotiated-system-version") + .build(test_snapshot()); + assert_eq!(profile.os_version(), "negotiated-system-version"); + assert!(profile.user_agent().contains("negotiated-system-version")); +} + +#[test] +fn csc_support_defaults_match_official_profiles() { + assert!(!ClientOs::Linux.default_csc_support()); + assert!(ClientOs::Mac.default_csc_support()); + assert!(ClientOs::Windows.default_csc_support()); +} + +#[test] +fn prelogin_param_location_matches_official_profiles() { + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .prelogin_param_location(), + PreloginParamLocation::Body + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .prelogin_param_location(), + PreloginParamLocation::Body + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .prelogin_param_location(), + PreloginParamLocation::Query + ); +} + +#[test] +fn embedded_portal_default_browser_is_minus_ten_for_all() { + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .portal_default_browser(PreloginBrowserMode::Embedded), + "-10" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .portal_default_browser(PreloginBrowserMode::Embedded), + "-10" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .portal_default_browser(PreloginBrowserMode::Embedded), + "-10" + ); +} + +#[test] +fn embedded_gateway_default_browser_is_zero_for_all() { + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .gateway_default_browser(PreloginBrowserMode::Embedded), + "0" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .gateway_default_browser(PreloginBrowserMode::Embedded), + "0" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .gateway_default_browser(PreloginBrowserMode::Embedded), + "0" + ); +} + +#[test] +fn external_default_browser_values_match_official_profiles() { + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .portal_default_browser(PreloginBrowserMode::External), + "4" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .portal_default_browser(PreloginBrowserMode::External), + "3" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .portal_default_browser(PreloginBrowserMode::External), + "2" + ); + + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .gateway_default_browser(PreloginBrowserMode::External), + "4" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .gateway_default_browser(PreloginBrowserMode::External), + "3" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .gateway_default_browser(PreloginBrowserMode::External), + "2" + ); +} + +#[test] +fn saml_password_matches_official_profiles() { + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .saml_password(), + "SAMLPASS" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .saml_password(), + "" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .saml_password(), + "" + ); +} + +#[test] +fn gateway_server_uses_resolved_ipv4_for_all() { + assert!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .gateway_server_uses_resolved_ipv4() + ); + assert!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .gateway_server_uses_resolved_ipv4() + ); + assert!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .gateway_server_uses_resolved_ipv4() + ); +} + +#[test] +fn kerberos_support_in_query_matches_official_profiles() { + assert!( + !OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .kerberos_support_in_query() + ); + assert!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .kerberos_support_in_query() + ); + assert!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .kerberos_support_in_query() + ); +} + +#[test] +fn os_vendor_matches_official_profiles() { + assert_eq!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .os_vendor(), + "Linux" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Mac).build(test_snapshot()).os_vendor(), + "Apple" + ); + assert_eq!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .os_vendor(), + "Microsoft" + ); +} + +#[test] +fn supports_macos_plist_csc_only_for_mac() { + assert!( + !OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .supports_macos_plist_csc() + ); + assert!( + OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .supports_macos_plist_csc() + ); + assert!( + !OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .supports_macos_plist_csc() + ); +} + +#[test] +fn supports_linux_process_csc_only_for_linux() { + assert!( + OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .supports_linux_process_csc() + ); + assert!( + !OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .supports_linux_process_csc() + ); + assert!( + !OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .supports_linux_process_csc() + ); +} + +#[test] +fn supports_windows_registry_csc_only_for_windows() { + assert!( + !OsProfileBuilder::new(ClientOs::Linux) + .build(test_snapshot()) + .supports_windows_registry_csc() + ); + assert!( + !OsProfileBuilder::new(ClientOs::Mac) + .build(test_snapshot()) + .supports_windows_registry_csc() + ); + assert!( + OsProfileBuilder::new(ClientOs::Windows) + .build(test_snapshot()) + .supports_windows_registry_csc() + ); +} + +// ─── User Agent Tests ─────────────────────────────────────────────────────── + +#[test] +fn user_agent_derived_format_without_override() { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .build(test_snapshot()); + + assert_eq!( + profile.user_agent(), + format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux)) + ); +} + +#[test] +fn user_agent_explicit_override_returns_custom_value() { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .user_agent("custom/1.0") + .build(test_snapshot()); + + assert_eq!(profile.user_agent(), "custom/1.0"); +} + +#[test] +fn user_agent_empty_override_falls_back_to_derived() { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .user_agent("") + .build(test_snapshot()); + + assert_eq!( + profile.user_agent(), + format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux)) + ); +} + +#[test] +fn user_agent_whitespace_only_override_falls_back_to_derived() { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .user_agent(" ") + .build(test_snapshot()); + + assert_eq!( + profile.user_agent(), + format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux)) + ); +} + +#[test] +fn user_agent_derived_is_non_empty_for_all_client_os_variants() { + for client_os in [ClientOs::Linux, ClientOs::Windows, ClientOs::Mac] { + let profile = OsProfileBuilder::new(client_os).build(test_snapshot()); + assert!( + !profile.user_agent().is_empty(), + "user_agent() should be non-empty for {:?}", + client_os + ); + } +} + +#[test] +fn native_webview_user_agent_uses_native_default() { + let profile = OsProfileBuilder::new(ClientOs::Mac).build(test_snapshot()); + let user_agent = profile.webview_user_agent(); + + assert_eq!( + user_agent, + WebviewUserAgent::Native { + prefix: profile.user_agent().to_string(), + transform: target::webview_user_agent_transform(ClientOs::Mac) + } + ); +} + +#[test] +fn projected_linux_webview_user_agent_uses_linux_default() { + if ClientOs::Mac == ClientOs::Linux { + return; + } + + let client_os = ClientOs::Linux; + let profile = OsProfileBuilder::new(client_os).build(test_snapshot()); + let user_agent = profile.webview_user_agent(); + + assert_eq!( + user_agent, + WebviewUserAgent::Projected { + prefix: profile.user_agent().to_string(), + default_user_agent: DEFAULT_LINUX_WEBVIEW_USER_AGENT.to_string() + } + ); +} + +#[test] +fn projected_macos_webview_user_agent_uses_macos_default() { + if ClientOs::Mac == ClientOs::Mac { + return; + } + + let client_os = ClientOs::Mac; + let profile = OsProfileBuilder::new(client_os).build(test_snapshot()); + let user_agent = profile.webview_user_agent(); + + assert_eq!( + user_agent, + WebviewUserAgent::Projected { + prefix: profile.user_agent().to_string(), + default_user_agent: DEFAULT_MACOS_WEBVIEW_USER_AGENT.to_string() + } + ); +} + +#[test] +fn projected_windows_webview_user_agent_uses_windows_default() { + if ClientOs::Mac == ClientOs::Windows { + return; + } + + let client_os = ClientOs::Windows; + let profile = OsProfileBuilder::new(client_os).build(test_snapshot()); + let user_agent = profile.webview_user_agent(); + + assert_eq!( + user_agent, + WebviewUserAgent::Projected { + prefix: profile.user_agent().to_string(), + default_user_agent: DEFAULT_WINDOWS_WEBVIEW_USER_AGENT.to_string() + } + ); +} + +#[test] +fn os_version_strings_match_profiles() { + assert!(defaults::os_version(ClientOs::Linux).starts_with("Linux ")); + assert!(defaults::os_version(ClientOs::Mac).starts_with("Apple Mac OS X ")); + assert!(defaults::os_version(ClientOs::Windows).starts_with("Microsoft ")); + assert_eq!(defaults::software_version(ClientOs::Linux), ""); + assert!(!defaults::software_version(ClientOs::Mac).is_empty()); + assert!(!defaults::software_version(ClientOs::Windows).is_empty()); +} + +#[test] +fn builder_fills_defaults_when_nothing_specified() { + let profile = OsProfileBuilder::new(ClientOs::Linux).build(test_snapshot()); + + assert_eq!(profile.client_os(), ClientOs::Linux); + assert!(!profile.computer().is_empty()); + assert!(profile.os_version().starts_with("Linux ")); + assert_eq!(profile.client_version(), GP_CLIENT_VERSION_LINUX); + assert!(!profile.host_id().is_empty()); +} + +#[test] +fn builder_uses_explicit_values_when_provided() { + let identity = HostIdentity::from_parts( + "identity-computer".to_string(), + "test-host-id".to_string(), + "test-serial".to_string(), + "aa:bb:cc:dd:ee:ff".to_string(), + ); + let profile = OsProfileBuilder::new(ClientOs::Mac) + .computer_name_override("MyMac") + .client_version("6.2.0-100") + .host_identity(identity.clone()) + .build(test_snapshot()); + + assert_eq!(profile.client_os(), ClientOs::Mac); + assert_eq!(profile.computer(), "MyMac"); + assert!(profile.os_version().starts_with("Apple Mac OS X ")); + assert_eq!(profile.client_version(), "6.2.0-100"); + assert_eq!(profile.host_identity(), &identity); + assert!(!profile.host_id().is_empty()); + assert!(!profile.serialno().is_empty()); + assert!(!profile.mac_addr().is_empty()); +} + +#[test] +fn builder_ignores_empty_strings() { + let profile = OsProfileBuilder::new(ClientOs::Windows) + .computer_name_override("") + .client_version("") + .build(test_snapshot()); + + // Should fall back to defaults, not use empty strings + assert!(!profile.computer().is_empty()); + assert!(profile.os_version().starts_with("Microsoft ")); + assert_eq!(profile.client_version(), GP_CLIENT_VERSION_WINDOWS); +} + +#[test] +fn identity_accessors_delegate_to_host_identity() { + let identity = HostIdentity::from_parts( + "test-computer".to_string(), + "host-123".to_string(), + "serial-456".to_string(), + "11:22:33:44:55:66".to_string(), + ); + let profile = OsProfileBuilder::new(ClientOs::Mac) + .host_identity(identity) + .build(test_snapshot()); + + assert!(!profile.host_id().is_empty()); + assert_eq!(profile.serialno(), "serial-456"); + assert!(!profile.mac_addr().is_empty()); +} + +#[test] +fn local_hostname_override_changes_only_projected_computer() { + let identity = HostIdentity::from_parts( + "real-computer".to_string(), + "real-host-id".to_string(), + "real-serial".to_string(), + "11:22:33:44:55:66".to_string(), + ); + + let profile = OsProfileBuilder::new(ClientOs::Mac) + .host_identity(identity) + .computer_name_override("profile-computer") + .build(test_snapshot()); + + assert_eq!(profile.computer(), "profile-computer"); + assert_eq!(profile.host_identity().computer(), "real-computer"); +} + +#[test] +fn simulated_profile_identity_is_derived_from_real_host_id() { + let client_os = non_native_client_os(); + let identity = HostIdentity::from_parts( + "real-computer".to_string(), + "stable-real-host-id".to_string(), + "real-serial".to_string(), + "11:22:33:44:55:66".to_string(), + ); + + let first = OsProfileBuilder::new(client_os) + .host_identity(identity.clone()) + .build(test_snapshot()); + let second = OsProfileBuilder::new(client_os) + .host_identity(identity) + .build(test_snapshot()); + + assert_eq!(first.host_identity().host_id(), "stable-real-host-id"); + assert_ne!(first.host_id(), "stable-real-host-id"); + assert_eq!(first.host_id(), second.host_id()); + assert_eq!(first.serialno(), second.serialno()); + assert_eq!(first.mac_addr(), second.mac_addr()); +} + +#[test] +fn simulated_linux_serial_uses_vmware_style_uuid_bytes() { + if ClientOs::Mac == ClientOs::Linux { + return; + } + + let identity = HostIdentity::from_parts( + "real-computer".to_string(), + "stable-real-host-id".to_string(), + "real-serial".to_string(), + "11:22:33:44:55:66".to_string(), + ); + + let profile = OsProfileBuilder::new(ClientOs::Linux) + .host_identity(identity) + .build(test_snapshot()); + + assert!(profile.serialno().starts_with("VMware-")); + assert_eq!( + profile.serialno().len(), + "VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".len() + ); +} + +#[test] +fn profile_os_versions_are_not_host_identity_fields() { + let identity = HostIdentity::from_parts( + "real-computer".to_string(), + "stable-real-host-id".to_string(), + "real-serial".to_string(), + "11:22:33:44:55:66".to_string(), + ); + let profile = OsProfileBuilder::new(ClientOs::Mac) + .host_identity(identity) + .build(test_snapshot()); + let value = serde_json::to_value(profile.host_identity()).unwrap(); + + assert!(value.get("osVersion").is_none()); + assert!(value.get("softwareVersion").is_none()); + assert!(profile.os_version().starts_with("Apple Mac OS X ")); + assert!(!profile.software_version().is_empty()); +} + +fn non_native_client_os() -> ClientOs { + match ClientOs::Mac { + ClientOs::Linux => ClientOs::Mac, + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => ClientOs::Linux, + } +} + +// ─── Property-Based Tests ───────────────────────────────────────────────── + +mod prop_tests { + use super::*; + use proptest::prelude::*; + + // **Validates: Requirements 1.1, 1.2, 1.3, 1.4, 2.3, 12.1, 12.2** + // + // Property 1: Derived user agent format + // For any valid OsProfile built without a user agent override (with arbitrary + // non-empty client_version), user_agent() returns a non-empty string matching + // the format "PAN GlobalProtect/{client_version} ({profile.os_version})". + proptest! { + #[test] + fn derived_user_agent_format( + cv in "\\S{1,50}", + ) { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version(cv.clone()) + .build(test_snapshot()); + + let expected = format!("PAN GlobalProtect/{} ({})", cv, profile.os_version()); + prop_assert_eq!(profile.user_agent(), expected.as_str()); + prop_assert!(!profile.user_agent().is_empty()); + } + } + + // **Validates: Requirements 2.2, 12.3** + // + // Property 2: Override returns verbatim + // For any non-whitespace-only string provided to OsProfileBuilder::user_agent(), + // the resulting OsProfile::user_agent() returns the exact input. + proptest! { + #[test] + fn override_returns_verbatim(ua in "[^\\s][\\s\\S]{0,49}") { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .user_agent(ua.clone()) + .build(test_snapshot()); + + prop_assert_eq!(profile.user_agent(), ua.as_str()); + } + } + + // **Validates: Requirements 2.4** + // + // Property 3: Whitespace override falls back to derived + // For any string composed entirely of whitespace characters provided to + // OsProfileBuilder::user_agent(), the resulting OsProfile::user_agent() + // returns the derived format (not the whitespace string). + proptest! { + #[test] + fn whitespace_override_falls_back_to_derived(ws in "[ \\t\\n]{1,20}") { + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .user_agent(ws.clone()) + .build(test_snapshot()); + + // The result must be the derived format, not the whitespace string + let expected = format!("PAN GlobalProtect/6.0.0 ({})", profile.os_version()); + prop_assert_eq!(profile.user_agent(), expected.as_str()); + prop_assert_ne!(profile.user_agent(), ws.as_str()); + } + } +} diff --git a/crates/gpapi/src/params/gateway_login.rs b/crates/gpapi/src/params/gateway_login.rs index 303003b..19640d7 100644 --- a/crates/gpapi/src/params/gateway_login.rs +++ b/crates/gpapi/src/params/gateway_login.rs @@ -1,7 +1,7 @@ use std::net::ToSocketAddrs; use super::{RequestParams, credential as credential_params}; -use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams}; +use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams, os_profile::ClientOs}; /// Inputs required to build gateway login request parameters. pub(crate) struct GatewayLoginInput<'a> { @@ -17,7 +17,7 @@ pub(crate) struct GatewayLoginInput<'a> { /// /// Resolves the `server` parameter to an IPv4 address when /// `profile.gateway_server_uses_resolved_ipv4()` is true. -/// Sets `gw` and `gateway-name` to the gateway FQDN. +/// iOS uses the portal gateway name for `gw` and `gateway-name`; desktop profiles use its FQDN. pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams { let profile = input.gp_params.os_profile(); let mut body: Vec<(String, String)> = Vec::new(); @@ -51,6 +51,10 @@ pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams { // Identity fields body.push(("host-id".into(), profile.host_id().into())); + if profile.client_os() == ClientOs::Ios { + body.push(("mobile-id".into(), profile.host_id().into())); + body.push(("vpn-type".into(), "App Level VPN".into())); + } body.push(("serialno".into(), profile.serialno().into())); body.push(("preferred-ip".into(), String::new())); body.push(("preferred-ipv6".into(), String::new())); @@ -64,8 +68,13 @@ pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams { if let Some(context) = input.context { let gateway_host = context.host().to_string(); body.push(("host".into(), gateway_host.clone())); - body.push(("gw".into(), gateway_host.clone())); - body.push(("gateway-name".into(), gateway_host)); + let gateway_name = if profile.client_os() == ClientOs::Ios { + context.name().to_owned() + } else { + gateway_host + }; + body.push(("gw".into(), gateway_name.clone())); + body.push(("gateway-name".into(), gateway_name)); body.push(("internal".into(), context.kind().as_login_param().to_string())); body.push(( "selection-type".into(), @@ -141,8 +150,39 @@ mod tests { os_profile::{ClientOs, HostIdentity, OsProfile}, }; + #[test] + fn mobile_login_fields_and_gateway_names_are_ios_only() { + for os in [ClientOs::Ios, ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] { + let params = GpParams::builder(test_profile(os)).build(); + let gateway = Gateway::new("Regional_Gateway".into(), "192.0.2.1".into()); + let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual); + let cred = make_credential(); + let result = build(&GatewayLoginInput { + gp_params: ¶ms, + cred: &cred, + gateway_host: "192.0.2.1", + context: Some(&context), + client_ip: Some("192.0.2.2"), + extend_lifetime: false, + }); + let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()); + assert_eq!(find("host"), Some("192.0.2.1")); + if os == ClientOs::Ios { + assert_eq!(find("mobile-id"), Some(params.os_profile().host_id())); + assert_eq!(find("vpn-type"), Some("App Level VPN")); + assert_eq!(find("gw"), Some("Regional_Gateway")); + assert_eq!(find("gateway-name"), Some("Regional_Gateway")); + } else { + assert_eq!(find("mobile-id"), None); + assert_eq!(find("vpn-type"), None); + assert_eq!(find("gw"), Some("192.0.2.1")); + assert_eq!(find("gateway-name"), Some("192.0.2.1")); + } + } + } + fn test_identity() -> HostIdentity { - HostIdentity::new( + HostIdentity::from_parts( "test-computer".to_string(), "host-id-123".to_string(), "serial-456".to_string(), @@ -151,7 +191,9 @@ mod tests { } fn test_profile(os: ClientOs) -> OsProfile { - OsProfile::builder(os).host_identity(test_identity()).build() + OsProfile::builder(os) + .host_identity(test_identity()) + .build(crate::os_profile::test_snapshot()) } fn make_gp_params() -> GpParams { diff --git a/crates/gpapi/src/params/gateway_prelogin.rs b/crates/gpapi/src/params/gateway_prelogin.rs index bc85a19..c05739a 100644 --- a/crates/gpapi/src/params/gateway_prelogin.rs +++ b/crates/gpapi/src/params/gateway_prelogin.rs @@ -40,7 +40,7 @@ mod tests { #[test] fn linux_places_params_in_body() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); assert!(!result.body.is_empty()); @@ -49,7 +49,7 @@ mod tests { #[test] fn mac_places_params_in_body_with_kerberos_query() { - let profile = OsProfile::builder(ClientOs::Mac).build(); + let profile = OsProfile::builder(ClientOs::Mac).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); assert!(!result.body.is_empty()); @@ -59,7 +59,7 @@ mod tests { #[test] fn windows_places_all_params_in_query() { - let profile = OsProfile::builder(ClientOs::Windows).build(); + let profile = OsProfile::builder(ClientOs::Windows).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); assert!(result.body.is_empty()); @@ -69,7 +69,7 @@ mod tests { #[test] fn uses_embedded_gateway_default_browser_value() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let browser_param = result @@ -82,7 +82,7 @@ mod tests { #[test] fn uses_target_value_when_external_browser_is_requested() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::External); let browser_param = result @@ -95,7 +95,7 @@ mod tests { #[test] fn includes_all_required_params() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect(); @@ -112,7 +112,7 @@ mod tests { #[test] fn data_param_is_cas_embedded_browser_base64() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let data_param = result diff --git a/crates/gpapi/src/params/portal_getconfig.rs b/crates/gpapi/src/params/portal_getconfig.rs index 4559556..f34e052 100644 --- a/crates/gpapi/src/params/portal_getconfig.rs +++ b/crates/gpapi/src/params/portal_getconfig.rs @@ -11,7 +11,7 @@ use crate::{credential::Credential, gp_params::GpParams, os_profile::ClientOs, p /// and left empty on macOS/Windows, matching official client behavior. pub(crate) fn build(cred: &Credential, gp_params: &GpParams, server: &str) -> RequestParams { let profile = gp_params.os_profile(); - let nonce = if profile.client_os() == ClientOs::Linux { + let nonce = if matches!(profile.client_os(), ClientOs::Linux | ClientOs::Ios) { "0".to_string() } else { swg_nonce() @@ -58,17 +58,37 @@ mod tests { os_profile::{ClientOs, HostIdentity, OsProfile}, }; + #[test] + fn ios_uses_zero_swg_nonce_without_changing_desktop_profiles() { + for os in [ClientOs::Ios, ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] { + let params = GpParams::builder(test_profile(os)).build(); + let result = build(&password_cred(), ¶ms, "vpn.example.com"); + let nonce = result + .body + .iter() + .find(|(key, _)| key == "swg-nonce") + .unwrap() + .1 + .as_str(); + if matches!(os, ClientOs::Ios | ClientOs::Linux) { + assert_eq!(nonce, "0"); + } else { + assert_ne!(nonce, "0"); + } + } + } + fn test_profile(os: ClientOs) -> OsProfile { OsProfile::builder(os) .computer_name_override("test-computer") .client_version("6.3.3-100") - .host_identity(HostIdentity::new( + .host_identity(HostIdentity::from_parts( "test-computer".into(), "test-host-id".into(), "test-serial".into(), "aa:bb:cc:dd:ee:ff".into(), )) - .build() + .build(crate::os_profile::test_snapshot()) } fn password_cred() -> Credential { diff --git a/crates/gpapi/src/params/portal_prelogin.rs b/crates/gpapi/src/params/portal_prelogin.rs index 8bed47e..ee7cccf 100644 --- a/crates/gpapi/src/params/portal_prelogin.rs +++ b/crates/gpapi/src/params/portal_prelogin.rs @@ -44,7 +44,7 @@ mod tests { #[test] fn linux_places_params_in_body() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); assert!(!result.body.is_empty()); @@ -53,7 +53,7 @@ mod tests { #[test] fn mac_places_params_in_body_with_kerberos_query() { - let profile = OsProfile::builder(ClientOs::Mac).build(); + let profile = OsProfile::builder(ClientOs::Mac).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); assert!(!result.body.is_empty()); @@ -63,7 +63,7 @@ mod tests { #[test] fn windows_places_all_params_in_query() { - let profile = OsProfile::builder(ClientOs::Windows).build(); + let profile = OsProfile::builder(ClientOs::Windows).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); assert!(result.body.is_empty()); @@ -73,7 +73,7 @@ mod tests { #[test] fn uses_embedded_portal_default_browser_value() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let browser_param = result @@ -86,7 +86,7 @@ mod tests { #[test] fn uses_target_value_when_external_browser_is_requested() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::External); let browser_param = result @@ -99,7 +99,7 @@ mod tests { #[test] fn includes_all_required_params() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect(); @@ -116,7 +116,7 @@ mod tests { #[test] fn data_param_is_cas_embedded_browser_base64() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let data_param = result @@ -129,7 +129,7 @@ mod tests { #[test] fn kerberos_not_in_query_for_linux() { - let profile = OsProfile::builder(ClientOs::Linux).build(); + let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support"); @@ -138,7 +138,7 @@ mod tests { #[test] fn kerberos_in_query_for_windows() { - let profile = OsProfile::builder(ClientOs::Windows).build(); + let profile = OsProfile::builder(ClientOs::Windows).build(crate::os_profile::test_snapshot()); let result = build(&profile, PreloginBrowserMode::Embedded); let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support"); diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 2ef5aec..1d2cf96 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -14,7 +14,7 @@ use crate::{ gateway::{Gateway, parse_gateways}, gp_params::GpParams, params, - session::{InternalSessionPolicy, network::InternalHostDetection}, + session::{InternalHostDetection, InternalSessionPolicy}, utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt}, }; @@ -52,6 +52,37 @@ pub struct PortalConfig { internal_session_policy: Option, } +/// Parsed portal policy before a caller chooses network-location candidates. +pub struct PortalPolicy { + config: PortalConfig, + internal_gateways: Vec, + external_gateways: Vec, +} + +impl PortalPolicy { + pub fn external_gateways(self) -> PortalConfig { + self.select_gateways(false, None) + } + + pub(super) fn detection(&self) -> Option<&InternalHostDetection> { + self.config.internal_detection.as_ref() + } + + pub(super) fn select_gateways(mut self, prefer_internal: bool, detected: Option) -> PortalConfig { + let mut gateways = if prefer_internal { + self.internal_gateways + } else { + self.external_gateways + }; + if gateways.is_empty() { + gateways.push(Gateway::new(self.config.portal.clone(), self.config.portal.clone())); + } + self.config.gateways = gateways; + self.config.internal_host_detection = detected; + self.config + } +} + impl PortalConfig { pub fn portal(&self) -> &str { &self.portal @@ -140,14 +171,13 @@ impl PortalConfig { } } -/// Cancellation is handled inside the request so a running native detection -/// helper is always cancelled and joined. Do not drop this future on disconnect. +/// Retrieve server policy without inspecting local network location. pub async fn retrieve_config( portal: &str, cred: &Credential, gp_params: &GpParams, cancellation: &CancellationToken, -) -> anyhow::Result { +) -> anyhow::Result { let portal = normalize_server(portal)?; let server_url = url::Url::parse(&portal)?; let server = remove_url_scheme(&portal); @@ -181,6 +211,9 @@ pub async fn retrieve_config( if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { return Err(anyhow::anyhow!(tls)); } + if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { + return Err(anyhow::anyhow!(crate::error::AuthenticationRejected)); + } if err.status == StatusCode::NOT_FOUND { bail!(PortalError::ConfigError("Config endpoint not found".to_string())); } @@ -216,11 +249,11 @@ pub async fn retrieve_config( }; 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_config(&server, cred, root, cancellation).await; + return parse_portal_policy(&server, cred, root, cancellation).await; } info!("Portal did not return CSC criteria"); - parse_portal_config(&server, cred, root, cancellation).await + parse_portal_policy(&server, cred, root, cancellation).await } async fn retrieve_csc_config( @@ -287,12 +320,12 @@ fn present(value: Option<&str>) -> &'static str { } } -async fn parse_portal_config( +async fn parse_portal_policy( server: &str, cred: &Credential, root: Element, cancellation: &CancellationToken, -) -> anyhow::Result { +) -> anyhow::Result { let internal_detection = root .descendant("internal-host-detection") .map(parse_internal_detection) @@ -302,22 +335,11 @@ async fn parse_portal_config( None }) .flatten(); - let prefer_internal = match &internal_detection { - Some(detection) => detection.detect(cancellation).await.unwrap_or_else(|error| { - warn!("Internal host detection failed: {error}"); - false - }), - None => false, - }; - if cancellation.is_cancelled() { bail!("Portal configuration cancelled"); } - - let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| { - info!("No gateways found in portal config"); - vec![] - }); + let internal_gateways = parse_gateways(&root, true).unwrap_or_default(); + let external_gateways = parse_gateways(&root, false).unwrap_or_default(); let user_auth_cookie = root.descendant_text("portal-userauthcookie").unwrap_or_default(); let prelogon_user_auth_cookie = root @@ -326,31 +348,29 @@ async fn parse_portal_config( let config_digest = root.descendant_text("config-digest"); let connect_method = parse_connect_method(&root); - if gateways.is_empty() { - gateways.push(Gateway::new(server.to_string(), server.to_string())); - } else { - info!("Found {} gateways in portal config", gateways.len()); - } - let version = root.descendant_text("version").map(|s| s.to_string()); info!("Detected portal version: {:?}", version); let allow_extend_session = parse_allow_extend_session(&root); let default_browser = parse_default_browser(&root); let internal_session_policy = parse_internal_session_policy(&root).ok(); - Ok(PortalConfig { - portal: server.to_string(), - auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie), - config_cred: cred.clone(), - gateways, - connect_method, - config_digest: config_digest.map(|s| s.to_string()), - internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal), - internal_detection, - version, - allow_extend_session, - default_browser, - internal_session_policy, + Ok(PortalPolicy { + internal_gateways, + external_gateways, + config: PortalConfig { + portal: server.to_string(), + auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie), + config_cred: cred.clone(), + gateways: Vec::new(), + connect_method, + config_digest: config_digest.map(|s| s.to_string()), + internal_host_detection: None, + internal_detection, + version, + allow_extend_session, + default_browser, + internal_session_policy, + }, }) } @@ -431,15 +451,54 @@ fn parse_internal_detection(element: &Element) -> anyhow::Result"), + &CancellationToken::new(), + ) + .await + .unwrap(); + let config = policy.select_gateways(detected.unwrap_or(false), detected); + assert_eq!(config.gateways().len(), 1); + assert_eq!(config.gateways()[0].server(), "portal.example"); + assert_eq!(config.internal_host_detection(), detected); + } + } + #[tokio::test] async fn invalid_non_tunnel_policy_does_not_reject_tunnel_candidates() { let root = parse_xml( "invalidinvalidinternal.example", ); let credential = crate::credential::PasswordCredential::new("alice", "password").into(); - let config = parse_portal_config("portal.example", &credential, root, &CancellationToken::new()) + let config = parse_portal_policy("portal.example", &credential, root, &CancellationToken::new()) .await - .unwrap(); + .unwrap() + .external_gateways(); assert!(config.internal_session_policy().is_none()); assert_eq!(config.gateways()[0].server(), "vpn.example"); assert_eq!(config.gateways()[0].kind(), crate::gateway::GatewayKind::External); @@ -482,9 +541,10 @@ mod tests { "fixture-user", "fixture-password", )); - let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new()) + let config = parse_portal_policy("vpn.example.com", &cred, root, &CancellationToken::new()) .await - .unwrap(); + .unwrap() + .external_gateways(); assert_eq!( config.internal_session_policy().unwrap().hip_interval(), std::time::Duration::from_secs(3600) @@ -567,9 +627,10 @@ mod tests { ); let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret")); - let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new()) + let config = parse_portal_policy("vpn.example.com", &cred, root, &CancellationToken::new()) .await - .unwrap(); + .unwrap() + .external_gateways(); assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie"); assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie"); diff --git a/crates/gpapi/src/portal/csc.rs b/crates/gpapi/src/portal/csc.rs index 2a9f394..46eb1b8 100644 --- a/crates/gpapi/src/portal/csc.rs +++ b/crates/gpapi/src/portal/csc.rs @@ -480,13 +480,13 @@ mod tests { fn gp_params(client_os: ClientOs) -> GpParams { let profile = OsProfile::builder(client_os) - .host_identity(HostIdentity::new( + .host_identity(HostIdentity::from_parts( "test-computer".to_string(), "host-id".to_string(), "serial".to_string(), "aa:bb:cc:dd:ee:ff".to_string(), )) - .build(); + .build(crate::os_profile::test_snapshot()); GpParams::builder(profile).build() } diff --git a/crates/gpapi/src/portal/discovery.rs b/crates/gpapi/src/portal/discovery.rs new file mode 100644 index 0000000..01e333b --- /dev/null +++ b/crates/gpapi/src/portal/discovery.rs @@ -0,0 +1,29 @@ +//! Desktop portal discovery: protocol retrieval followed by native location detection. +use super::{PortalConfig, retrieve_config}; +use crate::{credential::Credential, gp_params::GpParams}; +use tokio_util::sync::CancellationToken; + +/// Do not drop this future on disconnect: native detection must cancel and join. +pub async fn discover( + portal: &str, + credential: &Credential, + params: &GpParams, + cancellation: &CancellationToken, +) -> anyhow::Result { + let policy = retrieve_config(portal, credential, params, cancellation).await?; + let detected = match policy.detection() { + Some(detection) => Some( + crate::session::desktop::network::detect(detection, cancellation) + .await + .unwrap_or_else(|error| { + log::warn!("Internal host detection failed: {error}"); + false + }), + ), + None => None, + }; + if cancellation.is_cancelled() { + anyhow::bail!("Portal configuration cancelled"); + } + Ok(policy.select_gateways(detected.unwrap_or(false), detected)) +} diff --git a/crates/gpapi/src/portal/mod.rs b/crates/gpapi/src/portal/mod.rs index aa5ab06..c6f7549 100644 --- a/crates/gpapi/src/portal/mod.rs +++ b/crates/gpapi/src/portal/mod.rs @@ -4,3 +4,6 @@ mod prelogin; pub use config::*; pub use prelogin::*; + +#[cfg(feature = "desktop")] +pub mod discovery; diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index 6de091f..3275807 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -19,6 +19,7 @@ pub struct SamlPrelogin { region: String, is_gateway: bool, saml_request: String, + saml_method: String, support_default_browser: bool, } @@ -27,6 +28,10 @@ impl SamlPrelogin { &self.region } + pub fn saml_method(&self) -> &str { + &self.saml_method + } + pub fn saml_request(&self) -> &str { &self.saml_request } @@ -211,6 +216,11 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result { let saml_default_browser = root.descendant_text("saml-default-browser"); // Check if the prelogin response is SAML if saml_method.is_some() && saml_request.is_some() { + let saml_method = saml_method.unwrap(); + anyhow::ensure!( + matches!(saml_method.as_str(), "REDIRECT" | "POST"), + "Unsupported SAML binding" + ); let saml_request = base64::decode_to_string(&saml_request.unwrap())?; let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false); @@ -218,6 +228,7 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result { region, is_gateway, saml_request, + saml_method, support_default_browser, }; @@ -258,13 +269,13 @@ mod tests { fn gp_params(client_os: ClientOs) -> GpParams { let profile = OsProfile::builder(client_os) - .host_identity(HostIdentity::new( + .host_identity(HostIdentity::from_parts( "test-computer".to_string(), "host-id".to_string(), "serial".to_string(), "aa:bb:cc:dd:ee:ff".to_string(), )) - .build(); + .build(crate::os_profile::test_snapshot()); GpParams::builder(profile).build() } diff --git a/crates/gpapi/src/process/auth_launcher.rs b/crates/gpapi/src/process/auth_launcher.rs index 1919a52..9df60eb 100644 --- a/crates/gpapi/src/process/auth_launcher.rs +++ b/crates/gpapi/src/process/auth_launcher.rs @@ -431,7 +431,9 @@ mod tests { #[test] fn os_profile_sets_os_from_profile() { - let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build(); + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .build(crate::os_profile::test_snapshot()); let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile); @@ -440,7 +442,9 @@ mod tests { #[test] fn os_profile_sets_host_id_from_profile_runtime_identity() { - let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build(); + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .build(crate::os_profile::test_snapshot()); let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile); @@ -449,7 +453,9 @@ mod tests { #[test] fn os_profile_sets_client_version_from_profile() { - let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build(); + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .build(crate::os_profile::test_snapshot()); let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile); diff --git a/crates/gpapi/src/process/collection.rs b/crates/gpapi/src/process/collection.rs index 7f0e946..a53263c 100644 --- a/crates/gpapi/src/process/collection.rs +++ b/crates/gpapi/src/process/collection.rs @@ -3,48 +3,15 @@ use std::{ os::unix::fs::{MetadataExt, PermissionsExt}, path::{Path, PathBuf}, process::{Command, Output, Stdio}, - time::{Duration, Instant}, }; use super::command_runner::run_controlled; -/// Invocation control borrowed by collection; interruption must never be treated -/// as an unavailable optional product. -pub trait CollectionControl { - fn check(&self) -> io::Result<()>; -} - -impl io::Result<()>> CollectionControl for F { - fn check(&self) -> io::Result<()> { - self() - } -} - -pub struct CollectionBudget { - deadline: Instant, -} - -impl CollectionBudget { - pub fn new(timeout: Duration) -> Self { - Self { - deadline: Instant::now() + timeout, - } - } -} - -impl CollectionControl for CollectionBudget { - fn check(&self) -> io::Result<()> { - if Instant::now() >= self.deadline { - Err(io::Error::new( - io::ErrorKind::TimedOut, - "Device information collection timed out", - )) - } else { - Ok(()) - } - } -} - +#[cfg(test)] +use crate::collection::CollectionBudget; +use crate::collection::CollectionControl; +#[cfg(test)] +use std::time::{Duration, Instant}; const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024; const TOOL_DIRECTORIES: &[&str] = &[ "/usr/bin", diff --git a/crates/gpapi/src/process/command_runner.rs b/crates/gpapi/src/process/command_runner.rs index ae83e01..776ca90 100644 --- a/crates/gpapi/src/process/command_runner.rs +++ b/crates/gpapi/src/process/command_runner.rs @@ -12,7 +12,7 @@ use nix::{ unistd::Pid, }; -use super::collection::CollectionControl; +use crate::collection::CollectionControl; /// What the child reads on stdin. pub(crate) enum ChildInput<'a> { diff --git a/crates/gpapi/src/script_tun.rs b/crates/gpapi/src/script_tun.rs index 5abad1f..1387ed1 100644 --- a/crates/gpapi/src/script_tun.rs +++ b/crates/gpapi/src/script_tun.rs @@ -1,4 +1,4 @@ -use crate::session::tunnel::NegotiatedNetwork; +use crate::session::desktop::tunnel::NegotiatedNetwork; use serde::{Deserialize, Serialize}; use std::{io, path::PathBuf}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; @@ -8,7 +8,7 @@ const MAX_MESSAGE: usize = 60 * 1024; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, specta::Type)] pub struct Identity { pub service_instance: Uuid, - #[serde(with = "crate::session::tunnel::decimal")] + #[serde(with = "crate::session::desktop::tunnel::decimal")] #[specta(type = String)] pub attempt: u64, pub launch_id: Uuid, diff --git a/crates/gpapi/src/service/event.rs b/crates/gpapi/src/service/event.rs index c9ad5ee..4ba63c5 100644 --- a/crates/gpapi/src/service/event.rs +++ b/crates/gpapi/src/service/event.rs @@ -5,7 +5,7 @@ use crate::service::{vpn_env::VpnEnv, vpn_state::VpnState}; /// Events that can be emitted by the service #[derive(Debug, Serialize, Deserialize, Clone)] pub enum WsEvent { - TunnelState(Option), + TunnelState(Option), VpnEnv(VpnEnv), VpnState(VpnState), ActiveGui, diff --git a/crates/gpapi/src/service/request.rs b/crates/gpapi/src/service/request.rs index 1582b43..dfe2422 100644 --- a/crates/gpapi/src/service/request.rs +++ b/crates/gpapi/src/service/request.rs @@ -7,7 +7,7 @@ use zeroize::Zeroize; use crate::{ hip::HipSource, os_profile::{ClientOs, HostIdentity, OsProfile}, - session::ConnectionPlan, + session::desktop::ConnectionPlan, }; use super::vpn_state::ConnectInfo; @@ -452,14 +452,14 @@ mod tests { use crate::os_profile::OsProfileBuilder; use crate::{ gateway::Gateway, - session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy}, + session::{GatewayAuthentication, InternalSessionPolicy, desktop::AuthenticatedGateway}, }; fn test_request(info: ConnectInfo) -> ConnectRequest { let plan = ConnectionPlan::new( vec![AuthenticatedGateway { gateway: info.gateway().clone(), - binding: Some(crate::session::network::test_binding()), + binding: Some(crate::session::desktop::network::test_binding()), authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into()) .unwrap(), }], @@ -527,7 +527,9 @@ mod tests { #[test] fn with_os_profile_sets_user_agent_from_profile() { - let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build(); + let profile = OsProfileBuilder::new(ClientOs::Linux) + .client_version("6.0.0") + .build(crate::os_profile::test_snapshot()); let req = test_request(test_connect_info()).with_os_profile(&profile); @@ -536,7 +538,7 @@ mod tests { #[test] fn with_os_profile_sets_host_id_from_profile_runtime_identity() { - let profile = OsProfileBuilder::new(ClientOs::Linux).build(); + let profile = OsProfileBuilder::new(ClientOs::Linux).build(crate::os_profile::test_snapshot()); let req = test_request(test_connect_info()).with_os_profile(&profile); diff --git a/crates/gpapi/src/service/transport/message.rs b/crates/gpapi/src/service/transport/message.rs index b81d492..805e5e7 100644 --- a/crates/gpapi/src/service/transport/message.rs +++ b/crates/gpapi/src/service/transport/message.rs @@ -18,7 +18,7 @@ pub enum ClientMessage { #[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)] pub enum ServerMessage { TunnelStatistics { - snapshot: crate::session::tunnel::TunnelStatisticsSnapshot, + snapshot: crate::session::desktop::tunnel::TunnelStatisticsSnapshot, }, Attached { connection_id: Uuid, @@ -42,7 +42,7 @@ pub enum ServerMessage { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)] pub enum ServiceResult { - TunnelStatisticsSnapshot(crate::session::tunnel::TunnelStatisticsSnapshot), + TunnelStatisticsSnapshot(crate::session::desktop::tunnel::TunnelStatisticsSnapshot), Accepted, StoredHipReport { report_id: String, @@ -171,10 +171,10 @@ mod tests { let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string()); let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]); let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2; - let plan = crate::session::ConnectionPlan::new( - vec![crate::session::AuthenticatedGateway { + let plan = crate::session::desktop::ConnectionPlan::new( + vec![crate::session::desktop::AuthenticatedGateway { gateway: info.gateway().clone(), - binding: Some(crate::session::network::test_binding()), + binding: Some(crate::session::desktop::network::test_binding()), authentication: crate::session::GatewayAuthentication::new( "authcookie=token&user=user".into(), "tunnel".into(), @@ -200,12 +200,13 @@ mod tests { #[test] fn full_configuration_and_large_metadata_fit_complete_snapshot_envelopes_at_the_budget() { use crate::{ - os_profile::HostIdentity, service::{ vpn_env::HostInfo, vpn_state::{ConnectedInfo, VpnState}, }, - session::tunnel::{MAX_CONFIGURATION_BYTES, TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport}, + session::desktop::tunnel::{ + MAX_CONFIGURATION_BYTES, TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport, + }, }; let mut configuration = TunnelConfiguration::default(); configuration.included_routes.items = vec!["r".repeat(1024); 15]; @@ -234,7 +235,7 @@ mod tests { vpnc_script: Some("s".repeat(1024)), auth_executable: "a".repeat(1024), host_info: HostInfo { - host_identity: HostIdentity::collect(), + host_identity: crate::os_profile::desktop::collect_identity(), }, }; for mut message in [ diff --git a/crates/gpapi/src/service/vpn_env.rs b/crates/gpapi/src/service/vpn_env.rs index 3796280..22b75fd 100644 --- a/crates/gpapi/src/service/vpn_env.rs +++ b/crates/gpapi/src/service/vpn_env.rs @@ -18,7 +18,7 @@ pub struct HostInfo { /// to the client so that it can configure itself accordingly. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct VpnEnv { - pub tunnel_state: Option, + pub tunnel_state: Option, /// The VPN connection state pub vpn_state: VpnState, diff --git a/crates/gpapi/src/service/vpn_state.rs b/crates/gpapi/src/service/vpn_state.rs index a07ea7d..0f7d70f 100644 --- a/crates/gpapi/src/service/vpn_state.rs +++ b/crates/gpapi/src/service/vpn_state.rs @@ -5,7 +5,7 @@ use specta::Type; use crate::{ gateway::Gateway, - session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo}, + session::{GatewaySessionSummary, SessionInfo, desktop::GatewayFailureSummary}, }; #[derive(Debug, Deserialize, Serialize, Type, Clone)] diff --git a/crates/gpapi/src/session.rs b/crates/gpapi/src/session.rs index a9a2468..77ebc63 100644 --- a/crates/gpapi/src/session.rs +++ b/crates/gpapi/src/session.rs @@ -5,13 +5,12 @@ use serde::{Deserialize, Serialize}; use specta::Type; mod connection; -mod gateway_sessions; -pub mod network; -pub mod non_tunnel; +mod detection; +pub use detection::InternalHostDetection; +#[cfg(feature = "desktop")] +pub mod desktop; pub mod transport; -pub mod tunnel; pub use connection::*; -pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions}; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] pub struct SessionWarning { diff --git a/crates/gpapi/src/session/connection.rs b/crates/gpapi/src/session/connection.rs index ba150f2..cc8bbec 100644 --- a/crates/gpapi/src/session/connection.rs +++ b/crates/gpapi/src/session/connection.rs @@ -145,130 +145,6 @@ impl TryFrom for InternalSessionPolicy { } } -#[derive(Debug, Clone, Serialize, Deserialize, Type)] -pub struct AuthenticatedGateway { - pub gateway: Gateway, - pub authentication: GatewayAuthentication, - pub binding: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub enum GatewayFailure { - AuthenticationRejected, - Unreachable, - TunnelFailed, -} - -#[derive(Debug, Clone, Serialize, Deserialize, Type)] -pub struct GatewayFailureSummary { - pub gateway: Gateway, - pub failure: GatewayFailure, -} - -/// Credentials remain in the interactive authentication owner; only issued -/// gateway cookies cross the runtime/service boundary. -#[derive(Debug, Clone, Serialize, Deserialize, Type)] -#[serde(try_from = "ConnectionPlanFields")] -pub struct ConnectionPlan { - members: Vec, - failures: Vec, - policy: InternalSessionPolicy, - internal_detection: Option, -} - -#[derive(Deserialize)] -struct ConnectionPlanFields { - members: Vec, - failures: Vec, - policy: InternalSessionPolicy, - internal_detection: Option, -} - -impl TryFrom for ConnectionPlan { - type Error = anyhow::Error; - - fn try_from(fields: ConnectionPlanFields) -> Result { - Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection)) - } -} - -impl ConnectionPlan { - pub fn new( - members: Vec, - failures: Vec, - policy: InternalSessionPolicy, - ) -> anyhow::Result { - ensure!(!members.is_empty(), "Connection plan has no authenticated gateways"); - ensure!( - members.len() <= 64 && failures.len() <= 64, - "Connection plan exceeds its gateway limit" - ); - let mode = members[0].authentication.mode(); - ensure!( - members.iter().all(|member| member.authentication.mode() == mode), - "Mixed tunnel and non-tunnel sessions are unsupported" - ); - ensure!( - mode != SessionMode::NonTunnel - || members - .iter() - .all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal), - "Non-tunnel sessions require freshly discovered internal gateways" - ); - ensure!( - members.len() == 1 - || members - .iter() - .all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal), - "Multiple authenticated gateways require an internal connection" - ); - let mut hosts = std::collections::HashSet::new(); - for member in &members { - if mode == SessionMode::NonTunnel { - let binding = member - .binding - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Non-tunnel session has no physical binding"))?; - binding.validate_server(member.gateway.server())?; - } - let host = crate::utils::normalize_server(member.gateway.server())?; - ensure!(hosts.insert(host), "Connection plan has duplicate gateways"); - } - Ok(Self { - members, - failures, - policy, - internal_detection: None, - }) - } - - pub fn members(&self) -> &[AuthenticatedGateway] { - &self.members - } - - pub fn failures(&self) -> &[GatewayFailureSummary] { - &self.failures - } - - pub fn policy(&self) -> InternalSessionPolicy { - self.policy - } - - pub fn mode(&self) -> SessionMode { - self.members[0].authentication.mode() - } - - pub fn with_internal_detection(mut self, detection: Option) -> Self { - self.internal_detection = detection; - self - } - - pub fn internal_detection(&self) -> Option<&super::network::InternalHostDetection> { - self.internal_detection.as_ref() - } -} - impl Default for InternalSessionPolicy { fn default() -> Self { Self { @@ -299,37 +175,3 @@ impl InternalSessionPolicy { self.collect_hip_data } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn deserialization_enforces_authentication_invariants() { - for (cookie, mode) in [ - ("", "tunnel"), - ("not-a-cookie", "tunnel"), - ("user=alice", "tunnel"), - ("authcookie=token", "tunnel"), - ("authcookie=token&user=alice&user=bob", "tunnel"), - ("authcookie=token&user=alice", ""), - ] { - let serialized = serde_json::json!({"cookie":cookie, "connection_type":mode}); - assert!(serde_json::from_value::(serialized).is_err()); - } - let auth = GatewayAuthentication::new("authcookie=token&user=alice".into(), "non-tunnel".into()).unwrap(); - let decoded: GatewayAuthentication = serde_json::from_str(&serde_json::to_string(&auth).unwrap()).unwrap(); - assert_eq!(decoded.mode(), SessionMode::NonTunnel); - } - - #[test] - fn deserialization_enforces_schedule_invariants() { - for interval in [0, u32::MAX] { - let serialized = serde_json::json!({"hipIntervalSecs":interval,"collectHipData":false}); - assert!(serde_json::from_value::(serialized).is_err()); - } - let serialized = serde_json::to_string(&InternalSessionPolicy::default()).unwrap(); - let decoded: InternalSessionPolicy = serde_json::from_str(&serialized).unwrap(); - assert_eq!(decoded.hip_interval(), Duration::from_secs(3600)); - } -} diff --git a/crates/gpapi/src/session/desktop/connection_plan.rs b/crates/gpapi/src/session/desktop/connection_plan.rs new file mode 100644 index 0000000..da9767a --- /dev/null +++ b/crates/gpapi/src/session/desktop/connection_plan.rs @@ -0,0 +1,159 @@ +use super::*; +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +pub struct AuthenticatedGateway { + pub gateway: Gateway, + pub authentication: GatewayAuthentication, + pub binding: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum GatewayFailure { + AuthenticationRejected, + Unreachable, + TunnelFailed, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +pub struct GatewayFailureSummary { + pub gateway: Gateway, + pub failure: GatewayFailure, +} + +/// Credentials remain in the interactive authentication owner; only issued +/// gateway cookies cross the runtime/service boundary. +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +#[serde(try_from = "ConnectionPlanFields")] +pub struct ConnectionPlan { + members: Vec, + failures: Vec, + policy: InternalSessionPolicy, + internal_detection: Option, +} + +#[derive(Deserialize)] +struct ConnectionPlanFields { + members: Vec, + failures: Vec, + policy: InternalSessionPolicy, + internal_detection: Option, +} + +impl TryFrom for ConnectionPlan { + type Error = anyhow::Error; + + fn try_from(fields: ConnectionPlanFields) -> Result { + Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection)) + } +} + +impl ConnectionPlan { + pub fn new( + members: Vec, + failures: Vec, + policy: InternalSessionPolicy, + ) -> anyhow::Result { + ensure!(!members.is_empty(), "Connection plan has no authenticated gateways"); + ensure!( + members.len() <= 64 && failures.len() <= 64, + "Connection plan exceeds its gateway limit" + ); + let mode = members[0].authentication.mode(); + ensure!( + members.iter().all(|member| member.authentication.mode() == mode), + "Mixed tunnel and non-tunnel sessions are unsupported" + ); + ensure!( + mode != SessionMode::NonTunnel + || members + .iter() + .all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal), + "Non-tunnel sessions require freshly discovered internal gateways" + ); + ensure!( + members.len() == 1 + || members + .iter() + .all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal), + "Multiple authenticated gateways require an internal connection" + ); + let mut hosts = std::collections::HashSet::new(); + for member in &members { + if mode == SessionMode::NonTunnel { + let binding = member + .binding + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Non-tunnel session has no physical binding"))?; + binding.validate_server(member.gateway.server())?; + } + let host = crate::utils::normalize_server(member.gateway.server())?; + ensure!(hosts.insert(host), "Connection plan has duplicate gateways"); + } + Ok(Self { + members, + failures, + policy, + internal_detection: None, + }) + } + + pub fn members(&self) -> &[AuthenticatedGateway] { + &self.members + } + + pub fn failures(&self) -> &[GatewayFailureSummary] { + &self.failures + } + + pub fn policy(&self) -> InternalSessionPolicy { + self.policy + } + + pub fn mode(&self) -> SessionMode { + self.members[0].authentication.mode() + } + + pub fn with_internal_detection(mut self, detection: Option) -> Self { + self.internal_detection = detection; + self + } + + pub fn internal_detection(&self) -> Option<&crate::session::InternalHostDetection> { + self.internal_detection.as_ref() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn deserialization_enforces_authentication_invariants() { + for (cookie, mode) in [ + ("", "tunnel"), + ("not-a-cookie", "tunnel"), + ("user=alice", "tunnel"), + ("authcookie=token", "tunnel"), + ("authcookie=token&user=alice&user=bob", "tunnel"), + ("authcookie=token&user=alice", ""), + ] { + let serialized = serde_json::json!({"cookie":cookie, "connection_type":mode}); + assert!(serde_json::from_value::(serialized).is_err()); + } + let auth = GatewayAuthentication::new("authcookie=token&user=alice".into(), "non-tunnel".into()).unwrap(); + let decoded: GatewayAuthentication = serde_json::from_str(&serde_json::to_string(&auth).unwrap()).unwrap(); + assert_eq!(decoded.mode(), SessionMode::NonTunnel); + } + + #[test] + fn deserialization_enforces_schedule_invariants() { + for interval in [0, u32::MAX] { + let serialized = serde_json::json!({"hipIntervalSecs":interval,"collectHipData":false}); + assert!(serde_json::from_value::(serialized).is_err()); + } + let serialized = serde_json::to_string(&InternalSessionPolicy::default()).unwrap(); + let decoded: InternalSessionPolicy = serde_json::from_str(&serialized).unwrap(); + assert_eq!(decoded.hip_interval(), Duration::from_secs(3600)); + } +} diff --git a/crates/gpapi/src/session/gateway_sessions.rs b/crates/gpapi/src/session/desktop/gateway_sessions.rs similarity index 56% rename from crates/gpapi/src/session/gateway_sessions.rs rename to crates/gpapi/src/session/desktop/gateway_sessions.rs index 16b99f1..ddb1889 100644 --- a/crates/gpapi/src/session/gateway_sessions.rs +++ b/crates/gpapi/src/session/desktop/gateway_sessions.rs @@ -39,6 +39,74 @@ impl GatewaySessions { } } + /// Register cleanup ownership before any fallible native network work. + pub fn register_login( + &mut self, + gateway: Gateway, + authentication: super::GatewayAuthentication, + client: &crate::gateway::GatewayLoginClient, + ) { + self.register(GatewaySession { + gateway, + transport: GatewayTransport::from_authenticated_login( + client.request_client().clone(), + client.origin().clone(), + authentication, + client.params().os_profile().clone(), + ), + addresses: ClientAddresses::default(), + }); + } + + pub async fn bind_non_tunnel( + &mut self, + gateway: &Gateway, + client: &crate::gateway::GatewayLoginClient, + disable_ipv6: bool, + detection: Option<&super::InternalHostDetection>, + cancellation: &tokio_util::sync::CancellationToken, + ) -> anyhow::Result { + use super::{ + network::PhysicalNetwork, + transport::binding::{bound_client, gateway_origin}, + }; + let member = self + .members + .iter() + .find(|member| member.gateway.server() == gateway.server()) + .ok_or_else(|| anyhow::anyhow!("Gateway must be registered before network binding"))?; + let origin = gateway_origin(client.origin().as_str())?; + let response_url = client + .authenticated_url() + .ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?; + anyhow::ensure!( + response_url.origin() == origin.origin(), + "Redirected non-tunnel authentication is unsupported" + ); + let endpoint = client + .login_endpoint() + .ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?; + let network = PhysicalNetwork::capture_controlled(cancellation).await?; + let binding = network + .bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation) + .await?; + network + .validate_internal_binding(&binding, detection, cancellation) + .await?; + let maintenance = bound_client(origin.as_str(), client.params(), &binding)?; + self.update(GatewaySession { + gateway: gateway.clone(), + transport: GatewayTransport::from_authenticated_login( + maintenance, + client.origin().clone(), + member.transport.authentication().clone(), + client.params().os_profile().clone(), + ), + addresses: binding.addresses(), + }); + Ok(binding) + } + pub fn register(&mut self, session: GatewaySession) { self.members.push(Arc::new(session)); } @@ -101,3 +169,6 @@ async fn logout(session: Arc) { Err(_) => log::warn!("Gateway logout timed out"), } } + +#[cfg(test)] +mod tests; diff --git a/crates/gpapi/src/session/desktop/gateway_sessions/tests.rs b/crates/gpapi/src/session/desktop/gateway_sessions/tests.rs new file mode 100644 index 0000000..1661182 --- /dev/null +++ b/crates/gpapi/src/session/desktop/gateway_sessions/tests.rs @@ -0,0 +1,65 @@ +use super::*; +use crate::{ + gateway::{GatewayLogin, GatewayLoginClient}, + gp_params::GpParams, + os_profile::{ClientOs, OsProfile}, +}; +use tokio_util::sync::CancellationToken; + +#[tokio::test] +async fn failed_binding_retains_issued_session_for_exactly_once_logout() { + use crate::session::transport::tests::{login_gateway, response}; + let mut arguments = [""; 19]; + arguments[1] = "issued-cookie"; + arguments[4] = "alice"; + arguments[12] = "non-tunnel"; + let xml = format!( + "{}", + arguments + .iter() + .map(|value| format!("{value}")) + .collect::() + ); + let (_, origin, server) = login_gateway(vec![response(&xml), response("")]).await; + let params = GpParams::builder( + OsProfile::builder(ClientOs::Linux) + .computer_name_override("original-computer") + .build(crate::os_profile::test_snapshot()), + ) + .build(); + let mut client = GatewayLoginClient::new(origin.as_str(), params).unwrap(); + let credential = crate::credential::PasswordCredential::new("alice", "password").into(); + let GatewayLogin::Authenticated(authentication) = client + .login(&credential, None, &CancellationToken::new()) + .await + .unwrap() + else { + panic!("expected issued authentication") + }; + let gateway = Gateway::new(origin.to_string(), origin.to_string()); + let mut sessions = GatewaySessions::default(); + sessions.register_login(gateway.clone(), authentication, &client); + // HTTP is accepted by the protocol fixture but rejected by native binding validation. + assert!( + sessions + .bind_non_tunnel(&gateway, &client, false, None, &CancellationToken::new()) + .await + .is_err() + ); + assert_eq!(sessions.members().len(), 1); + assert!( + sessions.members()[0] + .transport + .authentication() + .cookie() + .contains("issued-cookie") + ); + sessions.logout_gateway(gateway.server()).await; + assert!(sessions.is_empty()); + sessions.logout().await; + let requests = server.await.unwrap(); + assert_eq!(requests.len(), 2); + assert_eq!(requests[1].0, "/ssl-vpn/logout.esp"); + assert!(requests[1].1.contains("authcookie=issued-cookie")); + assert!(requests[1].1.contains("computer=original-computer")); +} diff --git a/crates/gpapi/src/session/desktop/mod.rs b/crates/gpapi/src/session/desktop/mod.rs new file mode 100644 index 0000000..7cbf03b --- /dev/null +++ b/crates/gpapi/src/session/desktop/mod.rs @@ -0,0 +1,12 @@ +use super::{GatewayAuthentication, InternalHostDetection, InternalSessionPolicy, SessionMode, detection, transport}; +use crate::gateway::Gateway; +use anyhow::ensure; +use serde::{Deserialize, Serialize}; +use specta::Type; +mod connection_plan; +mod gateway_sessions; +pub mod network; +pub mod non_tunnel; +pub mod tunnel; +pub use connection_plan::{AuthenticatedGateway, ConnectionPlan, GatewayFailure, GatewayFailureSummary}; +pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions}; diff --git a/crates/gpapi/src/session/network/binding.rs b/crates/gpapi/src/session/desktop/network/binding.rs similarity index 98% rename from crates/gpapi/src/session/network/binding.rs rename to crates/gpapi/src/session/desktop/network/binding.rs index d501c6f..54ebef8 100644 --- a/crates/gpapi/src/session/network/binding.rs +++ b/crates/gpapi/src/session/desktop/network/binding.rs @@ -130,7 +130,7 @@ impl GatewayBinding { } pub fn validate_server(&self, server: &str) -> anyhow::Result<()> { - let origin = super::super::transport::gateway_origin(server)?; + let origin = super::super::transport::binding::gateway_origin(server)?; ensure!( origin.port_or_known_default() == Some(self.endpoint.port()), "Gateway endpoint port differs" diff --git a/crates/gpapi/src/session/network/bsd.rs b/crates/gpapi/src/session/desktop/network/bsd.rs similarity index 100% rename from crates/gpapi/src/session/network/bsd.rs rename to crates/gpapi/src/session/desktop/network/bsd.rs diff --git a/crates/gpapi/src/session/network/bsd_routes.rs b/crates/gpapi/src/session/desktop/network/bsd_routes.rs similarity index 100% rename from crates/gpapi/src/session/network/bsd_routes.rs rename to crates/gpapi/src/session/desktop/network/bsd_routes.rs diff --git a/crates/gpapi/src/session/network/linux.rs b/crates/gpapi/src/session/desktop/network/linux.rs similarity index 100% rename from crates/gpapi/src/session/network/linux.rs rename to crates/gpapi/src/session/desktop/network/linux.rs diff --git a/crates/gpapi/src/session/network/macos.rs b/crates/gpapi/src/session/desktop/network/macos.rs similarity index 100% rename from crates/gpapi/src/session/network/macos.rs rename to crates/gpapi/src/session/desktop/network/macos.rs diff --git a/crates/gpapi/src/session/network/mod.rs b/crates/gpapi/src/session/desktop/network/mod.rs similarity index 96% rename from crates/gpapi/src/session/network/mod.rs rename to crates/gpapi/src/session/desktop/network/mod.rs index b53df9b..00f8ce1 100644 --- a/crates/gpapi/src/session/network/mod.rs +++ b/crates/gpapi/src/session/desktop/network/mod.rs @@ -9,8 +9,9 @@ use anyhow::{Context, ensure}; use netdev::Interface; use tokio_util::sync::CancellationToken; -use super::ClientAddresses; -use crate::process::collection::{CollectionBudget, CollectionControl, CollectorCommands}; +use super::{ClientAddresses, InternalHostDetection}; +use crate::collection::{CollectionBudget, CollectionControl}; +use crate::process::collection::CollectorCommands; #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] mod bsd; @@ -29,10 +30,9 @@ use linux as platform; use macos as platform; mod binding; -mod detection; +use super::detection; pub mod native; pub use binding::GatewayBinding; -pub use detection::InternalHostDetection; const INSPECTION_TIMEOUT: Duration = Duration::from_secs(5); const POLL_INTERVAL: Duration = Duration::from_secs(5); @@ -170,7 +170,7 @@ impl PhysicalNetwork { ensure!(resolver_count > 0, "Physical resolver context is unavailable"); if let Some(detection) = detection { ensure!( - detection.detect(cancellation).await?, + detect(detection, cancellation).await?, "Internal host detection no longer matches" ); } @@ -298,7 +298,7 @@ async fn resolve_binding( cancellation: &CancellationToken, authenticated_endpoint: SocketAddr, ) -> anyhow::Result { - let origin = super::transport::gateway_origin(server)?; + let origin = super::transport::binding::gateway_origin(server)?; let host = origin.host_str().context("Gateway host is missing")?; let port = origin.port_or_known_default().context("Gateway port is missing")?; let literal = literal_gateway_address(&origin)?; @@ -628,7 +628,7 @@ mod tests { #[test] fn bracketed_ipv6_gateway_is_a_literal_endpoint() { - let origin = super::super::transport::gateway_origin("https://[2001:db8::1]:444").unwrap(); + let origin = super::super::transport::binding::gateway_origin("https://[2001:db8::1]:444").unwrap(); assert_eq!( literal_gateway_address(&origin).unwrap(), Some("2001:db8::1".parse().unwrap()) @@ -678,3 +678,15 @@ pub(crate) fn test_binding() -> GatewayBinding { ) .unwrap() } + +pub async fn detect( + policy: &super::InternalHostDetection, + cancellation: &tokio_util::sync::CancellationToken, +) -> anyhow::Result { + for (address, hostname) in policy.targets() { + if native::detect(address, hostname, cancellation).await? { + return Ok(true); + } + } + Ok(false) +} diff --git a/crates/gpapi/src/session/network/native.rs b/crates/gpapi/src/session/desktop/network/native.rs similarity index 99% rename from crates/gpapi/src/session/network/native.rs rename to crates/gpapi/src/session/desktop/network/native.rs index 5606c9e..a495feb 100644 --- a/crates/gpapi/src/session/network/native.rs +++ b/crates/gpapi/src/session/desktop/network/native.rs @@ -14,7 +14,7 @@ pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Re Ok(dns_lookup::lookup_addr(&address).is_ok_and(|name| name.eq_ignore_ascii_case(hostname))) } -pub(super) async fn detect( +pub(in crate::session) async fn detect( address: std::net::IpAddr, hostname: &str, cancellation: &CancellationToken, diff --git a/crates/gpapi/src/session/non_tunnel.rs b/crates/gpapi/src/session/desktop/non_tunnel.rs similarity index 97% rename from crates/gpapi/src/session/non_tunnel.rs rename to crates/gpapi/src/session/desktop/non_tunnel.rs index bee9846..d87bb74 100644 --- a/crates/gpapi/src/session/non_tunnel.rs +++ b/crates/gpapi/src/session/desktop/non_tunnel.rs @@ -1,3 +1,4 @@ +use crate::session::{GatewaySessionSummary, MaintenanceState, SessionEndReason}; use std::{ future::Future, io, @@ -10,12 +11,9 @@ use tokio::task::JoinSet; use tokio_util::sync::CancellationToken; use zeroize::{Zeroize, Zeroizing}; -use crate::{gateway::Gateway, process::collection::CollectionControl}; +use crate::{collection::CollectionControl, gateway::Gateway}; -use super::{ - GatewaySession, GatewaySessionSummary, GatewaySessions, InternalSessionPolicy, MaintenanceState, SessionEndReason, - SessionMode, transport::GatewayRequestError, -}; +use super::{GatewaySession, GatewaySessions, InternalSessionPolicy, SessionMode, transport::GatewayRequestError}; const COLLECTION_TIMEOUT: Duration = Duration::from_secs(60); diff --git a/crates/gpapi/src/session/non_tunnel/tests.rs b/crates/gpapi/src/session/desktop/non_tunnel/tests.rs similarity index 99% rename from crates/gpapi/src/session/non_tunnel/tests.rs rename to crates/gpapi/src/session/desktop/non_tunnel/tests.rs index a13abbc..64df082 100644 --- a/crates/gpapi/src/session/non_tunnel/tests.rs +++ b/crates/gpapi/src/session/desktop/non_tunnel/tests.rs @@ -11,7 +11,8 @@ use tokio::sync::Notify; use super::*; use crate::session::transport::GatewayTransport; use crate::session::{ - ClientAddresses, GatewaySessions, + desktop::ClientAddresses, + desktop::GatewaySessions, transport::tests::{gateway, response}, }; diff --git a/crates/gpapi/src/session/tunnel.rs b/crates/gpapi/src/session/desktop/tunnel.rs similarity index 100% rename from crates/gpapi/src/session/tunnel.rs rename to crates/gpapi/src/session/desktop/tunnel.rs diff --git a/crates/gpapi/src/session/network/detection.rs b/crates/gpapi/src/session/detection.rs similarity index 88% rename from crates/gpapi/src/session/network/detection.rs rename to crates/gpapi/src/session/detection.rs index ec50255..e9f2803 100644 --- a/crates/gpapi/src/session/network/detection.rs +++ b/crates/gpapi/src/session/detection.rs @@ -3,7 +3,6 @@ use std::net::IpAddr; use anyhow::ensure; use serde::{Deserialize, Serialize}; use specta::Type; -use tokio_util::sync::CancellationToken; #[derive(Debug, Clone, Serialize, Deserialize, Type)] #[serde(try_from = "DetectionFields")] @@ -52,13 +51,11 @@ impl InternalHostDetection { Ok(Self { targets }) } - pub async fn detect(&self, cancellation: &CancellationToken) -> anyhow::Result { - for target in &self.targets { - if super::native::detect(target.address, &target.hostname, cancellation).await? { - return Ok(true); - } - } - Ok(false) + pub(crate) fn targets(&self) -> impl Iterator { + self + .targets + .iter() + .map(|target| (target.address, target.hostname.as_str())) } } diff --git a/crates/gpapi/src/session/transport/binding.rs b/crates/gpapi/src/session/transport/binding.rs new file mode 100644 index 0000000..349acfe --- /dev/null +++ b/crates/gpapi/src/session/transport/binding.rs @@ -0,0 +1,76 @@ +use super::*; +use crate::{gp_params::GpParams, session::desktop::network::GatewayBinding}; +use reqwest::redirect::Policy; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +impl GatewayTransport { + pub fn new( + server: &str, + authentication: GatewayAuthentication, + params: &GpParams, + binding: Option<&GatewayBinding>, + ) -> anyhow::Result { + let origin = Url::parse(&crate::utils::normalize_server(server)?)?; + let client = match binding { + Some(binding) => bound_client(server, params, binding)?, + None => Client::try_from(params)?, + }; + Ok(Self { + client, + origin, + authentication, + profile: params.os_profile().clone(), + }) + } +} +pub(crate) fn bound_client(server: &str, params: &GpParams, binding: &GatewayBinding) -> anyhow::Result { + binding.validate_server(server)?; + let origin = gateway_origin(server)?; + let host = origin + .host_str() + .ok_or_else(|| anyhow::anyhow!("Gateway host is missing"))?; + let builder = params + .client_builder()? + .redirect(Policy::none()) + .no_proxy() + .local_address(binding.source().ip()) + .resolve(host, binding.endpoint()) + .timeout(REQUEST_TIMEOUT); + let builder = bind_interface(builder, binding)?; + Ok(builder.build()?) +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result { + Ok(builder.interface(binding.interface())) +} + +#[cfg(any(target_os = "freebsd", target_os = "openbsd"))] +fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result { + if let std::net::SocketAddr::V6(source) = binding.source() { + anyhow::ensure!( + source.scope_id() == 0, + "Scoped IPv6 source requires a native socket connector" + ); + } + Ok(builder) +} + +pub(crate) fn gateway_origin(server: &str) -> anyhow::Result { + let server = if server.starts_with("https://") { + server.to_owned() + } else { + format!("https://{server}") + }; + let origin = Url::parse(&server)?; + anyhow::ensure!( + origin.scheme() == "https" + && origin.username().is_empty() + && origin.password().is_none() + && origin.path() == "/" + && origin.query().is_none() + && origin.fragment().is_none(), + "Gateway endpoint must be an HTTPS origin" + ); + Ok(origin) +} diff --git a/crates/gpapi/src/session/transport.rs b/crates/gpapi/src/session/transport/mod.rs similarity index 77% rename from crates/gpapi/src/session/transport.rs rename to crates/gpapi/src/session/transport/mod.rs index 7c74271..67c23ae 100644 --- a/crates/gpapi/src/session/transport.rs +++ b/crates/gpapi/src/session/transport/mod.rs @@ -1,13 +1,14 @@ +#[cfg(feature = "desktop")] +pub(crate) mod binding; use std::{net::IpAddr, time::Duration}; -use reqwest::{Client, StatusCode, Url, redirect::Policy}; +use reqwest::{Client, StatusCode, Url}; use xmltree::Element; -use crate::{gp_params::GpParams, os_profile::OsProfile, utils::xml::ElementExt}; +use crate::{os_profile::OsProfile, utils::xml::ElementExt}; -use super::{GatewayAuthentication, network::GatewayBinding}; +use super::GatewayAuthentication; -const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); pub(crate) const MAX_GATEWAY_RESPONSE_BYTES: usize = 1024 * 1024; pub const MAX_HIP_REPORT_BYTES: usize = 1024 * 1024; @@ -45,25 +46,6 @@ pub struct GatewayTransport { } impl GatewayTransport { - pub fn new( - server: &str, - authentication: GatewayAuthentication, - params: &GpParams, - binding: Option<&GatewayBinding>, - ) -> anyhow::Result { - let origin = Url::parse(&crate::utils::normalize_server(server)?)?; - let client = match binding { - Some(binding) => bound_client(server, params, binding)?, - None => Client::try_from(params)?, - }; - Ok(Self { - client, - origin, - authentication, - profile: params.os_profile().clone(), - }) - } - /// The login client already validated and built this transport before issuing /// authentication. Registering its cleanup context cannot fail afterwards. pub(crate) fn from_authenticated_login( @@ -185,58 +167,6 @@ async fn post( parse_response(&body) } -pub(crate) fn bound_client(server: &str, params: &GpParams, binding: &GatewayBinding) -> anyhow::Result { - binding.validate_server(server)?; - let origin = gateway_origin(server)?; - let host = origin - .host_str() - .ok_or_else(|| anyhow::anyhow!("Gateway host is missing"))?; - let builder = params - .client_builder()? - .redirect(Policy::none()) - .no_proxy() - .local_address(binding.source().ip()) - .resolve(host, binding.endpoint()) - .timeout(REQUEST_TIMEOUT); - let builder = bind_interface(builder, binding)?; - Ok(builder.build()?) -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result { - Ok(builder.interface(binding.interface())) -} - -#[cfg(any(target_os = "freebsd", target_os = "openbsd"))] -fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result { - if let std::net::SocketAddr::V6(source) = binding.source() { - anyhow::ensure!( - source.scope_id() == 0, - "Scoped IPv6 source requires a native socket connector" - ); - } - Ok(builder) -} - -pub(crate) fn gateway_origin(server: &str) -> anyhow::Result { - let server = if server.starts_with("https://") { - server.to_owned() - } else { - format!("https://{server}") - }; - let origin = Url::parse(&server)?; - anyhow::ensure!( - origin.scheme() == "https" - && origin.username().is_empty() - && origin.password().is_none() - && origin.path() == "/" - && origin.query().is_none() - && origin.fragment().is_none(), - "Gateway endpoint must be an HTTPS origin" - ); - Ok(origin) -} - fn set_form(form: &mut Vec<(String, String)>, key: &str, value: &str) { form.retain(|(name, _)| name != key); form.push((key.into(), value.into())); diff --git a/crates/gpapi/src/session/transport/tests.rs b/crates/gpapi/src/session/transport/tests.rs index 7338b6d..2301330 100644 --- a/crates/gpapi/src/session/transport/tests.rs +++ b/crates/gpapi/src/session/transport/tests.rs @@ -1,3 +1,6 @@ +use reqwest::redirect::Policy; +use std::time::Duration; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); use super::*; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, @@ -91,7 +94,7 @@ async fn gateway_fixture( .unwrap(), profile: OsProfile::builder(crate::os_profile::ClientOs::Linux) .computer_name_override("test") - .build(), + .build(crate::os_profile::test_snapshot()), }; (transport, server) } diff --git a/crates/gpapi/src/utils/legacy_pkcs8.rs b/crates/gpapi/src/utils/certificate/legacy_pkcs8.rs similarity index 97% rename from crates/gpapi/src/utils/legacy_pkcs8.rs rename to crates/gpapi/src/utils/certificate/legacy_pkcs8.rs index 868a8b3..7c6df2a 100644 --- a/crates/gpapi/src/utils/legacy_pkcs8.rs +++ b/crates/gpapi/src/utils/certificate/legacy_pkcs8.rs @@ -16,7 +16,7 @@ use nix::{ use pkcs8::SecretDocument; use zeroize::Zeroizing; -use super::request::RequestIdentityError::{self, LegacyKeyConversion}; +use crate::utils::request::RequestIdentityError::{self, LegacyKeyConversion}; const TIMEOUT: Duration = Duration::from_secs(10); const MAX_OUTPUT: u64 = 1024 * 1024; @@ -57,7 +57,7 @@ fn read_output(pipe: &mut impl Read, output: &mut Zeroizing>, limit: u64 } } -pub(super) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result { +pub(in crate::utils) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result { let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?; // The command's line reader reserves one byte for a terminator. The linked // OpenSSL API accepted 1024 bytes, but the CLI would truncate that password. diff --git a/crates/gpapi/src/utils/certificate/mod.rs b/crates/gpapi/src/utils/certificate/mod.rs new file mode 100644 index 0000000..e514d3d --- /dev/null +++ b/crates/gpapi/src/utils/certificate/mod.rs @@ -0,0 +1,18 @@ +#[cfg(target_os = "macos")] +#[path = "pkcs12/macos.rs"] +pub(super) mod pkcs12_identity; +#[cfg(not(any(target_os = "macos", target_os = "ios")))] +#[path = "pkcs12/openssl.rs"] +pub(super) mod pkcs12_identity; +#[cfg(target_os = "ios")] +#[path = "pkcs12/ios.rs"] +pub(super) mod pkcs12_identity; +#[cfg(any(target_os = "macos", target_os = "ios"))] +#[path = "traditional_key/apple.rs"] +pub(super) mod traditional_key; +#[cfg(not(any(target_os = "macos", target_os = "ios")))] +#[path = "traditional_key/openssl.rs"] +pub(super) mod traditional_key; + +#[cfg(feature = "desktop")] +pub(super) mod legacy_pkcs8; diff --git a/crates/gpapi/src/utils/certificate/pkcs12/ios.rs b/crates/gpapi/src/utils/certificate/pkcs12/ios.rs new file mode 100644 index 0000000..214dc15 --- /dev/null +++ b/crates/gpapi/src/utils/certificate/pkcs12/ios.rs @@ -0,0 +1,10 @@ +use crate::utils::request::RequestIdentityError; +use security_framework::import_export::Pkcs12ImportOptions; +pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> { + if let Ok(imports) = Pkcs12ImportOptions::new().passphrase(password).import(bytes) + && !imports.last().is_some_and(|item| item.identity.is_some()) + { + return Err(RequestIdentityError::IncompletePkcs12.into()); + } + Ok(()) +} diff --git a/crates/gpapi/src/utils/pkcs12_identity/macos.rs b/crates/gpapi/src/utils/certificate/pkcs12/macos.rs similarity index 86% rename from crates/gpapi/src/utils/pkcs12_identity/macos.rs rename to crates/gpapi/src/utils/certificate/pkcs12/macos.rs index 9653c22..15e79f4 100644 --- a/crates/gpapi/src/utils/pkcs12_identity/macos.rs +++ b/crates/gpapi/src/utils/certificate/pkcs12/macos.rs @@ -1,8 +1,8 @@ use security_framework::{import_export::Pkcs12ImportOptions, os::macos::keychain::CreateOptions}; -use super::request::RequestIdentityError; +use crate::utils::request::RequestIdentityError; -pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> { +pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> { // native-tls assumes a successful import has a last item with an identity. // Incomplete archives violate that assumption and panic. Inspect them first // in a private temporary keychain, never the user's default keychain. diff --git a/crates/gpapi/src/utils/pkcs12_identity/openssl.rs b/crates/gpapi/src/utils/certificate/pkcs12/openssl.rs similarity index 74% rename from crates/gpapi/src/utils/pkcs12_identity/openssl.rs rename to crates/gpapi/src/utils/certificate/pkcs12/openssl.rs index 7ddedf9..9ad2a04 100644 --- a/crates/gpapi/src/utils/pkcs12_identity/openssl.rs +++ b/crates/gpapi/src/utils/certificate/pkcs12/openssl.rs @@ -1,8 +1,8 @@ use openssl::pkcs12::Pkcs12; -use super::request::RequestIdentityError; +use crate::utils::request::RequestIdentityError; -pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> { +pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> { // Parse errors belong to the existing native TLS importer. A successful parse // lets us report incomplete archives without suggesting a password change. if let Ok(archive) = Pkcs12::from_der(bytes).and_then(|archive| archive.parse2(password)) diff --git a/crates/gpapi/src/utils/traditional_key/macos.rs b/crates/gpapi/src/utils/certificate/traditional_key/apple.rs similarity index 75% rename from crates/gpapi/src/utils/traditional_key/macos.rs rename to crates/gpapi/src/utils/certificate/traditional_key/apple.rs index 6c59699..f0000e5 100644 --- a/crates/gpapi/src/utils/traditional_key/macos.rs +++ b/crates/gpapi/src/utils/certificate/traditional_key/apple.rs @@ -1,8 +1,8 @@ use pkcs8::SecretDocument; -use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError}; +use crate::utils::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError}; -pub(super) fn normalize( +pub(in crate::utils) fn normalize( _bytes: &[u8], format: TraditionalKeyFormat, _passphrase: Option<&str>, diff --git a/crates/gpapi/src/utils/traditional_key/openssl.rs b/crates/gpapi/src/utils/certificate/traditional_key/openssl.rs similarity index 92% rename from crates/gpapi/src/utils/traditional_key/openssl.rs rename to crates/gpapi/src/utils/certificate/traditional_key/openssl.rs index 1234053..d5fe899 100644 --- a/crates/gpapi/src/utils/traditional_key/openssl.rs +++ b/crates/gpapi/src/utils/certificate/traditional_key/openssl.rs @@ -5,9 +5,9 @@ use openssl::{ use pkcs8::SecretDocument; use zeroize::Zeroizing; -use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError}; +use crate::utils::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError}; -pub(super) fn normalize( +pub(in crate::utils) fn normalize( bytes: &[u8], format: TraditionalKeyFormat, passphrase: Option<&str>, diff --git a/crates/gpapi/src/utils/identity_encoding.rs b/crates/gpapi/src/utils/identity_encoding.rs index 59a001b..874f0f0 100644 --- a/crates/gpapi/src/utils/identity_encoding.rs +++ b/crates/gpapi/src/utils/identity_encoding.rs @@ -8,7 +8,7 @@ use pkcs8::{ }; use zeroize::Zeroizing; -use super::{request::RequestIdentityError, traditional_key}; +use super::{certificate::traditional_key, request::RequestIdentityError}; pub(super) enum TraditionalKeyFormat { Sec1Der, @@ -174,7 +174,10 @@ fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result bool { self.status.is_client_error() || self.status.is_server_error() } + + pub fn is_authentication_rejection(&self) -> bool { + matches!(self.status.as_u16(), 401 | 403) + } } pub async fn parse_gp_response(res: Response) -> anyhow::Result { diff --git a/crates/gpapi/src/utils/request.rs b/crates/gpapi/src/utils/request.rs index 92d89b1..36dd61f 100644 --- a/crates/gpapi/src/utils/request.rs +++ b/crates/gpapi/src/utils/request.rs @@ -4,7 +4,7 @@ use anyhow::{Context, ensure}; use reqwest::Identity; use zeroize::Zeroizing; -use super::{identity_encoding, pkcs12_identity}; +use super::{certificate::pkcs12_identity, identity_encoding}; #[derive(Debug, thiserror::Error)] pub enum RequestIdentityError { diff --git a/crates/gpapi/tests/client_identity.rs b/crates/gpapi/tests/client_identity.rs index be58047..a90db62 100644 --- a/crates/gpapi/tests/client_identity.rs +++ b/crates/gpapi/tests/client_identity.rs @@ -307,6 +307,7 @@ fn pbes2_legacy_ciphers_remain_supported() { } #[test] +#[cfg(feature = "desktop")] fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() { let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap(); assert_eq!( @@ -326,6 +327,7 @@ fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() { #[test] #[cfg(not(target_os = "macos"))] +#[cfg(feature = "desktop")] fn legacy_pkcs8_matches_previous_linux_openssl_processing() { let encrypted = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap(); let previous = openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, PASSWORD.as_bytes()) @@ -338,6 +340,7 @@ fn legacy_pkcs8_matches_previous_linux_openssl_processing() { } #[test] +#[cfg(feature = "desktop")] fn legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable() { use std::os::unix::fs::PermissionsExt; @@ -407,6 +410,7 @@ fn legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executab } #[test] +#[cfg(feature = "desktop")] fn legacy_converter_reports_its_password_length_limit_without_requesting_a_retry() { let password = "x".repeat(1024); let encrypted = fs::read(fixture("rsa-pbes1-3des-password-1024.pem")).unwrap(); @@ -435,6 +439,7 @@ fn legacy_converter_reports_its_password_length_limit_without_requesting_a_retry } #[test] +#[cfg(feature = "desktop")] fn legacy_conversion_keeps_original_files_and_rejects_line_breaks_in_passwords() { let original = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap(); for password in [ @@ -706,3 +711,15 @@ fn mismatched_certificate_key_is_rejected_before_request_client_creation() { .contains("Check that the private key matches the certificate") ); } + +#[cfg(not(feature = "desktop"))] +#[test] +fn portable_legacy_pkcs8_is_explicitly_unsupported() { + for password in [None, Some(PASSWORD)] { + let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", password).unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(RequestIdentityError::UnsupportedEncryption) + )); + } +} diff --git a/crates/gpapi/tests/ios_password_rejection.rs b/crates/gpapi/tests/ios_password_rejection.rs new file mode 100644 index 0000000..20ac976 --- /dev/null +++ b/crates/gpapi/tests/ios_password_rejection.rs @@ -0,0 +1,87 @@ +use gpapi::{ + credential::{Credential, PasswordCredential}, + error::AuthenticationRejected, + gateway::GatewayLoginClient, + gp_params::GpParams, + os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile}, + portal, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; +use tokio_util::sync::CancellationToken; + +#[tokio::test] +async fn explicit_rejection_is_typed_for_ios_without_changing_desktop_errors() { + for os in [ClientOs::Ios, ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] { + for status in [401, 403, 503] { + for gateway in [false, true] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + loop { + let mut chunk = [0; 4096]; + let count = socket.read(&mut chunk).await.unwrap(); + if count == 0 { + break; + } + request.extend_from_slice(&chunk[..count]); + if let Some(end) = request.windows(4).position(|v| v == b"\r\n\r\n") { + let headers = String::from_utf8_lossy(&request[..end]).to_lowercase(); + let length: usize = headers + .lines() + .find_map(|line| line.strip_prefix("content-length:").and_then(|s| s.trim().parse().ok())) + .unwrap_or(0); + if request.len() >= end + 4 + length { + break; + } + } + } + socket + .write_all(format!("HTTP/1.1 {status} Test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes()) + .await + .unwrap(); + }); + let profile = OsProfile::builder(os).build(HostSnapshot { + runtime_os: os, + identity: HostIdentity::application("fixture".into(), "fixture-id".into()), + os_version: "fixture".into(), + software_version: String::new(), + }); + let params = GpParams::builder(profile).build(); + let credential = Credential::Password(PasswordCredential::new("fixture", "fixture-password")); + let token = CancellationToken::new(); + let error = if gateway { + GatewayLoginClient::new(&origin, params) + .unwrap() + .login(&credential, None, &token) + .await + .err() + .unwrap() + } else { + portal::retrieve_config(&origin, &credential, ¶ms, &token) + .await + .err() + .unwrap() + }; + server.await.unwrap(); + assert_eq!( + error.is::(), + os == ClientOs::Ios && status != 503, + "os={os:?}, status={status}, gateway={gateway}" + ); + if os != ClientOs::Ios { + let prefix = if gateway { + "Gateway login error:" + } else { + "Portal config error:" + }; + assert!(error.to_string().starts_with(prefix)); + } + } + } + } +} diff --git a/crates/gpapi/tests/portable_protocol.rs b/crates/gpapi/tests/portable_protocol.rs new file mode 100644 index 0000000..3d0e16a --- /dev/null +++ b/crates/gpapi/tests/portable_protocol.rs @@ -0,0 +1,35 @@ +use gpapi::{ + gp_params::GpParams, + os_profile::{ClientOs, HostIdentity, OsProfile}, +}; + +#[test] +fn mobile_profile_preserves_supplied_identity_without_hardware_claims() { + let profile = OsProfile::builder(ClientOs::Ios).build(gpapi::os_profile::HostSnapshot { + runtime_os: ClientOs::Ios, + identity: HostIdentity::application("Phone".into(), "installation-id".into()), + os_version: "Apple iOS 27.0.1".into(), + software_version: String::new(), + }); + assert_eq!(profile.client_os().as_str(), "iOS"); + assert_eq!(profile.client_os().to_openconnect_os(), "apple-ios"); + assert_eq!(profile.host_id(), "installation-id"); + assert_eq!(profile.computer(), "Phone"); + assert_eq!(profile.os_version(), "Apple iOS 27.0.1"); + assert!(profile.serialno().is_empty()); + assert!(profile.mac_addr().is_empty()); + assert!(!GpParams::builder(profile).build().ignore_tls_errors()); +} + +#[test] +fn reported_profile_does_not_change_runtime_platform() { + let profile = OsProfile::builder(ClientOs::Mac).build(gpapi::os_profile::HostSnapshot { + runtime_os: ClientOs::Ios, + identity: HostIdentity::application("Phone".into(), "installation-id".into()), + os_version: "Apple iOS 27.0.1".into(), + software_version: String::new(), + }); + assert!(!profile.is_native()); + assert!(profile.os_version().starts_with("Apple Mac OS X ")); + assert_eq!(profile.host_identity().host_id(), "installation-id"); +} diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs index fbad75d..06a2910 100644 --- a/crates/gphip/src/lib.rs +++ b/crates/gphip/src/lib.rs @@ -5,7 +5,8 @@ use serde::Deserialize; use std::collections::HashMap; use std::{io, time::Duration}; -use gpapi::process::collection::{CollectionBudget, CollectionControl, CollectorCommands}; +use gpapi::collection::{CollectionBudget, CollectionControl}; +use gpapi::process::collection::CollectorCommands; use xmltree::Element; #[cfg(target_os = "macos")] @@ -506,7 +507,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { ipv4: Some("127.0.0.1".to_string()), ipv6: Some("::1".to_string()), }], - ClientOs::Linux | ClientOs::Mac => vec![], + ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => vec![], } } @@ -515,7 +516,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { fn domain_for_profile(&self) -> String { match self.profile.client_os() { ClientOs::Linux => String::new(), - ClientOs::Mac | ClientOs::Windows => self.get_domain(), + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => self.get_domain(), } } @@ -657,6 +658,7 @@ fn parse_defender_info(json: &str) -> Option { /// is a different OS (i.e. emulation). fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> (String, String) { match profile.client_os() { + ClientOs::Ios => (runtime.name.clone(), runtime.description.clone()), ClientOs::Linux => ("enp1s0f0".to_string(), "enp1s0f0".to_string()), ClientOs::Mac => ("en0".to_string(), "en0".to_string()), ClientOs::Windows => ( @@ -672,7 +674,7 @@ fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> fn format_mac_for(profile: &OsProfile, mac: Option) -> Option { match profile.client_os() { ClientOs::Windows => mac.map(|m| m.replace(':', "-")), - ClientOs::Linux | ClientOs::Mac => mac, + ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => mac, } } @@ -751,7 +753,7 @@ mod tests { } fn make_profile(client_os: ClientOs) -> OsProfile { - OsProfileBuilder::new(client_os).build() + gpapi::os_profile::desktop::collect_profile(OsProfileBuilder::new(client_os), None) } #[test] diff --git a/crates/gptunnel/src/configuration.rs b/crates/gptunnel/src/configuration.rs index f3e7479..a834876 100644 --- a/crates/gptunnel/src/configuration.rs +++ b/crates/gptunnel/src/configuration.rs @@ -1,6 +1,8 @@ use std::net::{Ipv4Addr, Ipv6Addr}; -use gpapi::session::tunnel::{MAX_CONFIGURATION_BYTES, TunnelAddress, TunnelConfiguration, TunnelList, TunnelState}; +use gpapi::session::desktop::tunnel::{ + MAX_CONFIGURATION_BYTES, TunnelAddress, TunnelConfiguration, TunnelList, TunnelState, +}; use log::{debug, info}; use openconnect::tunnel::{Configuration, NativeList}; diff --git a/crates/gptunnel/src/monitor.rs b/crates/gptunnel/src/monitor.rs index 0451405..4f91bce 100644 --- a/crates/gptunnel/src/monitor.rs +++ b/crates/gptunnel/src/monitor.rs @@ -3,7 +3,7 @@ use std::{ time::Duration, }; -use gpapi::session::tunnel::{ +use gpapi::session::desktop::tunnel::{ TunnelPhase, TunnelState, TunnelStatistics, TunnelStatisticsSnapshot, TunnelStatisticsState, TunnelStatisticsView, TunnelTransport, }; diff --git a/crates/openconnect/build.rs b/crates/openconnect/build.rs index d10f7b6..bf708c0 100644 --- a/crates/openconnect/build.rs +++ b/crates/openconnect/build.rs @@ -1,250 +1,12 @@ -use std::{env, path::PathBuf}; - -fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { - let libxml2_dir = deps_dir.join("libxml2"); - let install_dir = out_dir.join("libxml2_install"); - - // The temporary location where we will build - let build_src = out_dir.join("libxml2_build"); - - // Track changes so cargo rebuilds if submodule changes - println!("cargo:rerun-if-changed={}", libxml2_dir.display()); - - // Prepare the build directory - // If the directory exists from a previous run, remove it to ensure a clean slate - if build_src.exists() { - std::fs::remove_dir_all(&build_src).unwrap(); - } - if install_dir.exists() { - std::fs::remove_dir_all(&install_dir).unwrap(); - } - std::fs::create_dir_all(&install_dir).unwrap(); - std::fs::create_dir_all(&build_src).unwrap(); - - // Copy the source code to OUT_DIR - // We use fs_extra options to copy contents recursively - let mut options = fs_extra::dir::CopyOptions::new(); - options.overwrite = true; - options.content_only = true; // Copy content of src into dest, not src folder itself - - fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR"); - - // Build the libxml2 library using autotools - let dst = { - let mut config = autotools::Config::new(&build_src); - config - .out_dir(&install_dir) - .reconf("-ivf") - .enable_static() - .disable_shared() - // Disable optional features that complicate static builds - .with("python", Some("no")) - .with("icu", Some("no")) - .with("http", Some("no")) - .with("ftp", Some("no")) - .with("catalog", Some("no")) - .with("docbook", Some("no")) - .with("legacy", Some("no")) - .with("threads", Some("no")) - .with("zlib", Some("no")) - .with("lzma", Some("no")) - // Ensure position-independent code (safe for static linking) - .cflag("-fPIC"); - config.build() - }; - - let lib_dir = dst.join("lib"); - let include_dir = dst.join("include/libxml2"); - - // Tell rustc where to find the static library - println!("cargo:rustc-link-search=native={}", lib_dir.display()); - - // Static linking of libxml2 - println!("cargo:rustc-link-lib=static=xml2"); - - // Export include path for downstream use (bindgen / cc) - println!("cargo:include={}", include_dir.display()); - - dst -} - -fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { - let openconnect_dir = deps_dir.join("openconnect"); - let install_dir = out_dir.join("openconnect_install"); - - // The temporary location where we will build - let build_src = out_dir.join("openconnect_build"); - - // Track changes so cargo rebuilds if submodule changes - println!("cargo:rerun-if-changed={}", openconnect_dir.display()); - - // Prepare the build directory - // If the directory exists from a previous run, remove it to ensure a clean slate - if build_src.exists() { - std::fs::remove_dir_all(&build_src).unwrap(); - } - if install_dir.exists() { - std::fs::remove_dir_all(&install_dir).unwrap(); - } - std::fs::create_dir_all(&install_dir).unwrap(); - std::fs::create_dir_all(&build_src).unwrap(); - - // Copy the source code to OUT_DIR - // We use fs_extra options to copy contents recursively - let mut options = fs_extra::dir::CopyOptions::new(); - options.overwrite = true; - options.content_only = true; // Copy content of src into dest, not src folder itself - - fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR"); - - // Build the OpenConnect library using autotools. Keep the upstream LGPL - // library dynamically linked on macOS so it remains replaceable in the app - // bundle. Other platforms retain the existing static-link behavior. - let mut config = autotools::Config::new(&build_src); - config - .out_dir(&install_dir) - .reconf("-ivf") - .disable("nls", None) // disable translations to save space - .disable("docs", None) - .disable("dsa-tests", None) - .without("libproxy", None) - .without("stoken", None) - .without("libpcsclite", None) - .without("libpskc", None) - .without("gssapi", None) - .with("gnutls-tss2", Some("no")) - .with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS - - #[cfg(target_os = "macos")] - { - config - .disable_static() - .enable_shared() - .with("gnutls", None) - .without("openssl", None); - config.ldflag("-liconv"); - config.env("LIBS", "-liconv"); - } - - #[cfg(not(target_os = "macos"))] - config.enable_static().disable_shared(); - - #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] - { - config.ldflag("-L/usr/local/lib"); - config.ldflag("-liconv"); - config.env("LIBS", "-liconv"); - } - - let dst = config.build(); - - let lib_dir = dst.join("lib"); - let include_dir = dst.join("include"); - - #[cfg(target_os = "macos")] - { - let configuration = std::fs::read_to_string(dst.join("build/config.h")) - .expect("Failed to read the OpenConnect TLS backend configuration"); - assert!( - configuration.lines().any(|line| line == "#define OPENCONNECT_GNUTLS 1") - && !configuration - .lines() - .any(|line| line == "#define OPENCONNECT_OPENSSL 1"), - "macOS OpenConnect must use GnuTLS" - ); - // Do not embed Cargo's temporary build directory in consumers of this library. - let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap(); - let library_name = library.file_name().unwrap().to_str().unwrap(); - let status = std::process::Command::new("install_name_tool") - .arg("-id") - .arg(format!("@rpath/{library_name}")) - .arg(&library) - .status() - .expect("Failed to update the OpenConnect dylib install name"); - assert!(status.success(), "Failed to update the OpenConnect dylib install name"); - let status = std::process::Command::new("codesign") - .args(["--force", "--sign", "-"]) - .arg(&library) - .status() - .expect("Failed to sign the OpenConnect dylib"); - assert!(status.success(), "Failed to sign the OpenConnect dylib"); - println!("cargo:lib_dir={}", lib_dir.display()); - } - - println!("cargo:rustc-link-search=native={}", lib_dir.display()); - - #[cfg(target_os = "macos")] - println!("cargo:rustc-link-lib=dylib=openconnect"); - - #[cfg(not(target_os = "macos"))] - println!("cargo:rustc-link-lib=static=openconnect"); - - // Export include path for downstream use (bindgen / cc) - println!("cargo:include={}", include_dir.display()); - - dst -} +#[path = "build/desktop.rs"] +mod desktop; +#[path = "build/ios.rs"] +mod ios; fn main() { - let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); - let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); - let deps_dir = PathBuf::from(manifest_dir).join("deps"); - - let oc_dst = build_openconnect(&deps_dir, &out_dir); - println!( - "cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}", - oc_dst.join("build").display() - ); - println!( - "cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}", - out_dir.join("openconnect_build").display() - ); - - // Only statically link libxml2 if `LIBXML2_STATIC` is set - if env::var("LIBXML2_STATIC").is_ok() { - let _libxml2_dst = build_libxml2(&deps_dir, &out_dir); - } else { - // Using pkg-config to find system libxml2 - pkg_config::probe_library("libxml-2.0").unwrap(); + match std::env::var("CARGO_CFG_TARGET_OS").as_deref() { + Ok("ios") => ios::build(), + Ok("macos" | "linux" | "freebsd" | "openbsd") => desktop::build(), + target => panic!("Unsupported OpenConnect target: {target:?}"), } - - // Using pkg-config to find system deps - pkg_config::probe_library("zlib").unwrap(); - #[cfg(target_os = "macos")] - pkg_config::probe_library("gnutls").unwrap(); - - #[cfg(not(target_os = "macos"))] - { - pkg_config::probe_library("liblz4").unwrap(); - pkg_config::probe_library("gnutls").unwrap(); - - // Below are required by gnutls - pkg_config::probe_library("p11-kit-1").unwrap(); - pkg_config::probe_library("hogweed").unwrap(); - pkg_config::probe_library("nettle").unwrap(); - pkg_config::probe_library("gmp").unwrap(); - } - - // Compile the vpn.c file - println!("cargo:rerun-if-changed=src/ffi/vpn.c"); - println!("cargo:rerun-if-changed=src/ffi/vpn.h"); - - #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] - { - println!("cargo:rustc-link-search=native=/usr/local/lib"); - println!("cargo:rustc-link-lib=iconv"); - } - - // Prevent silent fallback to dynamic libraries - #[cfg(target_os = "linux")] - { - println!("cargo:rustc-link-arg=-Wl,-Bstatic"); - println!("cargo:rustc-link-arg=-Wl,-Bdynamic"); - } - - cc::Build::new() - .file("src/ffi/vpn.c") - .include("src/ffi") - .include(&oc_dst.join("include")) - .compile("vpn"); } diff --git a/crates/openconnect/build/desktop.rs b/crates/openconnect/build/desktop.rs new file mode 100644 index 0000000..7a075fd --- /dev/null +++ b/crates/openconnect/build/desktop.rs @@ -0,0 +1,252 @@ +use std::{env, path::PathBuf}; + +fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { + let libxml2_dir = deps_dir.join("libxml2"); + let install_dir = out_dir.join("libxml2_install"); + + // The temporary location where we will build + let build_src = out_dir.join("libxml2_build"); + + // Track changes so cargo rebuilds if submodule changes + println!("cargo:rerun-if-changed={}", libxml2_dir.display()); + + // Prepare the build directory + // If the directory exists from a previous run, remove it to ensure a clean slate + if build_src.exists() { + std::fs::remove_dir_all(&build_src).unwrap(); + } + if install_dir.exists() { + std::fs::remove_dir_all(&install_dir).unwrap(); + } + std::fs::create_dir_all(&install_dir).unwrap(); + std::fs::create_dir_all(&build_src).unwrap(); + + // Copy the source code to OUT_DIR + // We use fs_extra options to copy contents recursively + let mut options = fs_extra::dir::CopyOptions::new(); + options.overwrite = true; + options.content_only = true; // Copy content of src into dest, not src folder itself + + fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR"); + + // Build the libxml2 library using autotools + let dst = { + let mut config = autotools::Config::new(&build_src); + config + .out_dir(&install_dir) + .reconf("-ivf") + .enable_static() + .disable_shared() + // Disable optional features that complicate static builds + .with("python", Some("no")) + .with("icu", Some("no")) + .with("http", Some("no")) + .with("ftp", Some("no")) + .with("catalog", Some("no")) + .with("docbook", Some("no")) + .with("legacy", Some("no")) + .with("threads", Some("no")) + .with("zlib", Some("no")) + .with("lzma", Some("no")) + // Ensure position-independent code (safe for static linking) + .cflag("-fPIC"); + config.build() + }; + + let lib_dir = dst.join("lib"); + let include_dir = dst.join("include/libxml2"); + + // Tell rustc where to find the static library + println!("cargo:rustc-link-search=native={}", lib_dir.display()); + + // Static linking of libxml2 + println!("cargo:rustc-link-lib=static=xml2"); + + // Export include path for downstream use (bindgen / cc) + println!("cargo:include={}", include_dir.display()); + + dst +} + +fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { + let openconnect_dir = deps_dir.join("openconnect"); + let install_dir = out_dir.join("openconnect_install"); + + // The temporary location where we will build + let build_src = out_dir.join("openconnect_build"); + + // Track changes so cargo rebuilds if submodule changes + println!("cargo:rerun-if-changed={}", openconnect_dir.display()); + + // Prepare the build directory + // If the directory exists from a previous run, remove it to ensure a clean slate + if build_src.exists() { + std::fs::remove_dir_all(&build_src).unwrap(); + } + if install_dir.exists() { + std::fs::remove_dir_all(&install_dir).unwrap(); + } + std::fs::create_dir_all(&install_dir).unwrap(); + std::fs::create_dir_all(&build_src).unwrap(); + + // Copy the source code to OUT_DIR + // We use fs_extra options to copy contents recursively + let mut options = fs_extra::dir::CopyOptions::new(); + options.overwrite = true; + options.content_only = true; // Copy content of src into dest, not src folder itself + + fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR"); + + // Build the OpenConnect library using autotools. Keep the upstream LGPL + // library dynamically linked on macOS so it remains replaceable in the app + // bundle. Other platforms retain the existing static-link behavior. + let mut config = autotools::Config::new(&build_src); + config + .out_dir(&install_dir) + .reconf("-ivf") + .disable("nls", None) // disable translations to save space + .disable("docs", None) + .disable("dsa-tests", None) + .without("libproxy", None) + .without("stoken", None) + .without("libpcsclite", None) + .without("libpskc", None) + .without("gssapi", None) + .with("gnutls-tss2", Some("no")) + .with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS + + if target_os() == "macos" { + config + .disable_static() + .enable_shared() + .with("gnutls", None) + .without("openssl", None); + config.ldflag("-liconv"); + config.env("LIBS", "-liconv"); + } + + if target_os() != "macos" { + config.enable_static().disable_shared(); + } + + if matches!(target_os().as_str(), "freebsd" | "openbsd") { + config.ldflag("-L/usr/local/lib"); + config.ldflag("-liconv"); + config.env("LIBS", "-liconv"); + } + + let dst = config.build(); + + let lib_dir = dst.join("lib"); + let include_dir = dst.join("include"); + + if target_os() == "macos" { + let configuration = std::fs::read_to_string(dst.join("build/config.h")) + .expect("Failed to read the OpenConnect TLS backend configuration"); + assert!( + configuration.lines().any(|line| line == "#define OPENCONNECT_GNUTLS 1") + && !configuration + .lines() + .any(|line| line == "#define OPENCONNECT_OPENSSL 1"), + "macOS OpenConnect must use GnuTLS" + ); + // Do not embed Cargo's temporary build directory in consumers of this library. + let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap(); + let library_name = library.file_name().unwrap().to_str().unwrap(); + let status = std::process::Command::new("install_name_tool") + .arg("-id") + .arg(format!("@rpath/{library_name}")) + .arg(&library) + .status() + .expect("Failed to update the OpenConnect dylib install name"); + assert!(status.success(), "Failed to update the OpenConnect dylib install name"); + let status = std::process::Command::new("codesign") + .args(["--force", "--sign", "-"]) + .arg(&library) + .status() + .expect("Failed to sign the OpenConnect dylib"); + assert!(status.success(), "Failed to sign the OpenConnect dylib"); + println!("cargo:lib_dir={}", lib_dir.display()); + } + + println!("cargo:rustc-link-search=native={}", lib_dir.display()); + + if target_os() == "macos" { + println!("cargo:rustc-link-lib=dylib=openconnect"); + } + + if target_os() != "macos" { + println!("cargo:rustc-link-lib=static=openconnect"); + } + + // Export include path for downstream use (bindgen / cc) + println!("cargo:include={}", include_dir.display()); + + dst +} + +pub fn build() { + let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let deps_dir = PathBuf::from(manifest_dir).join("deps"); + + let oc_dst = build_openconnect(&deps_dir, &out_dir); + println!( + "cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}", + oc_dst.join("build").display() + ); + println!( + "cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}", + out_dir.join("openconnect_build").display() + ); + + // Only statically link libxml2 if `LIBXML2_STATIC` is set + if env::var("LIBXML2_STATIC").is_ok() { + let _libxml2_dst = build_libxml2(&deps_dir, &out_dir); + } else { + // Using pkg-config to find system libxml2 + pkg_config::probe_library("libxml-2.0").unwrap(); + } + + // Using pkg-config to find system deps + pkg_config::probe_library("zlib").unwrap(); + if target_os() == "macos" { + pkg_config::probe_library("gnutls").unwrap(); + } + + if target_os() != "macos" { + pkg_config::probe_library("liblz4").unwrap(); + pkg_config::probe_library("gnutls").unwrap(); + + // Below are required by gnutls + pkg_config::probe_library("p11-kit-1").unwrap(); + pkg_config::probe_library("hogweed").unwrap(); + pkg_config::probe_library("nettle").unwrap(); + pkg_config::probe_library("gmp").unwrap(); + } + + // Compile the vpn.c file + println!("cargo:rerun-if-changed=src/ffi/vpn.c"); + println!("cargo:rerun-if-changed=src/ffi/vpn.h"); + + if matches!(target_os().as_str(), "freebsd" | "openbsd") { + println!("cargo:rustc-link-search=native=/usr/local/lib"); + println!("cargo:rustc-link-lib=iconv"); + } + + // Prevent silent fallback to dynamic libraries + if target_os() == "linux" { + println!("cargo:rustc-link-arg=-Wl,-Bstatic"); + println!("cargo:rustc-link-arg=-Wl,-Bdynamic"); + } + + cc::Build::new() + .file("src/ffi/vpn.c") + .include("src/ffi") + .include(&oc_dst.join("include")) + .compile("vpn"); +} + +fn target_os() -> String { + env::var("CARGO_CFG_TARGET_OS").expect("Cargo target OS") +} diff --git a/crates/openconnect/build/ios.rs b/crates/openconnect/build/ios.rs new file mode 100644 index 0000000..6064acf --- /dev/null +++ b/crates/openconnect/build/ios.rs @@ -0,0 +1,36 @@ +use std::{env, path::PathBuf}; + +pub fn build() { + println!("cargo:rerun-if-env-changed=GP_IOS_NATIVE_PREFIX"); + let prefix = PathBuf::from(env::var_os("GP_IOS_NATIVE_PREFIX").expect( + "Set GP_IOS_NATIVE_PREFIX to target-built OpenConnect/GnuTLS libraries with an aarch64-apple-ios target.txt receipt", + )); + let target = std::fs::read_to_string(prefix.join("target.txt")).expect("Missing iOS native target receipt"); + assert_eq!( + target.trim(), + env::var("TARGET").unwrap(), + "Native library target mismatch" + ); + for name in ["openconnect", "gnutls", "hogweed", "nettle", "gmp"] { + let archive = prefix.join(format!("lib/lib{name}.a")); + assert!(archive.is_file(), "Missing {}", archive.display()); + println!("cargo:rerun-if-changed={}", archive.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(prefix.join("include")) + .flag("-fapplication-extension") + .compile("vpn"); + println!("cargo:rustc-link-search=native={}", prefix.join("lib").display()); + for name in ["openconnect", "gnutls", "hogweed", "nettle", "gmp"] { + println!("cargo:rustc-link-lib=static={name}"); + } + for name in ["xml2", "z", "iconv", "resolv"] { + println!("cargo:rustc-link-lib={name}"); + } + println!("cargo:rustc-link-lib=framework=Security"); + println!("cargo:rustc-link-lib=framework=CoreFoundation"); +} diff --git a/crates/openconnect/deps/openconnect b/crates/openconnect/deps/openconnect index 33b3d7a..43b36d7 160000 --- a/crates/openconnect/deps/openconnect +++ b/crates/openconnect/deps/openconnect @@ -1 +1 @@ -Subproject commit 33b3d7a01d2fdcbc68652d63d69387ed599c244b +Subproject commit 43b36d7293804d66a27addad54a2b3b78ae8f789 diff --git a/crates/openconnect/src/ffi/mod.rs b/crates/openconnect/src/ffi/mod.rs index 26d3512..cfd44b7 100644 --- a/crates/openconnect/src/ffi/mod.rs +++ b/crates/openconnect/src/ffi/mod.rs @@ -44,6 +44,7 @@ pub(crate) struct ConnectOptions { pub interface: *const c_char, pub script_tun: u32, pub script_tun_launch: *const ScriptTunLaunchRaw, + pub packet_fd: c_int, pub certificate: *const c_char, pub sslkey: *const c_char, diff --git a/crates/openconnect/src/ffi/vpn.c b/crates/openconnect/src/ffi/vpn.c index 4d8fbaa..0023344 100644 --- a/crates/openconnect/src/ffi/vpn.c +++ b/crates/openconnect/src/ffi/vpn.c @@ -52,9 +52,13 @@ static void observe_statistics(void *private_data, const struct oc_stats *stats) } /* Validate the peer certificate */ -static int validate_peer_cert(__attribute__((unused)) void *_vpninfo, +static int validate_peer_cert(void *private_data, const char *reason) { + struct vpn_context *context = 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); return 0; } @@ -82,7 +86,10 @@ static void setup_tun_handler(void *private_data) struct openconnect_info *_vpninfo = context->vpninfo; const vpn_options *options = context->options; int ret; - if (options->script_tun) { + if (options->packet_fd >= 0) { + int fd = dup(options->packet_fd); + ret = fd < 0 ? -errno : openconnect_setup_tun_fd_with_config(_vpninfo, fd); + } else if (options->script_tun) { const struct openconnect_script_tun_launch *launch = options->script_tun_launch; if (launch) { ret = openconnect_setup_tun_script_exec(_vpninfo, launch); @@ -156,6 +163,9 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback) } context.vpninfo = vpninfo; + /* A supplied pin is authoritative even when the system would trust a CA. */ + if (options->servercert) + openconnect_set_system_trust(vpninfo, 0); openconnect_set_tunnel_handler(vpninfo, observe_tunnel); openconnect_set_reconnected_handler(vpninfo, observe_reconnected); openconnect_set_stats_handler(vpninfo, observe_statistics); diff --git a/crates/openconnect/src/ffi/vpn.h b/crates/openconnect/src/ffi/vpn.h index e159a76..6ec44e8 100644 --- a/crates/openconnect/src/ffi/vpn.h +++ b/crates/openconnect/src/ffi/vpn.h @@ -48,6 +48,7 @@ typedef struct vpn_options { const char *interface; const int script_tun; const struct openconnect_script_tun_launch *script_tun_launch; + const int packet_fd; const char *certificate; const char *sslkey; diff --git a/crates/openconnect/src/vpn.rs b/crates/openconnect/src/vpn.rs index c38110b..e2c87f3 100644 --- a/crates/openconnect/src/vpn.rs +++ b/crates/openconnect/src/vpn.rs @@ -151,6 +151,7 @@ pub struct Vpn { interface: Option, script_tun: bool, script_tun_launch: Option, + packet_endpoint: Option, certificate: Option, sslkey: Option, @@ -314,6 +315,7 @@ impl Vpn { interface: Self::option_to_ptr(&self.interface), script_tun: self.script_tun as u32, script_tun_launch: std::ptr::null(), + packet_fd: self.packet_endpoint.as_ref().map_or(-1, AsRawFd::as_raw_fd), certificate: Self::option_to_ptr(&self.certificate), sslkey: Self::option_to_ptr(&self.sslkey), @@ -382,6 +384,7 @@ pub struct VpnBuilder { interface: Option, script_tun: bool, script_tun_launch: Option, + packet_endpoint: Option, user_agent: Option, os: Option, @@ -393,6 +396,7 @@ pub struct VpnBuilder { certificate: Option, sslkey: Option, key_password: Option, + servercert: Option, hip_source: Arc, @@ -417,6 +421,7 @@ impl VpnBuilder { interface: None, script_tun: false, script_tun_launch: None, + packet_endpoint: None, user_agent: None, os: None, @@ -428,6 +433,7 @@ impl VpnBuilder { certificate: None, sslkey: None, key_password: None, + servercert: None, hip_source: Arc::new(HipSource::Disabled), @@ -441,6 +447,16 @@ impl VpnBuilder { } } + /// Use an application-owned packet descriptor. OpenConnect borrows a duplicate + /// during connect; this owner remains alive until the Vpn is dropped. Apple/BSD + /// endpoints use the native four-byte, network-order address-family prefix. + /// Requires callback configuration and a SHA-256 server public-key pin. + pub fn packet_endpoint(mut self, endpoint: OwnedFd, server_pin: String) -> Self { + self.packet_endpoint = Some(endpoint); + self.servercert = Some(server_pin); + self + } + pub fn script>>(mut self, script: T) -> Self { self.script = script.into(); self.script_is_path = false; @@ -618,6 +634,24 @@ impl VpnBuilder { } pub fn build(self) -> Result { + if self.packet_endpoint.is_some() { + let pin = self.servercert.as_deref().unwrap_or_default(); + if self.network_configuration_handler.is_none() + || self.interface.is_some() + || self.script.is_some() + || self.script_tun + || self.script_tun_launch.is_some() + { + return Err(VpnError::new( + "Packet endpoint requires callback configuration and no device/script options".into(), + )); + } + if !pin.starts_with("pin-sha256:") || pin.len() != 55 || pin.contains('\0') { + return Err(VpnError::new( + "Packet endpoint requires a pin-sha256 server public-key fingerprint".into(), + )); + } + } if self.script_tun_launch.is_some() && !self.script_tun { return Err(VpnError::new("Child identity requires script-tun".into())); } @@ -643,11 +677,12 @@ impl VpnBuilder { interface: self.interface.as_deref().map(Self::to_cstring), script_tun: self.script_tun, script_tun_launch: self.script_tun_launch, + packet_endpoint: self.packet_endpoint, certificate: self.certificate.as_deref().map(Self::to_cstring), sslkey: self.sslkey.as_deref().map(Self::to_cstring), key_password: self.key_password.as_deref().map(Self::to_cstring), - servercert: None, + servercert: self.servercert.as_deref().map(Self::to_cstring), hip_source: self.hip_source, @@ -775,6 +810,7 @@ mod tests { interface: None, script_tun: false, script_tun_launch: None, + packet_endpoint: None, certificate: None, sslkey: None, key_password: None, diff --git a/crates/openconnect/tests/esp_gateway.c b/crates/openconnect/tests/esp_gateway.c index 98a9bff..af7edff 100644 --- a/crates/openconnect/tests/esp_gateway.c +++ b/crates/openconnect/tests/esp_gateway.c @@ -75,6 +75,58 @@ int inspect_esp_packet(struct openconnect_info *vpninfo, struct pkt *pkt, uint8_ return 1; } +/* Check the real request builder without a VPN server. Desktop payloads stay exact. */ +static void getconfig_profile_parameters(void) +{ + const char *platforms[] = { "linux", "mac-intel", "win", "apple-ios" }; + const char *names[] = { "Linux", "Mac", "Windows", "iOS" }; + int i; + for (i = 0; i < 4; i++) { + struct openconnect_info *vpninfo = openconnect_vpninfo_new("test", NULL, NULL, NULL, NULL, NULL); + struct oc_text_buf *body = buf_alloc(); + char expected[2048]; + assert(vpninfo && body); + assert(!openconnect_set_reported_os(vpninfo, platforms[i])); + assert(!openconnect_set_gp_app_version(vpninfo, "6.3.5-28")); + assert(!openconnect_set_gp_os_version(vpninfo, "test-os")); + assert(!openconnect_set_gp_host_id(vpninfo, "HOSTID")); + assert(!openconnect_set_cookie(vpninfo, "user=test&portal=portal&authcookie=fixture&computer=Phone&preferred-ip=192.0.2.5")); + assert(!gpst_build_getconfig_request(vpninfo, body)); + if (i == 3) { + assert(strstr(body->data, "clientos=iOS")); + assert(strstr(body->data, "vpn-type=App%20Level%20VPN")); + assert(strstr(body->data, "client-ip=&client-ipv6=&serialno=&joined-domain=")); + assert(strstr(body->data, "user=test") && strstr(body->data, "authcookie=fixture")); + assert(strstr(body->data, "preferred-ip=192.0.2.5")); + assert(!strstr(body->data, "host-id=") && !strstr(body->data, "clientgpversion=") && !strstr(body->data, "computer=")); + buf_truncate(body); + vpninfo->ip_info.addr = strdup("192.0.2.6"); + assert(!gpst_build_getconfig_request(vpninfo, body)); + assert(strstr(body->data, "preferred-ip=192.0.2.6")); + assert(!strstr(body->data, "192.0.2.5")); + /* The connected HTTPS socket supplies the actual local client address. */ + int fd = socket(AF_INET, SOCK_STREAM, 0); + struct sockaddr_in local = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) }; + assert(fd >= 0 && !bind(fd, (struct sockaddr *)&local, sizeof(local))); + vpninfo->ssl_fd = fd; + buf_truncate(body); + assert(!gpst_build_getconfig_request(vpninfo, body)); + assert(strstr(body->data, "client-ip=127.0.0.1&client-ipv6=")); + vpninfo->ssl_fd = -1; + close(fd); + } else { + snprintf(expected, sizeof(expected), + "client-type=1&protocol-version=p1&internal=no&app-version=6.3.5-28&ipv6-support=yes" + "&clientos=%s&os-version=test-os&hmac-algo=sha1%%2c&enc-algo=aes-256-gcm%%2caes-128-gcm%%2caes-128-cbc%%2c" + "&clientgpversion=6.3.5-28&host-id=HOSTID&user=test&portal=portal&authcookie=fixture&computer=Phone&preferred-ip=192.0.2.5", + names[i]); + assert(!strcmp(body->data, expected)); + } + buf_free(body); + openconnect_vpninfo_free(vpninfo); + } +} + int main(int argc, char **argv) { static const char key[] = @@ -92,6 +144,7 @@ int main(int argc, char **argv) int sockets[2], nlb, invalid, length; assert(argc == 2); + getconfig_profile_parameters(); nlb = !strncmp(argv[1], "nlb-", 4); invalid = !strcmp(argv[1], "regular-invalid") || !strcmp(argv[1], "regular-missing"); if (!strcmp(argv[1], "regular-address") || !strcmp(argv[1], "nlb-address")) diff --git a/crates/openconnect/tests/network_configuration.c b/crates/openconnect/tests/network_configuration.c index 0c2644f..53cb4b0 100644 --- a/crates/openconnect/tests/network_configuration.c +++ b/crates/openconnect/tests/network_configuration.c @@ -160,6 +160,59 @@ static void reconnect_refusal_propagates(void) openconnect_vpninfo_free(vpninfo); } +static void external_packets_and_configuration(void) +{ + struct state state = { .parent = getpid(), .reason = "connect" }; + struct openconnect_info *vpninfo = new_vpn(&state); + int fds[2], families[] = { AF_INET, AF_INET6 }; + int creations = device_creations; + assert(!socketpair(AF_UNIX, SOCK_DGRAM, 0, fds)); + assert(!openconnect_setup_tun_fd_with_config(vpninfo, fds[0])); + assert(device_creations == creations); + assert(state.calls == 1); + for (int i = 0; i < 2; i++) { + unsigned char frame[1504] = {0}, received[1504]; + struct pkt *packet = alloc_pkt(vpninfo, 1500); + int prefix = 0, length = i ? 40 : 20; +#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) + uint32_t family = htonl(families[i]); + memcpy(frame, &family, 4); + prefix = 4; +#endif + frame[prefix] = i ? 0x60 : 0x45; + assert(write(fds[1], frame, length + prefix) == length + prefix); + packet->len = 1500; + assert(!os_read_tun(vpninfo, packet)); + assert(packet->len == length); + assert(!memcmp(packet->data, frame + prefix, length)); + assert(!os_write_tun(vpninfo, packet)); + assert(read(fds[1], received, sizeof(received)) == length + prefix); + assert(!memcmp(received, frame, length + prefix)); + free_pkt(vpninfo, packet); + } + state.reason = "disconnect"; + openconnect_vpninfo_free(vpninfo); + assert(state.calls == 2); + assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF); + close(fds[1]); + + state.calls = 0; + state.reason = "connect"; + state.failure_reason = "connect"; + state.result = -EPERM; + const char *reasons[] = { "connect", "disconnect" }; + state.expected_reasons = reasons; + state.expected_count = 2; + vpninfo = new_vpn(&state); + assert(!socketpair(AF_UNIX, SOCK_DGRAM, 0, fds)); + assert(openconnect_setup_tun_fd_with_config(vpninfo, fds[0]) == -EPERM); + assert(vpninfo->tun_fd == -1); + assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF); + openconnect_vpninfo_free(vpninfo); + assert(state.calls == 2); + close(fds[1]); +} + int main(void) { const char *reasons[] = { "pre-init", "connect", "attempt-reconnect", "reconnect", "disconnect" }; @@ -199,5 +252,6 @@ int main(void) openconnect_vpninfo_free(vpninfo); connect_failure_rolls_back(); reconnect_refusal_propagates(); + external_packets_and_configuration(); return 0; }