feat: add portable GlobalProtect APIs and iOS tunnel support

This commit is contained in:
Kevin Yue committed 2026-11-01 23:34:18 +08:00
1 parent 4f8f828a0b
commit da90bc80e3
112 files changed
+3864 -3011

No files matched your search

+15 -13
View File
@@ -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
View File
@@ -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 -1
View File
@@ -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"),
}
}
}
+41
View File
@@ -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(())
}
}
}
+5
View File
@@ -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}")]
+10 -8
View File
@@ -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, &params, 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, &params, 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
+43 -94
View File
@@ -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(&params)?;
@@ -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,
+4
View File
@@ -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>,
}
+14 -5
View File
@@ -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)
+42 -27
View File
@@ -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(&params);
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(&params);
@@ -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(&params);
@@ -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(&params);
@@ -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(&params);
@@ -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());
+7
View File
@@ -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;
+163
View File
@@ -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,
}
}
}
+26
View File
@@ -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),
)
}
}
+242
View File
@@ -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);
}
+136
View File
@@ -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()));
}
}
}
+56
View File
@@ -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
}
}
File diff suppressed because it is too large. Load diff
+277
View File
@@ -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,
}
}
}
+171
View File
@@ -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");
}
}
+634
View File
@@ -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());
}
}
}
+48 -6
View File
@@ -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: &params,
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 {
+7 -7
View File
@@ -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
+23 -3
View File
@@ -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(), &params, "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 {
+9 -9
View File
@@ -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");
+107 -46
View File
@@ -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");
+2 -2
View File
@@ -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()
}
+29
View File
@@ -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))
}
+3
View File
@@ -4,3 +4,6 @@ mod prelogin;
pub use config::*;
pub use prelogin::*;
#[cfg(feature = "desktop")]
pub mod discovery;
+13 -2
View File
@@ -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()
}
+9 -3
View File
@@ -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);
+5 -38
View File
@@ -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",
+1 -1
View File
@@ -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> {
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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 -5
View File
@@ -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 [
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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)]
+4 -5
View File
@@ -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 {
-158
View File
@@ -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));
}
}
@@ -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"));
}
+12
View File
@@ -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};
@@ -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"
@@ -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)
}
@@ -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,
@@ -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);
@@ -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},
};
@@ -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()));
+4 -1
View File
@@ -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)
}
@@ -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.
+18
View File
@@ -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(())
}
@@ -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.
@@ -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))
@@ -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>,
@@ -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>,
+5 -2
View File
@@ -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());
}
+11 -14
View File
@@ -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> {
+1 -1
View File
@@ -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 {
+17
View File
@@ -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, &params, &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));
}
}
}
}
}
+35
View File
@@ -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");
}
+7 -5
View File
@@ -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]
+3 -1
View File
@@ -1,6 +1,8 @@
use std::net::{Ipv4Addr, Ipv6Addr};
use gpapi::session::tunnel::{MAX_CONFIGURATION_BYTES, TunnelAddress, TunnelConfiguration, TunnelList, TunnelState};
use gpapi::session::desktop::tunnel::{
MAX_CONFIGURATION_BYTES, TunnelAddress, TunnelConfiguration, TunnelList, TunnelState,
};
use log::{debug, info};
use openconnect::tunnel::{Configuration, NativeList};
+1 -1
View File
@@ -3,7 +3,7 @@ use std::{
time::Duration,
};
use gpapi::session::tunnel::{
use gpapi::session::desktop::tunnel::{
TunnelPhase, TunnelState, TunnelStatistics, TunnelStatisticsSnapshot, TunnelStatisticsState, TunnelStatisticsView,
TunnelTransport,
};
+8 -246
View File
@@ -1,250 +1,12 @@
use std::{env, path::PathBuf};
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2");
let install_dir = out_dir.join("libxml2_install");
// The temporary location where we will build
let build_src = out_dir.join("libxml2_build");
// Track changes so cargo rebuilds if submodule changes
println!("cargo:rerun-if-changed={}", libxml2_dir.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
if install_dir.exists() {
std::fs::remove_dir_all(&install_dir).unwrap();
}
std::fs::create_dir_all(&install_dir).unwrap();
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Build the libxml2 library using autotools
let dst = {
let mut config = autotools::Config::new(&build_src);
config
.out_dir(&install_dir)
.reconf("-ivf")
.enable_static()
.disable_shared()
// Disable optional features that complicate static builds
.with("python", Some("no"))
.with("icu", Some("no"))
.with("http", Some("no"))
.with("ftp", Some("no"))
.with("catalog", Some("no"))
.with("docbook", Some("no"))
.with("legacy", Some("no"))
.with("threads", Some("no"))
.with("zlib", Some("no"))
.with("lzma", Some("no"))
// Ensure position-independent code (safe for static linking)
.cflag("-fPIC");
config.build()
};
let lib_dir = dst.join("lib");
let include_dir = dst.join("include/libxml2");
// Tell rustc where to find the static library
println!("cargo:rustc-link-search=native={}", lib_dir.display());
// Static linking of libxml2
println!("cargo:rustc-link-lib=static=xml2");
// Export include path for downstream use (bindgen / cc)
println!("cargo:include={}", include_dir.display());
dst
}
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect");
let install_dir = out_dir.join("openconnect_install");
// The temporary location where we will build
let build_src = out_dir.join("openconnect_build");
// Track changes so cargo rebuilds if submodule changes
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
if install_dir.exists() {
std::fs::remove_dir_all(&install_dir).unwrap();
}
std::fs::create_dir_all(&install_dir).unwrap();
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Build the OpenConnect library using autotools. Keep the upstream LGPL
// library dynamically linked on macOS so it remains replaceable in the app
// bundle. Other platforms retain the existing static-link behavior.
let mut config = autotools::Config::new(&build_src);
config
.out_dir(&install_dir)
.reconf("-ivf")
.disable("nls", None) // disable translations to save space
.disable("docs", None)
.disable("dsa-tests", None)
.without("libproxy", None)
.without("stoken", None)
.without("libpcsclite", None)
.without("libpskc", None)
.without("gssapi", None)
.with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS
#[cfg(target_os = "macos")]
{
config
.disable_static()
.enable_shared()
.with("gnutls", None)
.without("openssl", None);
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
#[cfg(not(target_os = "macos"))]
config.enable_static().disable_shared();
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
{
config.ldflag("-L/usr/local/lib");
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
let dst = config.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
#[cfg(target_os = "macos")]
{
let configuration = std::fs::read_to_string(dst.join("build/config.h"))
.expect("Failed to read the OpenConnect TLS backend configuration");
assert!(
configuration.lines().any(|line| line == "#define OPENCONNECT_GNUTLS 1")
&& !configuration
.lines()
.any(|line| line == "#define OPENCONNECT_OPENSSL 1"),
"macOS OpenConnect must use GnuTLS"
);
// Do not embed Cargo's temporary build directory in consumers of this library.
let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap();
let library_name = library.file_name().unwrap().to_str().unwrap();
let status = std::process::Command::new("install_name_tool")
.arg("-id")
.arg(format!("@rpath/{library_name}"))
.arg(&library)
.status()
.expect("Failed to update the OpenConnect dylib install name");
assert!(status.success(), "Failed to update the OpenConnect dylib install name");
let status = std::process::Command::new("codesign")
.args(["--force", "--sign", "-"])
.arg(&library)
.status()
.expect("Failed to sign the OpenConnect dylib");
assert!(status.success(), "Failed to sign the OpenConnect dylib");
println!("cargo:lib_dir={}", lib_dir.display());
}
println!("cargo:rustc-link-search=native={}", lib_dir.display());
#[cfg(target_os = "macos")]
println!("cargo:rustc-link-lib=dylib=openconnect");
#[cfg(not(target_os = "macos"))]
println!("cargo:rustc-link-lib=static=openconnect");
// Export include path for downstream use (bindgen / cc)
println!("cargo:include={}", include_dir.display());
dst
}
#[path = "build/desktop.rs"]
mod desktop;
#[path = "build/ios.rs"]
mod ios;
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let deps_dir = PathBuf::from(manifest_dir).join("deps");
let oc_dst = build_openconnect(&deps_dir, &out_dir);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}",
oc_dst.join("build").display()
);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}",
out_dir.join("openconnect_build").display()
);
// Only statically link libxml2 if `LIBXML2_STATIC` is set
if env::var("LIBXML2_STATIC").is_ok() {
let _libxml2_dst = build_libxml2(&deps_dir, &out_dir);
} else {
// Using pkg-config to find system libxml2
pkg_config::probe_library("libxml-2.0").unwrap();
match std::env::var("CARGO_CFG_TARGET_OS").as_deref() {
Ok("ios") => ios::build(),
Ok("macos" | "linux" | "freebsd" | "openbsd") => desktop::build(),
target => panic!("Unsupported OpenConnect target: {target:?}"),
}
// Using pkg-config to find system deps
pkg_config::probe_library("zlib").unwrap();
#[cfg(target_os = "macos")]
pkg_config::probe_library("gnutls").unwrap();
#[cfg(not(target_os = "macos"))]
{
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
// Below are required by gnutls
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
pkg_config::probe_library("gmp").unwrap();
}
// Compile the vpn.c file
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
{
println!("cargo:rustc-link-search=native=/usr/local/lib");
println!("cargo:rustc-link-lib=iconv");
}
// Prevent silent fallback to dynamic libraries
#[cfg(target_os = "linux")]
{
println!("cargo:rustc-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-link-arg=-Wl,-Bdynamic");
}
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include(&oc_dst.join("include"))
.compile("vpn");
}
+252
View File
@@ -0,0 +1,252 @@
use std::{env, path::PathBuf};
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2");
let install_dir = out_dir.join("libxml2_install");
// The temporary location where we will build
let build_src = out_dir.join("libxml2_build");
// Track changes so cargo rebuilds if submodule changes
println!("cargo:rerun-if-changed={}", libxml2_dir.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
if install_dir.exists() {
std::fs::remove_dir_all(&install_dir).unwrap();
}
std::fs::create_dir_all(&install_dir).unwrap();
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Build the libxml2 library using autotools
let dst = {
let mut config = autotools::Config::new(&build_src);
config
.out_dir(&install_dir)
.reconf("-ivf")
.enable_static()
.disable_shared()
// Disable optional features that complicate static builds
.with("python", Some("no"))
.with("icu", Some("no"))
.with("http", Some("no"))
.with("ftp", Some("no"))
.with("catalog", Some("no"))
.with("docbook", Some("no"))
.with("legacy", Some("no"))
.with("threads", Some("no"))
.with("zlib", Some("no"))
.with("lzma", Some("no"))
// Ensure position-independent code (safe for static linking)
.cflag("-fPIC");
config.build()
};
let lib_dir = dst.join("lib");
let include_dir = dst.join("include/libxml2");
// Tell rustc where to find the static library
println!("cargo:rustc-link-search=native={}", lib_dir.display());
// Static linking of libxml2
println!("cargo:rustc-link-lib=static=xml2");
// Export include path for downstream use (bindgen / cc)
println!("cargo:include={}", include_dir.display());
dst
}
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect");
let install_dir = out_dir.join("openconnect_install");
// The temporary location where we will build
let build_src = out_dir.join("openconnect_build");
// Track changes so cargo rebuilds if submodule changes
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
if install_dir.exists() {
std::fs::remove_dir_all(&install_dir).unwrap();
}
std::fs::create_dir_all(&install_dir).unwrap();
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Build the OpenConnect library using autotools. Keep the upstream LGPL
// library dynamically linked on macOS so it remains replaceable in the app
// bundle. Other platforms retain the existing static-link behavior.
let mut config = autotools::Config::new(&build_src);
config
.out_dir(&install_dir)
.reconf("-ivf")
.disable("nls", None) // disable translations to save space
.disable("docs", None)
.disable("dsa-tests", None)
.without("libproxy", None)
.without("stoken", None)
.without("libpcsclite", None)
.without("libpskc", None)
.without("gssapi", None)
.with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS
if target_os() == "macos" {
config
.disable_static()
.enable_shared()
.with("gnutls", None)
.without("openssl", None);
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
if target_os() != "macos" {
config.enable_static().disable_shared();
}
if matches!(target_os().as_str(), "freebsd" | "openbsd") {
config.ldflag("-L/usr/local/lib");
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
let dst = config.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
if target_os() == "macos" {
let configuration = std::fs::read_to_string(dst.join("build/config.h"))
.expect("Failed to read the OpenConnect TLS backend configuration");
assert!(
configuration.lines().any(|line| line == "#define OPENCONNECT_GNUTLS 1")
&& !configuration
.lines()
.any(|line| line == "#define OPENCONNECT_OPENSSL 1"),
"macOS OpenConnect must use GnuTLS"
);
// Do not embed Cargo's temporary build directory in consumers of this library.
let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap();
let library_name = library.file_name().unwrap().to_str().unwrap();
let status = std::process::Command::new("install_name_tool")
.arg("-id")
.arg(format!("@rpath/{library_name}"))
.arg(&library)
.status()
.expect("Failed to update the OpenConnect dylib install name");
assert!(status.success(), "Failed to update the OpenConnect dylib install name");
let status = std::process::Command::new("codesign")
.args(["--force", "--sign", "-"])
.arg(&library)
.status()
.expect("Failed to sign the OpenConnect dylib");
assert!(status.success(), "Failed to sign the OpenConnect dylib");
println!("cargo:lib_dir={}", lib_dir.display());
}
println!("cargo:rustc-link-search=native={}", lib_dir.display());
if target_os() == "macos" {
println!("cargo:rustc-link-lib=dylib=openconnect");
}
if target_os() != "macos" {
println!("cargo:rustc-link-lib=static=openconnect");
}
// Export include path for downstream use (bindgen / cc)
println!("cargo:include={}", include_dir.display());
dst
}
pub fn build() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let deps_dir = PathBuf::from(manifest_dir).join("deps");
let oc_dst = build_openconnect(&deps_dir, &out_dir);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}",
oc_dst.join("build").display()
);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}",
out_dir.join("openconnect_build").display()
);
// Only statically link libxml2 if `LIBXML2_STATIC` is set
if env::var("LIBXML2_STATIC").is_ok() {
let _libxml2_dst = build_libxml2(&deps_dir, &out_dir);
} else {
// Using pkg-config to find system libxml2
pkg_config::probe_library("libxml-2.0").unwrap();
}
// Using pkg-config to find system deps
pkg_config::probe_library("zlib").unwrap();
if target_os() == "macos" {
pkg_config::probe_library("gnutls").unwrap();
}
if target_os() != "macos" {
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
// Below are required by gnutls
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
pkg_config::probe_library("gmp").unwrap();
}
// Compile the vpn.c file
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
if matches!(target_os().as_str(), "freebsd" | "openbsd") {
println!("cargo:rustc-link-search=native=/usr/local/lib");
println!("cargo:rustc-link-lib=iconv");
}
// Prevent silent fallback to dynamic libraries
if target_os() == "linux" {
println!("cargo:rustc-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-link-arg=-Wl,-Bdynamic");
}
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include(&oc_dst.join("include"))
.compile("vpn");
}
fn target_os() -> String {
env::var("CARGO_CFG_TARGET_OS").expect("Cargo target OS")
}
+36
View File
@@ -0,0 +1,36 @@
use std::{env, path::PathBuf};
pub fn build() {
println!("cargo:rerun-if-env-changed=GP_IOS_NATIVE_PREFIX");
let prefix = PathBuf::from(env::var_os("GP_IOS_NATIVE_PREFIX").expect(
"Set GP_IOS_NATIVE_PREFIX to target-built OpenConnect/GnuTLS libraries with an aarch64-apple-ios target.txt receipt",
));
let target = std::fs::read_to_string(prefix.join("target.txt")).expect("Missing iOS native target receipt");
assert_eq!(
target.trim(),
env::var("TARGET").unwrap(),
"Native library target mismatch"
);
for name in ["openconnect", "gnutls", "hogweed", "nettle", "gmp"] {
let archive = prefix.join(format!("lib/lib{name}.a"));
assert!(archive.is_file(), "Missing {}", archive.display());
println!("cargo:rerun-if-changed={}", archive.display());
}
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include(prefix.join("include"))
.flag("-fapplication-extension")
.compile("vpn");
println!("cargo:rustc-link-search=native={}", prefix.join("lib").display());
for name in ["openconnect", "gnutls", "hogweed", "nettle", "gmp"] {
println!("cargo:rustc-link-lib=static={name}");
}
for name in ["xml2", "z", "iconv", "resolv"] {
println!("cargo:rustc-link-lib={name}");
}
println!("cargo:rustc-link-lib=framework=Security");
println!("cargo:rustc-link-lib=framework=CoreFoundation");
}
+1
View File
@@ -44,6 +44,7 @@ pub(crate) struct ConnectOptions {
pub interface: *const c_char,
pub script_tun: u32,
pub script_tun_launch: *const ScriptTunLaunchRaw,
pub packet_fd: c_int,
pub certificate: *const c_char,
pub sslkey: *const c_char,
+12 -2
View File
@@ -52,9 +52,13 @@ static void observe_statistics(void *private_data, const struct oc_stats *stats)
}
/* Validate the peer certificate */
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
static int validate_peer_cert(void *private_data,
const char *reason)
{
struct vpn_context *context = private_data;
if (context->options->servercert)
return openconnect_check_peer_cert_hash(context->vpninfo,
context->options->servercert);
INFO("Accepting the server certificate though %s", reason);
return 0;
}
@@ -82,7 +86,10 @@ static void setup_tun_handler(void *private_data)
struct openconnect_info *_vpninfo = context->vpninfo;
const vpn_options *options = context->options;
int ret;
if (options->script_tun) {
if (options->packet_fd >= 0) {
int fd = dup(options->packet_fd);
ret = fd < 0 ? -errno : openconnect_setup_tun_fd_with_config(_vpninfo, fd);
} else if (options->script_tun) {
const struct openconnect_script_tun_launch *launch = options->script_tun_launch;
if (launch) {
ret = openconnect_setup_tun_script_exec(_vpninfo, launch);
@@ -156,6 +163,9 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
}
context.vpninfo = vpninfo;
/* A supplied pin is authoritative even when the system would trust a CA. */
if (options->servercert)
openconnect_set_system_trust(vpninfo, 0);
openconnect_set_tunnel_handler(vpninfo, observe_tunnel);
openconnect_set_reconnected_handler(vpninfo, observe_reconnected);
openconnect_set_stats_handler(vpninfo, observe_statistics);
+1
View File
@@ -48,6 +48,7 @@ typedef struct vpn_options {
const char *interface;
const int script_tun;
const struct openconnect_script_tun_launch *script_tun_launch;
const int packet_fd;
const char *certificate;
const char *sslkey;
+37 -1
View File
@@ -151,6 +151,7 @@ pub struct Vpn {
interface: Option<CString>,
script_tun: bool,
script_tun_launch: Option<ScriptTunLaunch>,
packet_endpoint: Option<OwnedFd>,
certificate: Option<CString>,
sslkey: Option<CString>,
@@ -314,6 +315,7 @@ impl Vpn {
interface: Self::option_to_ptr(&self.interface),
script_tun: self.script_tun as u32,
script_tun_launch: std::ptr::null(),
packet_fd: self.packet_endpoint.as_ref().map_or(-1, AsRawFd::as_raw_fd),
certificate: Self::option_to_ptr(&self.certificate),
sslkey: Self::option_to_ptr(&self.sslkey),
@@ -382,6 +384,7 @@ pub struct VpnBuilder {
interface: Option<String>,
script_tun: bool,
script_tun_launch: Option<ScriptTunLaunch>,
packet_endpoint: Option<OwnedFd>,
user_agent: Option<String>,
os: Option<String>,
@@ -393,6 +396,7 @@ pub struct VpnBuilder {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
servercert: Option<String>,
hip_source: Arc<HipSource>,
@@ -417,6 +421,7 @@ impl VpnBuilder {
interface: None,
script_tun: false,
script_tun_launch: None,
packet_endpoint: None,
user_agent: None,
os: None,
@@ -428,6 +433,7 @@ impl VpnBuilder {
certificate: None,
sslkey: None,
key_password: None,
servercert: None,
hip_source: Arc::new(HipSource::Disabled),
@@ -441,6 +447,16 @@ impl VpnBuilder {
}
}
/// Use an application-owned packet descriptor. OpenConnect borrows a duplicate
/// during connect; this owner remains alive until the Vpn is dropped. Apple/BSD
/// endpoints use the native four-byte, network-order address-family prefix.
/// Requires callback configuration and a SHA-256 server public-key pin.
pub fn packet_endpoint(mut self, endpoint: OwnedFd, server_pin: String) -> Self {
self.packet_endpoint = Some(endpoint);
self.servercert = Some(server_pin);
self
}
pub fn script<T: Into<Option<String>>>(mut self, script: T) -> Self {
self.script = script.into();
self.script_is_path = false;
@@ -618,6 +634,24 @@ impl VpnBuilder {
}
pub fn build(self) -> Result<Vpn, VpnError> {
if self.packet_endpoint.is_some() {
let pin = self.servercert.as_deref().unwrap_or_default();
if self.network_configuration_handler.is_none()
|| self.interface.is_some()
|| self.script.is_some()
|| self.script_tun
|| self.script_tun_launch.is_some()
{
return Err(VpnError::new(
"Packet endpoint requires callback configuration and no device/script options".into(),
));
}
if !pin.starts_with("pin-sha256:") || pin.len() != 55 || pin.contains('\0') {
return Err(VpnError::new(
"Packet endpoint requires a pin-sha256 server public-key fingerprint".into(),
));
}
}
if self.script_tun_launch.is_some() && !self.script_tun {
return Err(VpnError::new("Child identity requires script-tun".into()));
}
@@ -643,11 +677,12 @@ impl VpnBuilder {
interface: self.interface.as_deref().map(Self::to_cstring),
script_tun: self.script_tun,
script_tun_launch: self.script_tun_launch,
packet_endpoint: self.packet_endpoint,
certificate: self.certificate.as_deref().map(Self::to_cstring),
sslkey: self.sslkey.as_deref().map(Self::to_cstring),
key_password: self.key_password.as_deref().map(Self::to_cstring),
servercert: None,
servercert: self.servercert.as_deref().map(Self::to_cstring),
hip_source: self.hip_source,
@@ -775,6 +810,7 @@ mod tests {
interface: None,
script_tun: false,
script_tun_launch: None,
packet_endpoint: None,
certificate: None,
sslkey: None,
key_password: None,
+53
View File
@@ -75,6 +75,58 @@ int inspect_esp_packet(struct openconnect_info *vpninfo, struct pkt *pkt, uint8_
return 1;
}
/* Check the real request builder without a VPN server. Desktop payloads stay exact. */
static void getconfig_profile_parameters(void)
{
const char *platforms[] = { "linux", "mac-intel", "win", "apple-ios" };
const char *names[] = { "Linux", "Mac", "Windows", "iOS" };
int i;
for (i = 0; i < 4; i++) {
struct openconnect_info *vpninfo = openconnect_vpninfo_new("test", NULL, NULL, NULL, NULL, NULL);
struct oc_text_buf *body = buf_alloc();
char expected[2048];
assert(vpninfo && body);
assert(!openconnect_set_reported_os(vpninfo, platforms[i]));
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.5-28"));
assert(!openconnect_set_gp_os_version(vpninfo, "test-os"));
assert(!openconnect_set_gp_host_id(vpninfo, "HOSTID"));
assert(!openconnect_set_cookie(vpninfo, "user=test&portal=portal&authcookie=fixture&computer=Phone&preferred-ip=192.0.2.5"));
assert(!gpst_build_getconfig_request(vpninfo, body));
if (i == 3) {
assert(strstr(body->data, "clientos=iOS"));
assert(strstr(body->data, "vpn-type=App%20Level%20VPN"));
assert(strstr(body->data, "client-ip=&client-ipv6=&serialno=&joined-domain="));
assert(strstr(body->data, "user=test") && strstr(body->data, "authcookie=fixture"));
assert(strstr(body->data, "preferred-ip=192.0.2.5"));
assert(!strstr(body->data, "host-id=") && !strstr(body->data, "clientgpversion=") && !strstr(body->data, "computer="));
buf_truncate(body);
vpninfo->ip_info.addr = strdup("192.0.2.6");
assert(!gpst_build_getconfig_request(vpninfo, body));
assert(strstr(body->data, "preferred-ip=192.0.2.6"));
assert(!strstr(body->data, "192.0.2.5"));
/* The connected HTTPS socket supplies the actual local client address. */
int fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in local = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
assert(fd >= 0 && !bind(fd, (struct sockaddr *)&local, sizeof(local)));
vpninfo->ssl_fd = fd;
buf_truncate(body);
assert(!gpst_build_getconfig_request(vpninfo, body));
assert(strstr(body->data, "client-ip=127.0.0.1&client-ipv6="));
vpninfo->ssl_fd = -1;
close(fd);
} else {
snprintf(expected, sizeof(expected),
"client-type=1&protocol-version=p1&internal=no&app-version=6.3.5-28&ipv6-support=yes"
"&clientos=%s&os-version=test-os&hmac-algo=sha1%%2c&enc-algo=aes-256-gcm%%2caes-128-gcm%%2caes-128-cbc%%2c"
"&clientgpversion=6.3.5-28&host-id=HOSTID&user=test&portal=portal&authcookie=fixture&computer=Phone&preferred-ip=192.0.2.5",
names[i]);
assert(!strcmp(body->data, expected));
}
buf_free(body);
openconnect_vpninfo_free(vpninfo);
}
}
int main(int argc, char **argv)
{
static const char key[] =
@@ -92,6 +144,7 @@ int main(int argc, char **argv)
int sockets[2], nlb, invalid, length;
assert(argc == 2);
getconfig_profile_parameters();
nlb = !strncmp(argv[1], "nlb-", 4);
invalid = !strcmp(argv[1], "regular-invalid") || !strcmp(argv[1], "regular-missing");
if (!strcmp(argv[1], "regular-address") || !strcmp(argv[1], "nlb-address"))
@@ -160,6 +160,59 @@ static void reconnect_refusal_propagates(void)
openconnect_vpninfo_free(vpninfo);
}
static void external_packets_and_configuration(void)
{
struct state state = { .parent = getpid(), .reason = "connect" };
struct openconnect_info *vpninfo = new_vpn(&state);
int fds[2], families[] = { AF_INET, AF_INET6 };
int creations = device_creations;
assert(!socketpair(AF_UNIX, SOCK_DGRAM, 0, fds));
assert(!openconnect_setup_tun_fd_with_config(vpninfo, fds[0]));
assert(device_creations == creations);
assert(state.calls == 1);
for (int i = 0; i < 2; i++) {
unsigned char frame[1504] = {0}, received[1504];
struct pkt *packet = alloc_pkt(vpninfo, 1500);
int prefix = 0, length = i ? 40 : 20;
#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__)
uint32_t family = htonl(families[i]);
memcpy(frame, &family, 4);
prefix = 4;
#endif
frame[prefix] = i ? 0x60 : 0x45;
assert(write(fds[1], frame, length + prefix) == length + prefix);
packet->len = 1500;
assert(!os_read_tun(vpninfo, packet));
assert(packet->len == length);
assert(!memcmp(packet->data, frame + prefix, length));
assert(!os_write_tun(vpninfo, packet));
assert(read(fds[1], received, sizeof(received)) == length + prefix);
assert(!memcmp(received, frame, length + prefix));
free_pkt(vpninfo, packet);
}
state.reason = "disconnect";
openconnect_vpninfo_free(vpninfo);
assert(state.calls == 2);
assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
close(fds[1]);
state.calls = 0;
state.reason = "connect";
state.failure_reason = "connect";
state.result = -EPERM;
const char *reasons[] = { "connect", "disconnect" };
state.expected_reasons = reasons;
state.expected_count = 2;
vpninfo = new_vpn(&state);
assert(!socketpair(AF_UNIX, SOCK_DGRAM, 0, fds));
assert(openconnect_setup_tun_fd_with_config(vpninfo, fds[0]) == -EPERM);
assert(vpninfo->tun_fd == -1);
assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
openconnect_vpninfo_free(vpninfo);
assert(state.calls == 2);
close(fds[1]);
}
int main(void)
{
const char *reasons[] = { "pre-init", "connect", "attempt-reconnect", "reconnect", "disconnect" };
@@ -199,5 +252,6 @@ int main(void)
openconnect_vpninfo_free(vpninfo);
connect_failure_rolls_back();
reconnect_refusal_propagates();
external_packets_and_configuration();
return 0;
}