mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: add portable GlobalProtect APIs and iOS tunnel support
This commit is contained in:
112 files changed
+3864
-3011
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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<PathBuf> {
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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<Notice>,
|
||||
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(),
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -87,14 +87,14 @@ pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result<Ap
|
||||
}
|
||||
|
||||
pub fn resolve(approval_id: &str, desktop_uid: u32) -> anyhow::Result<ApprovedScript> {
|
||||
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<ApprovedScript> {
|
||||
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<ApprovedScript> {
|
||||
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<ApprovedScript> {
|
||||
control.check()?;
|
||||
let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?;
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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<String> {
|
||||
control.check()?;
|
||||
@@ -177,9 +177,9 @@ pub(crate) fn profile(
|
||||
os_version: Option<String>,
|
||||
host_id: Option<String>,
|
||||
hostname: Option<String>,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
control: &dyn gpapi::collection::CollectionControl,
|
||||
) -> io::Result<OsProfile> {
|
||||
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");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -420,7 +420,7 @@ enum LifecycleEvent {
|
||||
MembersChanged {
|
||||
attempt: u64,
|
||||
members: Vec<gpapi::session::GatewaySessionSummary>,
|
||||
failures: Vec<gpapi::session::GatewayFailureSummary>,
|
||||
failures: Vec<gpapi::session::desktop::GatewayFailureSummary>,
|
||||
},
|
||||
Ended {
|
||||
attempt: u64,
|
||||
@@ -679,7 +679,7 @@ impl VpnTask {
|
||||
&self,
|
||||
attempt: u64,
|
||||
members: Vec<gpapi::session::GatewaySessionSummary>,
|
||||
failures: Vec<gpapi::session::GatewayFailureSummary>,
|
||||
failures: Vec<gpapi::session::desktop::GatewayFailureSummary>,
|
||||
) {
|
||||
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())
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<LifecycleEvent>,
|
||||
) {
|
||||
|
||||
@@ -60,7 +60,7 @@ pub(super) async fn run(
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
session_id: uuid::Uuid,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
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<gpapi::session::tunnel::NegotiatedNetwork> {
|
||||
) -> anyhow::Result<gpapi::session::desktop::tunnel::NegotiatedNetwork> {
|
||||
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()
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) struct ConnectionControl {
|
||||
connection_id: Uuid,
|
||||
tx: mpsc::Sender<ConnectionCommand>,
|
||||
close_tx: watch::Sender<Option<CloseReason>>,
|
||||
statistics: watch::Sender<Option<gpapi::session::tunnel::TunnelStatisticsSnapshot>>,
|
||||
statistics: watch::Sender<Option<gpapi::session::desktop::tunnel::TunnelStatisticsSnapshot>>,
|
||||
statistics_enabled: Arc<AtomicBool>,
|
||||
committed: Arc<AtomicBool>,
|
||||
}
|
||||
@@ -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<Option<gpapi::session::tunnel::TunnelStatisticsSnapshot>> {
|
||||
pub fn subscribe_statistics(
|
||||
&self,
|
||||
) -> watch::Receiver<Option<gpapi::session::desktop::tunnel::TunnelStatisticsSnapshot>> {
|
||||
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();
|
||||
|
||||
@@ -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];
|
||||
|
||||
+15
-13
@@ -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"]
|
||||
+38
-14
@@ -12,6 +12,16 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
|
||||
|
||||
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
|
||||
|
||||
/// 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<SamlAuthData, AuthDataParseError> {
|
||||
@@ -217,6 +221,26 @@ fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
|
||||
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!("<saml-auth-status>{status}</saml-auth-status>");
|
||||
assert!(matches!(
|
||||
SamlAuthData::from_html(&html),
|
||||
Err(AuthDataParseError::AuthenticationFailed(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_data_from_gpcallback_cas() {
|
||||
let auth_data = "globalprotectcallback:cas-as=1&[email protected]&token=very_long_string";
|
||||
|
||||
@@ -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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<F: Fn() -> 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(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}")]
|
||||
|
||||
@@ -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
|
||||
|
||||
File renamed without changes.
@@ -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<GatewayBinding>,
|
||||
login_endpoint: Option<SocketAddr>,
|
||||
login_url: Option<reqwest::Url>,
|
||||
maintenance_client: Option<Client>,
|
||||
peer_certificate: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
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<Self> {
|
||||
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<SocketAddr> {
|
||||
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<Vec<u8>>,
|
||||
login: GatewayLogin,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
}
|
||||
|
||||
struct ReceivedLogin {
|
||||
peer_certificate: Option<Vec<u8>>,
|
||||
body: String,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
@@ -260,17 +193,26 @@ async fn receive_gateway_login(
|
||||
}
|
||||
})?;
|
||||
|
||||
let peer_certificate = res
|
||||
.extensions()
|
||||
.get::<reqwest::tls::TlsInfo>()
|
||||
.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<LoginResponse> {
|
||||
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("<response status='success'/>"),
|
||||
])
|
||||
.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,
|
||||
|
||||
@@ -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<PriorityRule>,
|
||||
}
|
||||
|
||||
|
||||
@@ -21,17 +21,26 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
|
||||
pub struct SessionExtensionAuth {
|
||||
credential: Credential,
|
||||
client: GatewayLoginClient,
|
||||
binding: Option<crate::session::desktop::network::GatewayBinding>,
|
||||
}
|
||||
|
||||
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<crate::session::desktop::network::GatewayBinding>) -> 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)
|
||||
|
||||
@@ -162,6 +162,7 @@ impl GpParams {
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
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());
|
||||
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
@@ -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<NativeHostIdentitySnapshot> {
|
||||
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<Option<String>> {
|
||||
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<Option<String>> {
|
||||
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<Option<String>> {
|
||||
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<String> {
|
||||
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<Option<String>> {
|
||||
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<Option<String>> {
|
||||
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),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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<HostIdentity> {
|
||||
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<HostIdentity> {
|
||||
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<String>,
|
||||
mac_address: Option<String>,
|
||||
}
|
||||
|
||||
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::<Vec<_>>();
|
||||
|
||||
bytes.join(":")
|
||||
}
|
||||
|
||||
fn normalize_mac_colon(value: &str) -> Option<String> {
|
||||
let compact = value
|
||||
.trim()
|
||||
.replace('-', ":")
|
||||
.split(':')
|
||||
.map(|part| part.to_lowercase())
|
||||
.collect::<Vec<_>>();
|
||||
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<String> {
|
||||
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<OsProfile> {
|
||||
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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<NativeHostIdentitySnapshot> {
|
||||
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<String> {
|
||||
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
|
||||
}
|
||||
|
||||
fn normalize_uuid(value: &str) -> Option<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String>,
|
||||
product_uuid: impl FnOnce() -> Option<String>,
|
||||
) -> Option<String> {
|
||||
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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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<NativeHostIdentitySnapshot> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
|
||||
}
|
||||
|
||||
fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||
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<String> {
|
||||
let output = Command::new("reg")
|
||||
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
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<Self> {
|
||||
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<String>,
|
||||
mac_address: Option<String>,
|
||||
}
|
||||
|
||||
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::<Vec<_>>();
|
||||
|
||||
bytes.join(":")
|
||||
}
|
||||
|
||||
fn normalize_mac_colon(value: &str) -> Option<String> {
|
||||
let compact = value
|
||||
.trim()
|
||||
.replace('-', ":")
|
||||
.split(':')
|
||||
.map(|part| part.to_lowercase())
|
||||
.collect::<Vec<_>>();
|
||||
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<String> {
|
||||
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<NativeHostIdentitySnapshot> {
|
||||
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<Option<String>> {
|
||||
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<Option<String>> {
|
||||
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<Option<String>> {
|
||||
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<String> {
|
||||
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<Option<String>> {
|
||||
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<Option<String>> {
|
||||
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<NativeHostIdentitySnapshot> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
|
||||
}
|
||||
|
||||
fn collect_windows_csproduct_uuid() -> Option<String> {
|
||||
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<String> {
|
||||
let output = Command::new("reg")
|
||||
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
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<NativeHostIdentitySnapshot> {
|
||||
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<String> {
|
||||
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
|
||||
}
|
||||
|
||||
fn normalize_uuid(value: &str) -> Option<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String>,
|
||||
product_uuid: impl FnOnce() -> Option<String>,
|
||||
) -> Option<String> {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+27
-1387
File diff suppressed because it is too large.
Load diff
@@ -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<String>,
|
||||
) -> 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<String>,
|
||||
pub(super) os_version_override: Option<String>,
|
||||
pub(super) computer_name_override: Option<String>,
|
||||
pub(super) host_identity: Option<HostIdentity>,
|
||||
pub(super) user_agent: Option<String>,
|
||||
}
|
||||
|
||||
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<String>) -> Self {
|
||||
self.computer_name_override = Some(name.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_version(mut self, version: impl Into<String>) -> Self {
|
||||
self.client_version = Some(version.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Preserve an explicitly negotiated operating system version.
|
||||
pub fn os_version(mut self, version: impl Into<String>) -> 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<String>) -> 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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::<Vec<_>>();
|
||||
|
||||
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<String>,
|
||||
) -> 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>) -> 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<String>,
|
||||
) -> 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<String>) -> 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<String>) -> 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<String>) -> 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");
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<InternalSessionPolicy>,
|
||||
}
|
||||
|
||||
/// Parsed portal policy before a caller chooses network-location candidates.
|
||||
pub struct PortalPolicy {
|
||||
config: PortalConfig,
|
||||
internal_gateways: Vec<Gateway>,
|
||||
external_gateways: Vec<Gateway>,
|
||||
}
|
||||
|
||||
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<bool>) -> 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<PortalConfig> {
|
||||
) -> anyhow::Result<PortalPolicy> {
|
||||
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<PortalConfig> {
|
||||
) -> anyhow::Result<PortalPolicy> {
|
||||
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<Option<Internal
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn parsed_policy_keeps_location_selection_explicit() {
|
||||
let xml = "<policy><internal-host-detection><ip-address>192.0.2.1</ip-address><host>inside.example</host></internal-host-detection><gateways><internal><list><entry name='internal.example'/></list></internal><external><list><entry name='external.example'/></list></external></gateways></policy>";
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let policy = parse_portal_policy("portal.example", &credential, parse_xml(xml), &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(policy.detection().is_some());
|
||||
let external = policy.external_gateways();
|
||||
assert_eq!(external.gateways()[0].server(), "external.example");
|
||||
assert_eq!(external.internal_host_detection(), None);
|
||||
let policy = parse_portal_policy("portal.example", &credential, parse_xml(xml), &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let internal = policy.select_gateways(true, Some(true));
|
||||
assert_eq!(internal.gateways()[0].server(), "internal.example");
|
||||
assert_eq!(internal.internal_host_detection(), Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_candidates_preserve_portal_gateway_fallback() {
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
for detected in [None, Some(false), Some(true)] {
|
||||
let policy = parse_portal_policy(
|
||||
"portal.example",
|
||||
&credential,
|
||||
parse_xml("<policy/>"),
|
||||
&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(
|
||||
"<policy><hip-collection><hip-report-interval>invalid</hip-report-interval></hip-collection><internal-host-detection><ip-address>invalid</ip-address><host>internal.example</host></internal-host-detection><gateways><external><list><entry name='vpn.example'/></list></external></gateways></policy>",
|
||||
);
|
||||
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");
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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<PortalConfig> {
|
||||
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))
|
||||
}
|
||||
@@ -4,3 +4,6 @@ mod prelogin;
|
||||
|
||||
pub use config::*;
|
||||
pub use prelogin::*;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod discovery;
|
||||
@@ -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<Prelogin> {
|
||||
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<Prelogin> {
|
||||
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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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<F: Fn() -> 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",
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<crate::session::tunnel::TunnelState>),
|
||||
TunnelState(Option<crate::session::desktop::tunnel::TunnelState>),
|
||||
VpnEnv(VpnEnv),
|
||||
VpnState(VpnState),
|
||||
ActiveGui,
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -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<crate::session::tunnel::TunnelState>,
|
||||
pub tunnel_state: Option<crate::session::desktop::tunnel::TunnelState>,
|
||||
/// The VPN connection state
|
||||
pub vpn_state: VpnState,
|
||||
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -145,130 +145,6 @@ impl TryFrom<InternalSessionPolicyFields> for InternalSessionPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct AuthenticatedGateway {
|
||||
pub gateway: Gateway,
|
||||
pub authentication: GatewayAuthentication,
|
||||
pub binding: Option<super::network::GatewayBinding>,
|
||||
}
|
||||
|
||||
#[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<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<super::network::InternalHostDetection>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ConnectionPlanFields {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<super::network::InternalHostDetection>,
|
||||
}
|
||||
|
||||
impl TryFrom<ConnectionPlanFields> for ConnectionPlan {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: ConnectionPlanFields) -> Result<Self, Self::Error> {
|
||||
Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionPlan {
|
||||
pub fn new(
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
) -> anyhow::Result<Self> {
|
||||
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<super::network::InternalHostDetection>) -> 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::<GatewayAuthentication>(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::<InternalSessionPolicy>(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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
use super::*;
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct AuthenticatedGateway {
|
||||
pub gateway: Gateway,
|
||||
pub authentication: GatewayAuthentication,
|
||||
pub binding: Option<crate::session::desktop::network::GatewayBinding>,
|
||||
}
|
||||
|
||||
#[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<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<crate::session::InternalHostDetection>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ConnectionPlanFields {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<crate::session::InternalHostDetection>,
|
||||
}
|
||||
|
||||
impl TryFrom<ConnectionPlanFields> for ConnectionPlan {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: ConnectionPlanFields) -> Result<Self, Self::Error> {
|
||||
Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionPlan {
|
||||
pub fn new(
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
) -> anyhow::Result<Self> {
|
||||
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<crate::session::InternalHostDetection>) -> 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::<GatewayAuthentication>(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::<InternalSessionPolicy>(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));
|
||||
}
|
||||
}
|
||||
+71
@@ -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<super::network::GatewayBinding> {
|
||||
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<GatewaySession>) {
|
||||
Err(_) => log::warn!("Gateway logout timed out"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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!(
|
||||
"<jnlp><application-desc>{}</application-desc></jnlp>",
|
||||
arguments
|
||||
.iter()
|
||||
.map(|value| format!("<argument>{value}</argument>"))
|
||||
.collect::<String>()
|
||||
);
|
||||
let (_, origin, server) = login_gateway(vec![response(&xml), response("<response status='success'/>")]).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"));
|
||||
}
|
||||
@@ -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};
|
||||
+1
-1
@@ -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"
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+19
-7
@@ -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<GatewayBinding> {
|
||||
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<bool> {
|
||||
for (address, hostname) in policy.targets() {
|
||||
if native::detect(address, hostname, cancellation).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
+1
-1
@@ -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,
|
||||
+3
-5
@@ -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);
|
||||
|
||||
+2
-1
@@ -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},
|
||||
};
|
||||
|
||||
File renamed without changes.
+5
-8
@@ -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<bool> {
|
||||
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<Item = (IpAddr, &str)> {
|
||||
self
|
||||
.targets
|
||||
.iter()
|
||||
.map(|target| (target.address, target.hostname.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Self> {
|
||||
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<Client> {
|
||||
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<reqwest::ClientBuilder> {
|
||||
Ok(builder.interface(binding.interface()))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
if let std::net::SocketAddr::V6(source) = binding.source() {
|
||||
anyhow::ensure!(
|
||||
source.scope_id() == 0,
|
||||
"Scoped IPv6 source requires a native socket connector"
|
||||
);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_origin(server: &str) -> anyhow::Result<Url> {
|
||||
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)
|
||||
}
|
||||
@@ -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<Self> {
|
||||
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<Client> {
|
||||
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<reqwest::ClientBuilder> {
|
||||
Ok(builder.interface(binding.interface()))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
if let std::net::SocketAddr::V6(source) = binding.source() {
|
||||
anyhow::ensure!(
|
||||
source.scope_id() == 0,
|
||||
"Scoped IPv6 source requires a native socket connector"
|
||||
);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_origin(server: &str) -> anyhow::Result<Url> {
|
||||
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()));
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+2
-2
@@ -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<Vec<u8>>, limit: u64
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
pub(in crate::utils) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
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.
|
||||
@@ -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;
|
||||
@@ -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(())
|
||||
}
|
||||
+2
-2
@@ -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.
|
||||
+2
-2
@@ -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))
|
||||
+2
-2
@@ -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>,
|
||||
+2
-2
@@ -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>,
|
||||
@@ -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<SecretDocumen
|
||||
// PKCS#12 PBE-SHA1-3DES inside standalone PKCS#8 is not implemented by
|
||||
// RustCrypto. Only this known legacy scheme uses the optional executable.
|
||||
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
|
||||
return super::legacy_pkcs8::decrypt(der, passphrase);
|
||||
#[cfg(feature = "desktop")]
|
||||
return super::certificate::legacy_pkcs8::decrypt(der, passphrase);
|
||||
#[cfg(not(feature = "desktop"))]
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
}
|
||||
|
||||
@@ -1,35 +1,28 @@
|
||||
pub mod xml;
|
||||
|
||||
pub mod base64;
|
||||
mod certificate;
|
||||
pub mod checksum;
|
||||
pub mod crypto;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod endpoint;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod env_utils;
|
||||
mod identity_encoding;
|
||||
mod legacy_pkcs8;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod lock_file;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
pub mod openssl;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "pkcs12_identity/macos.rs"]
|
||||
mod pkcs12_identity;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "pkcs12_identity/openssl.rs"]
|
||||
mod pkcs12_identity;
|
||||
pub mod redact;
|
||||
pub mod request;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "traditional_key/macos.rs"]
|
||||
mod traditional_key;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "traditional_key/openssl.rs"]
|
||||
mod traditional_key;
|
||||
#[cfg(feature = "tauri")]
|
||||
pub mod window;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
mod shutdown_signal;
|
||||
|
||||
use log::warn;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub use shutdown_signal::shutdown_signal;
|
||||
|
||||
use reqwest::{Response, StatusCode, Url};
|
||||
@@ -74,6 +67,10 @@ impl GpError {
|
||||
pub fn is_status_error(&self) -> 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<String, GpError> {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -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::<AuthenticationRejected>(),
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<DefenderInfo> {
|
||||
/// 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<String>) -> Option<String> {
|
||||
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]
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user