refactor: align GP profile and packaging flow

Main changes:

- Refactor connect/auth flows around a single OS profile and host identity model, including gateway fallback and cookie-on-stdin handling.

- Align request parameters, HIP host-id propagation, SAML webview user-agent behavior, and portal default-browser handling with observed official client behavior.

- Add opt-in cookie cache support and Microsoft Defender HIP reporting while keeping host-id validation explicit.

- Add BSD build, packaging, release artifact, and provenance support with FreeBSD/OpenBSD path and dependency cleanup.

- Update NixOS install documentation and dependency compatibility fixes.
This commit is contained in:
Kevin Yue committed 2026-06-19 21:23:29 +08:00
1 parent f98e0336dc
commit 888dc93643
92 files changed
+9847 -2868

No files matched your search

+5 -5
View File
@@ -32,10 +32,11 @@ uzers.workspace = true
serde_urlencoded.workspace = true
md5.workspace = true
sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
netdev.workspace = true
os_info = { version = "3", default-features = false }
# Optional dependencies for features
tauri = { workspace = true, optional = true }
@@ -45,14 +46,13 @@ clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true }
# Dependencies for macOS and Windows only
[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies]
os_info = { version = "3", default-features = false }
# Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = { version = "0.18", optional = true }
[dev-dependencies]
proptest.workspace = true
[features]
tauri = ["dep:tauri", "dep:gtk"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]
+83 -4
View File
@@ -9,7 +9,7 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SamlAuthData {
#[serde(alias = "un")]
@@ -17,9 +17,11 @@ pub struct SamlAuthData {
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
host_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum SamlAuthResult {
Success(SamlAuthData),
@@ -33,6 +35,13 @@ impl SamlAuthResult {
SamlAuthResult::Failure(_) => false,
}
}
pub fn host_id(&self) -> Option<&str> {
match self {
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
SamlAuthResult::Failure(_) => None,
}
}
}
impl SamlAuthData {
@@ -62,9 +71,16 @@ impl SamlAuthData {
prelogin_cookie: Some(prelogin_cookie),
portal_userauthcookie: Some(portal_userauthcookie),
token: None,
host_id: None,
})
}
pub fn with_host_id(mut self, host_id: impl Into<String>) -> Self {
let host_id = host_id.into();
self.host_id = (!host_id.trim().is_empty()).then_some(host_id);
self
}
pub fn from_html(html: &str) -> AuthDataParseResult {
match parse_xml_tag(html, "saml-auth-status") {
Some(status) if status == "1" => {
@@ -72,7 +88,11 @@ impl SamlAuthData {
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)
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::Invalid(anyhow::anyhow!(
"SAML auth status: {}",
@@ -102,6 +122,7 @@ impl SamlAuthData {
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
auth_data.log_summary("gpcallback-cas");
return Ok(auth_data);
}
@@ -122,9 +143,32 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
pub fn host_id(&self) -> Option<&str> {
self.host_id.as_deref()
}
fn log_summary(&self, source: &str) {
info!(
"Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}",
source,
!self.username.is_empty(),
optional_len(self.prelogin_cookie.as_deref()),
optional_len(self.portal_userauthcookie.as_deref()),
optional_len(self.token.as_deref())
);
}
}
fn optional_len(value: Option<&str>) -> usize {
value.unwrap_or_default().len()
}
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
@@ -160,11 +204,46 @@ mod tests {
#[test]
fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHBvcnRhbC11c2VyYXV0aGNvb2tpZT5wb3J0YWwtdXNlcmF1dGhjb29raWU8L3BvcnRhbC11c2VyYXV0aGNvb2tpZT48c2FtbC11c2VybmFtZT54eXpAZW1haWwuY29tPC9zYW1sLXVzZXJuYW1lPjxzYW1sLXNsbz5ubzwvc2FtbC1zbG8+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie"));
}
#[test]
fn auth_result_success_can_carry_host_id() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
None,
)
.unwrap()
.with_host_id("host-seed");
let result = SamlAuthResult::Success(auth_data);
assert_eq!(result.host_id(), Some("host-seed"));
let value = serde_json::to_value(result).unwrap();
assert_eq!(value["success"]["hostId"], "host-seed");
}
#[test]
fn auth_result_success_omits_empty_host_id() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
None,
)
.unwrap()
.with_host_id(" ");
let result = SamlAuthResult::Success(auth_data);
assert_eq!(result.host_id(), None);
let value = serde_json::to_value(result).unwrap();
assert!(value["success"].get("hostId").is_none());
}
}
+38 -37
View File
@@ -1,37 +1,22 @@
use clap::{ValueEnum, builder::PossibleValue};
use crate::gp_params::ClientOs;
use crate::{
gp_params::CscMode,
os_profile::{ClientOs, runtime_client_os},
};
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Os {
#[value(name = "Linux")]
Linux,
#[value(name = "Windows")]
Windows,
#[value(name = "Mac")]
Mac,
}
impl Os {
pub fn as_str(&self) -> &'static str {
match self {
Os::Linux => "Linux",
Os::Windows => "Windows",
Os::Mac => "Mac",
}
}
}
impl From<&str> for Os {
fn from(os: &str) -> Self {
match os.to_lowercase().as_str() {
"linux" => Os::Linux,
"windows" => Os::Windows,
"mac" => Os::Mac,
_ => Os::Linux,
}
}
}
impl From<&Os> for ClientOs {
fn from(value: &Os) -> Self {
impl From<Os> for ClientOs {
fn from(value: Os) -> Self {
match value {
Os::Linux => ClientOs::Linux,
Os::Windows => ClientOs::Windows,
@@ -40,25 +25,41 @@ impl From<&Os> for ClientOs {
}
}
impl ValueEnum for Os {
impl Default for Os {
fn default() -> Self {
match runtime_client_os() {
ClientOs::Linux => Os::Linux,
ClientOs::Windows => Os::Windows,
ClientOs::Mac => Os::Mac,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_os_uses_runtime_client_os() {
assert_eq!(ClientOs::from(Os::default()), runtime_client_os());
}
}
impl ValueEnum for CscMode {
fn value_variants<'a>() -> &'a [Self] {
&[Os::Linux, Os::Windows, Os::Mac]
&[CscMode::Auto, CscMode::Yes, CscMode::No]
}
fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
match self {
Os::Linux => Some(PossibleValue::new("Linux")),
Os::Windows => Some(PossibleValue::new("Windows")),
Os::Mac => Some(PossibleValue::new("Mac")),
}
fn to_possible_value(&self) -> Option<PossibleValue> {
Some(PossibleValue::new(self.as_str()))
}
fn from_str(input: &str, _: bool) -> Result<Self, String> {
match input.to_lowercase().as_str() {
"linux" => Ok(Os::Linux),
"windows" => Ok(Os::Windows),
"mac" => Ok(Os::Mac),
_ => Err(format!("Invalid OS: {}", input)),
"auto" => Ok(CscMode::Auto),
"yes" => Ok(CscMode::Yes),
"no" => Ok(CscMode::No),
_ => Err(format!("Invalid CSC mode: {}", input)),
}
}
}
+82 -11
View File
@@ -1,7 +1,6 @@
use std::{
fs,
io::Write,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
};
@@ -16,13 +15,20 @@ pub struct StoredCookie {
pub version: u32,
pub server: String,
pub username: String,
pub host_id: String,
pub last_gateway: String,
pub auth_cookie: AuthCookieCredential,
pub saved_at: u64,
}
impl StoredCookie {
pub fn new(server: String, username: String, last_gateway: String, auth_cookie: AuthCookieCredential) -> Self {
pub fn new(
server: String,
username: String,
host_id: String,
last_gateway: String,
auth_cookie: AuthCookieCredential,
) -> Self {
let saved_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
@@ -31,6 +37,7 @@ impl StoredCookie {
version: STORE_VERSION,
server,
username,
host_id,
last_gateway,
auth_cookie,
saved_at,
@@ -46,10 +53,10 @@ pub fn cookie_path(custom: Option<&str>) -> PathBuf {
PathBuf::from(home).join(".config/gpclient/cookie.json")
}
pub fn load(path: &Path, server: &str) -> Option<StoredCookie> {
pub fn load(path: &Path, server: &str, host_id: &str) -> Option<StoredCookie> {
let bytes = fs::read(path).ok()?;
let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?;
if stored.version != STORE_VERSION || stored.server != server {
if stored.version != STORE_VERSION || stored.server != server || stored.host_id != host_id {
return None;
}
Some(stored)
@@ -60,12 +67,12 @@ pub fn save(path: &Path, stored: &StoredCookie) -> anyhow::Result<()> {
.parent()
.ok_or_else(|| anyhow::anyhow!("cookie path has no parent directory"))?;
fs::create_dir_all(parent)?;
fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?;
set_private_dir_permissions(parent)?;
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(&serde_json::to_vec(stored)?)?;
tmp.flush()?;
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o600))?;
set_private_file_permissions(tmp.path())?;
tmp.persist(path)?;
Ok(())
}
@@ -74,6 +81,60 @@ pub fn clear(path: &Path) {
let _ = fs::remove_file(path);
}
use permissions::{set_private_dir_permissions, set_private_file_permissions};
mod permissions {
use std::path::Path;
#[cfg(unix)]
mod unix {
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
pub(super) fn set_private_dir(path: &Path) -> anyhow::Result<()> {
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
Ok(())
}
pub(super) fn set_private_file(path: &Path) -> anyhow::Result<()> {
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
Ok(())
}
#[cfg(test)]
pub(super) fn file_mode(path: &Path) -> Option<u32> {
Some(fs::metadata(path).ok()?.permissions().mode() & 0o777)
}
}
pub(super) fn set_private_dir_permissions(path: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
unix::set_private_dir(path)?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
pub(super) fn set_private_file_permissions(path: &Path) -> anyhow::Result<()> {
#[cfg(unix)]
unix::set_private_file(path)?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)]
pub(super) fn file_mode(path: &Path) -> Option<u32> {
#[cfg(unix)]
return unix::file_mode(path);
#[cfg(not(unix))]
{
let _ = path;
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -82,6 +143,7 @@ mod tests {
StoredCookie::new(
"vpn.example.com".to_string(),
"alice".to_string(),
"host-1".to_string(),
"gw1.example.com".to_string(),
AuthCookieCredential::new("alice", "user-auth", "prelogon-auth"),
)
@@ -94,15 +156,24 @@ mod tests {
let s = sample();
save(&path, &s).unwrap();
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode);
if let Some(mode) = permissions::file_mode(&path) {
assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode);
}
let loaded = load(&path, "vpn.example.com").unwrap();
let loaded = load(&path, "vpn.example.com", "host-1").unwrap();
assert_eq!(loaded.username, "alice");
assert_eq!(loaded.host_id, "host-1");
assert_eq!(loaded.last_gateway, "gw1.example.com");
assert_eq!(loaded.auth_cookie.user_auth_cookie(), "user-auth");
assert!(load(&path, "other.example.com").is_none(), "must reject mismatched server");
assert!(
load(&path, "other.example.com", "host-1").is_none(),
"must reject mismatched server"
);
assert!(
load(&path, "vpn.example.com", "host-2").is_none(),
"must reject mismatched host id"
);
clear(&path);
assert!(!path.exists());
}
@@ -114,6 +185,6 @@ mod tests {
let mut s = sample();
s.version = STORE_VERSION + 1;
save(&path, &s).unwrap();
assert!(load(&path, "vpn.example.com").is_none());
assert!(load(&path, "vpn.example.com", "host-1").is_none());
}
}
+139 -38
View File
@@ -1,5 +1,3 @@
use std::collections::HashMap;
use anyhow::bail;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -41,14 +39,21 @@ impl From<&CachedCredential> for PasswordCredential {
pub struct PreloginCredential {
username: String,
prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>,
}
impl PreloginCredential {
pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self {
pub fn new(
username: &str,
prelogin_cookie: Option<&str>,
portal_userauthcookie: Option<&str>,
token: Option<&str>,
) -> Self {
Self {
username: username.to_string(),
prelogin_cookie: prelogin_cookie.map(|s| s.to_string()),
portal_userauthcookie: portal_userauthcookie.map(|s| s.to_string()),
token: token.map(|s| s.to_string()),
}
}
@@ -61,6 +66,10 @@ impl PreloginCredential {
self.prelogin_cookie.as_deref()
}
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
@@ -70,9 +79,10 @@ impl From<SamlAuthData> for PreloginCredential {
fn from(value: SamlAuthData) -> Self {
let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie();
let portal_userauthcookie = value.portal_userauthcookie();
let token = value.token();
Self::new(&username, prelogin_cookie, token)
Self::new(&username, prelogin_cookie, portal_userauthcookie, token)
}
}
@@ -82,6 +92,8 @@ pub struct AuthCookieCredential {
username: String,
user_auth_cookie: String,
prelogon_user_auth_cookie: String,
#[serde(skip)]
password: Option<String>,
}
impl AuthCookieCredential {
@@ -90,9 +102,16 @@ impl AuthCookieCredential {
username: username.to_string(),
user_auth_cookie: user_auth_cookie.to_string(),
prelogon_user_auth_cookie: prelogon_user_auth_cookie.to_string(),
password: None,
}
}
pub fn with_password(mut self, password: impl Into<String>) -> Self {
let password = password.into();
self.password = (!password.trim().is_empty()).then_some(password);
self
}
pub fn username(&self) -> &str {
&self.username
}
@@ -104,6 +123,19 @@ impl AuthCookieCredential {
pub fn prelogon_user_auth_cookie(&self) -> &str {
&self.prelogon_user_auth_cookie
}
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
pub fn can_authenticate_gateway(&self) -> bool {
is_gateway_auth_cookie(&self.user_auth_cookie) || is_gateway_auth_cookie(&self.prelogon_user_auth_cookie)
}
}
fn is_gateway_auth_cookie(value: &str) -> bool {
let value = value.trim();
!value.is_empty() && value != "empty"
}
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
@@ -135,6 +167,13 @@ impl CachedCredential {
self.auth_cookie.as_ref()
}
pub fn can_authenticate_gateway(&self) -> bool {
self
.auth_cookie
.as_ref()
.is_some_and(AuthCookieCredential::can_authenticate_gateway)
}
pub fn set_auth_cookie(&mut self, auth_cookie: AuthCookieCredential) {
self.auth_cookie = Some(auth_cookie);
}
@@ -180,42 +219,20 @@ impl Credential {
}
}
pub fn to_params(&self) -> HashMap<&str, &str> {
let mut params = HashMap::new();
params.insert("user", self.username());
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()),
Credential::AuthCookie(cred) => (
None,
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::Cached(cred) => (
cred.password(),
None,
cred.auth_cookie.as_ref().map(|c| c.user_auth_cookie()),
cred.auth_cookie.as_ref().map(|c| c.prelogon_user_auth_cookie()),
None,
),
};
params.insert("passwd", passwd.unwrap_or_default());
params.insert("prelogin-cookie", prelogin_cookie.unwrap_or_default());
params.insert("portal-userauthcookie", portal_userauthcookie.unwrap_or_default());
params.insert(
"portal-prelogonuserauthcookie",
portal_prelogonuserauthcookie.unwrap_or_default(),
);
if let Some(token) = token {
params.insert("token", token);
pub fn password(&self) -> Option<&str> {
match self {
Credential::Password(cred) => Some(cred.password()),
Credential::Cached(cred) => cred.password(),
Credential::Prelogin(_) | Credential::AuthCookie(_) => None,
}
}
params
pub fn can_authenticate_gateway(&self) -> bool {
match self {
Credential::AuthCookie(cred) => cred.can_authenticate_gateway(),
Credential::Cached(cred) => cred.can_authenticate_gateway(),
Credential::Password(_) | Credential::Prelogin(_) => true,
}
}
}
@@ -255,3 +272,87 @@ impl From<&CachedCredential> for Credential {
Self::Cached(value.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prelogin_credential_keeps_saml_cookies() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
Some("portal-userauthcookie".to_string()),
)
.unwrap();
let cred = Credential::from(auth_data);
let Credential::Prelogin(prelogin) = cred else {
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]");
assert_eq!(prelogin.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(prelogin.portal_userauthcookie(), Some("portal-userauthcookie"));
assert_eq!(prelogin.token(), None);
}
#[test]
fn prelogin_credential_keeps_cas_token_without_cookies() {
let auth_data =
SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap();
let cred = Credential::from(auth_data);
let Credential::Prelogin(prelogin) = cred else {
panic!("expected prelogin credential");
};
assert_eq!(prelogin.username(), "[email protected]");
assert_eq!(prelogin.prelogin_cookie(), None);
assert_eq!(prelogin.portal_userauthcookie(), None);
assert_eq!(prelogin.token(), Some("cas-token"));
}
#[test]
fn auth_cookie_runtime_password_is_not_serialized() {
let value = serde_json::to_value(
AuthCookieCredential::new("alice", "user-cookie", "prelogon-cookie").with_password("secret"),
)
.unwrap();
assert_eq!(value.get("password"), None);
}
#[test]
fn auth_cookie_with_empty_sentinels_cannot_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "empty", "empty");
assert!(!cred.can_authenticate_gateway());
}
#[test]
fn auth_cookie_with_blank_values_cannot_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "", " ");
assert!(!cred.can_authenticate_gateway());
}
#[test]
fn auth_cookie_with_real_cookie_can_authenticate_gateway() {
let cred = AuthCookieCredential::new("alice", "empty", "portal-prelogon-cookie");
assert!(cred.can_authenticate_gateway());
}
#[test]
fn cached_credential_without_real_auth_cookie_cannot_authenticate_gateway() {
let cred = CachedCredential::new(
"alice".to_string(),
None,
Some(AuthCookieCredential::new("alice", "empty", "empty")),
);
assert!(!cred.can_authenticate_gateway());
assert!(!Credential::from(&cred).can_authenticate_gateway());
}
}
-173
View File
@@ -1,173 +0,0 @@
use std::collections::HashMap;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
gp_params::GpParams,
process::hip_launcher::HipLauncher,
utils::{normalize_server, xml::ElementExt},
};
struct HipReporter<'a> {
server: String,
cookie: &'a str,
md5: &'a str,
csd_wrapper: &'a str,
gp_params: &'a GpParams,
client: Client,
}
impl HipReporter<'_> {
async fn report(&self) -> anyhow::Result<()> {
let client_ip = self.retrieve_client_ip().await?;
let hip_needed = match self.check_hip(&client_ip).await {
Ok(hip_needed) => hip_needed,
Err(err) => {
warn!("Failed to check HIP: {}", err);
return Ok(());
}
};
if !hip_needed {
info!("HIP report not needed");
return Ok(());
}
info!("HIP report needed, generating report...");
let report = self.generate_report(&client_ip).await?;
if let Err(err) = self.submit_hip(&client_ip, &report).await {
warn!("Failed to submit HIP report: {}", err);
}
Ok(())
}
async fn retrieve_client_ip(&self) -> anyhow::Result<String> {
let config_url = format!("{}/ssl-vpn/getconfig.esp", self.server);
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("client-type", "1");
params.insert("protocol-version", "p1");
params.insert("internal", "no");
params.insert("ipv6-support", "yes");
params.insert("clientos", self.gp_params.client_os());
params.insert("hmac-algo", "sha1,md5,sha256");
params.insert("enc-algo", "aes-128-cbc,aes-256-cbc");
if let Some(os_version) = self.gp_params.os_version() {
params.insert("os-version", os_version);
}
if let Some(client_version) = self.gp_params.client_version() {
params.insert("app-version", client_version);
}
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&config_url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
let root = Element::parse(res_xml.as_bytes())?;
// Get <ip-address>
let ip = root
.descendant_text("ip-address")
.ok_or_else(|| anyhow::anyhow!("ip-address not found"))?;
Ok(ip.to_string())
}
async fn check_hip(&self, client_ip: &str) -> anyhow::Result<bool> {
let url = format!("{}/ssl-vpn/hipreportcheck.esp", self.server);
let mut params = HashMap::new();
params.insert("client-role", "global-protect-full");
params.insert("client-ip", client_ip);
params.insert("md5", self.md5);
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
is_hip_needed(&res_xml)
}
async fn generate_report(&self, client_ip: &str) -> anyhow::Result<String> {
let launcher = HipLauncher::new(self.csd_wrapper)
.cookie(self.cookie)
.md5(self.md5)
.client_ip(client_ip)
.client_os(self.gp_params.client_os())
.client_version(self.gp_params.client_version());
launcher.launch().await
}
async fn submit_hip(&self, client_ip: &str, report: &str) -> anyhow::Result<()> {
let url = format!("{}/ssl-vpn/hipreport.esp", self.server);
let mut params = HashMap::new();
params.insert("client-role", "global-protect-full");
params.insert("client-ip", client_ip);
params.insert("report", report);
let params = merge_cookie_params(self.cookie, &params)?;
let res = self.client.post(&url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
info!("HIP check response: {}", res_xml);
Ok(())
}
}
fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> {
let root = Element::parse(res_xml.as_bytes())?;
let hip_needed = root
.descendant_text("hip-report-needed")
.ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?;
Ok(hip_needed == "yes")
}
fn merge_cookie_params(cookie: &str, params: &HashMap<&str, &str>) -> anyhow::Result<HashMap<String, String>> {
let cookie_params = serde_urlencoded::from_str::<HashMap<String, String>>(cookie)?;
let params = params
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.chain(cookie_params)
.collect::<HashMap<String, String>>();
Ok(params)
}
// Compute md5 for fields except authcookie,preferred-ip,preferred-ipv6
fn build_csd_token(cookie: &str) -> anyhow::Result<String> {
let mut cookie_params = serde_urlencoded::from_str::<Vec<(String, String)>>(cookie)?;
cookie_params.retain(|(k, _)| k != "authcookie" && k != "preferred-ip" && k != "preferred-ipv6");
let token = serde_urlencoded::to_string(cookie_params)?;
let md5 = format!("{:x}", md5::compute(token));
Ok(md5)
}
pub async fn hip_report(gateway: &str, cookie: &str, csd_wrapper: &str, gp_params: &GpParams) -> anyhow::Result<()> {
let client = Client::try_from(gp_params)?;
let md5 = build_csd_token(cookie)?;
info!("Submit HIP report md5: {}", md5);
let reporter = HipReporter {
server: normalize_server(gateway)?,
cookie,
md5: &md5,
csd_wrapper,
gp_params,
client,
};
reporter.report().await
}
+60 -51
View File
@@ -1,4 +1,4 @@
use std::{borrow::Cow, collections::HashMap};
use std::{borrow::Cow, net::UdpSocket};
use anyhow::bail;
use log::{debug, info, warn};
@@ -9,7 +9,9 @@ use xmltree::Element;
use crate::{
credential::Credential,
error::PortalError,
gateway::GatewayLoginContext,
gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
@@ -19,7 +21,16 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
gateway_login_with_options(gateway, cred, gp_params, None, false).await
}
pub async fn gateway_login_with_context(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: &GatewayLoginContext,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
}
pub async fn gateway_login_with_extend_lifetime(
@@ -27,13 +38,14 @@ pub async fn gateway_login_with_extend_lifetime(
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
gateway_login_with_options(gateway, cred, gp_params, None, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
@@ -42,14 +54,33 @@ async fn gateway_login_with_options(
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime);
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host()))
});
let request_params = gateway_login::build(&GatewayLoginInput {
gp_params,
cred,
gateway_host: &gateway,
context,
client_ip: client_ip.as_deref(),
extend_lifetime,
});
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res = client
.post(&login_url)
.form(&request_params.body)
.send()
.await
.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}");
@@ -80,31 +111,29 @@ async fn gateway_login_with_options(
Ok(GatewayLogin::Cookie(cookie))
}
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
let Some(context) = context else {
return;
};
info!(
"Gateway login context: host_present={}, gateway_name_present={}, connect_method_present={}, selection_type={}, internal={}, clientgpversion_present={}, client_ip_present={}",
!context.host().is_empty(),
!context.name().is_empty(),
context.connect_method().is_some(),
context.selection().as_login_param(),
context.kind().as_login_param(),
gp_params.client_version().is_some(),
client_ip.is_some()
);
params.insert("server".to_string(), gateway.to_string());
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
@@ -205,26 +234,6 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(input_str, "5ef64e83000119ed");
}
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, false);
assert!(!params.contains_key("extend-lifetime"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
+134 -1
View File
@@ -1,4 +1,3 @@
pub mod hip;
mod login;
mod parse_gateways;
pub mod session;
@@ -23,10 +22,119 @@ pub(crate) struct PriorityRule {
pub struct Gateway {
pub(crate) name: String,
pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
pub(crate) priority: u32,
pub(crate) priority_rules: Vec<PriorityRule>,
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewayKind {
Internal,
External,
}
impl GatewayKind {
pub fn as_login_param(self) -> &'static str {
match self {
GatewayKind::Internal => "yes",
GatewayKind::External => "no",
}
}
}
impl Default for GatewayKind {
fn default() -> Self {
Self::External
}
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewaySelection {
Auto,
Manual,
}
impl GatewaySelection {
pub fn as_login_param(self) -> &'static str {
match self {
GatewaySelection::Auto => "auto",
GatewaySelection::Manual => "manual",
}
}
}
impl Default for GatewaySelection {
fn default() -> Self {
Self::Auto
}
}
#[derive(Debug, Clone)]
pub struct GatewayLoginContext {
host: String,
name: String,
kind: GatewayKind,
selection: GatewaySelection,
connect_method: Option<String>,
client_ip: Option<String>,
}
impl GatewayLoginContext {
pub fn new(gateway: &Gateway, selection: GatewaySelection) -> Self {
let name = if gateway.name().is_empty() {
gateway.server()
} else {
gateway.name()
};
Self {
host: gateway.server().to_string(),
name: name.to_string(),
kind: gateway.kind(),
selection,
connect_method: None,
client_ip: None,
}
}
pub fn with_connect_method(mut self, connect_method: Option<&str>) -> Self {
self.connect_method = connect_method.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_ip(mut self, client_ip: Option<String>) -> Self {
self.client_ip = client_ip.filter(|s| !s.is_empty());
self
}
pub(crate) fn host(&self) -> &str {
&self.host
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn kind(&self) -> GatewayKind {
self.kind
}
pub(crate) fn selection(&self) -> GatewaySelection {
self.selection
}
pub(crate) fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub(crate) fn client_ip(&self) -> Option<&str> {
self.client_ip.as_deref()
}
}
impl Display for Gateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.name, self.address)
@@ -38,6 +146,7 @@ impl Gateway {
Self {
name,
address,
kind: GatewayKind::External,
priority: 0,
priority_rules: vec![],
}
@@ -50,4 +159,28 @@ impl Gateway {
pub fn server(&self) -> &str {
&self.address
}
pub fn kind(&self) -> GatewayKind {
self.kind
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_gateway_without_kind_as_external() {
let gateway: Gateway = serde_json::from_str(
r#"{
"name": "US East",
"address": "us-east.example.com",
"priority": 1,
"priorityRules": []
}"#,
)
.unwrap();
assert_eq!(gateway.kind(), GatewayKind::External);
}
}
+63 -4
View File
@@ -3,21 +3,28 @@ use xmltree::Element;
use crate::utils::xml::ElementExt;
use super::{Gateway, PriorityRule};
use super::{Gateway, GatewayKind, PriorityRule};
pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?;
let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways...");
node_gateways.descendant("internal").and_then(|n| n.child("list"))
node_gateways
.descendant("internal")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::Internal))
} else {
None
};
let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways...");
node_gateways.descendant("external").and_then(|n| n.child("list"))
node_gateways
.descendant("external")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::External))
})?;
let (gateway_list, kind) = gateway_list;
let gateways = gateway_list
.children("entry")
@@ -28,12 +35,13 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option
let priority = parse_priority(gateway_item);
let priority_rules = gateway_item
.child("priority-rule")
.map(|n| parse_priority_rules(n))
.map(parse_priority_rules)
.unwrap_or_default();
Gateway {
name,
address,
kind,
priority,
priority_rules,
}
@@ -62,3 +70,54 @@ fn parse_priority(element: &Element) -> u32 {
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_external_gateways_marks_gateway_kind() {
let xml = r#"
<policy>
<gateways>
<external>
<list>
<entry name="us1.vpn.example.com">
<description>US_East</description>
</entry>
</list>
</external>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, false).unwrap();
assert_eq!(gateways[0].name(), "US_East");
assert_eq!(gateways[0].server(), "us1.vpn.example.com");
assert_eq!(gateways[0].kind(), GatewayKind::External);
}
#[test]
fn parse_internal_gateways_marks_gateway_kind_when_preferred() {
let xml = r#"
<policy>
<gateways>
<internal>
<list>
<entry name="internal.vpn.example.com">
<description>Internal</description>
</entry>
</list>
</internal>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, true).unwrap();
assert_eq!(gateways[0].kind(), GatewayKind::Internal);
}
}
+27 -14
View File
@@ -13,7 +13,7 @@ use crate::{
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, xml::ElementExt},
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
@@ -120,16 +120,19 @@ fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = GpParams::builder();
builder.user_agent(args.user_agent().as_deref().unwrap_or_default());
builder.client_os(args.os().unwrap_or_default());
builder.os_version(args.os_version());
builder.client_version(args.client_version());
builder.certificate(args.certificate());
builder.sslkey(args.sslkey());
builder.key_password(args.key_password());
let mut builder = Client::builder();
Client::try_from(&builder.build())
if let Some(user_agent) = args.user_agent() {
builder = builder.user_agent(user_agent);
}
if let Some(cert) = args.certificate() {
info!("Using client certificate authentication...");
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
builder = builder.identity(identity);
}
Ok(builder.build()?)
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
@@ -165,15 +168,25 @@ fn unix_timestamp() -> u64 {
#[cfg(test)]
mod tests {
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
session::SessionRequestArgs,
};
use super::*;
fn build_session_args() -> SessionRequestArgs {
let profile = OsProfile::builder(ClientOs::Mac)
.host_identity(HostIdentity::new(
"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();
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_os(Some(ClientOs::Mac))
.with_os_version(Some("macOS 15.0".to_string()))
.with_client_version(Some("6.3.1-12".to_string()))
.with_user_agent(profile.user_agent().to_string())
.with_disable_ipv6(true)
}
+410 -142
View File
@@ -1,76 +1,59 @@
use std::collections::HashMap;
use common::constants::GP_USER_AGENT;
use log::info;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::utils::host_utils;
use crate::utils::request::create_identity;
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::create_identity,
};
#[derive(Debug, Serialize, Deserialize, Clone, Type, Default)]
pub enum ClientOs {
#[cfg_attr(not(target_os = "macos"), default)]
Linux,
Windows,
#[cfg_attr(target_os = "macos", default)]
Mac,
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
#[serde(rename_all = "lowercase")]
pub enum CscMode {
#[default]
Auto,
Yes,
No,
}
impl From<&str> for ClientOs {
fn from(os: &str) -> Self {
match os {
"Linux" => ClientOs::Linux,
"Windows" => ClientOs::Windows,
"Mac" => ClientOs::Mac,
_ => ClientOs::Linux,
}
}
}
impl ClientOs {
pub fn as_str(&self) -> &str {
impl CscMode {
pub fn effective(self, client_os: ClientOs) -> bool {
match self {
ClientOs::Linux => "Linux",
ClientOs::Windows => "Windows",
ClientOs::Mac => "Mac",
CscMode::Auto => client_os.default_csc_support(),
CscMode::Yes => true,
CscMode::No => false,
}
}
pub fn to_openconnect_os(&self) -> &str {
pub fn as_str(self) -> &'static str {
match self {
ClientOs::Linux => "linux",
ClientOs::Windows => "win",
ClientOs::Mac => "mac-intel",
CscMode::Auto => "auto",
CscMode::Yes => "yes",
CscMode::No => "no",
}
}
}
#[derive(Debug, Serialize, Deserialize, Type, Default, Clone)]
#[derive(Debug, Clone)]
pub struct GpParams {
is_gateway: bool,
user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
// Endpoint identifier. PAN-OS binds the portal's authentication-override cookie
// (portal-userauthcookie) to this value; without it the portal returns an empty
// cookie and the gateway then rejects SAML with saml-auth-status=-1 (issue #491).
host_id: String,
os_profile: OsProfile,
// Transport
ignore_tls_errors: bool,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
// Used for MFA
// Feature
csc_mode: CscMode,
// Per-request state
is_gateway: bool,
input_str: Option<String>,
otp: Option<String>,
}
impl GpParams {
pub fn builder() -> GpParamsBuilder {
GpParamsBuilder::new()
pub fn builder(os_profile: OsProfile) -> GpParamsBuilder {
GpParamsBuilder::new(os_profile)
}
pub(crate) fn is_gateway(&self) -> bool {
@@ -82,27 +65,63 @@ impl GpParams {
}
pub(crate) fn user_agent(&self) -> &str {
&self.user_agent
}
pub(crate) fn computer(&self) -> &str {
&self.computer
self.os_profile.user_agent()
}
pub fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
// ─── OsProfile accessor ─────────────────────────────────────────────────
pub fn os_profile(&self) -> &OsProfile {
&self.os_profile
}
// ─── Delegated identity accessors ────────────────────────────────────────
pub fn client_os(&self) -> &str {
self.client_os.as_str()
self.os_profile.client_os().as_str()
}
pub(crate) fn computer(&self) -> &str {
self.os_profile.computer()
}
pub fn os_version(&self) -> Option<&str> {
self.os_version.as_deref()
Some(self.os_profile.os_version())
}
pub fn client_version(&self) -> Option<&str> {
self.client_version.as_deref()
Some(self.os_profile.client_version())
}
pub(crate) fn host_id(&self) -> &str {
self.os_profile.host_id()
}
pub(crate) fn serialno(&self) -> &str {
self.os_profile.serialno()
}
pub fn host_identity(&self) -> &HostIdentity {
self.os_profile.host_identity()
}
// ─── Feature accessors ──────────────────────────────────────────────────
pub(crate) fn effective_csc_support(&self) -> bool {
self.csc_mode.effective(self.os_profile.client_os())
}
pub fn csc_mode(&self) -> CscMode {
self.csc_mode
}
// ─── Per-request state ──────────────────────────────────────────────────
pub(crate) fn input_str(&self) -> Option<&str> {
self.input_str.as_deref()
}
pub fn set_input_str(&mut self, input_str: &str) {
@@ -113,48 +132,15 @@ impl GpParams {
self.otp = Some(otp.to_string());
}
pub(crate) fn to_params(&self) -> HashMap<&str, &str> {
let mut params: HashMap<&str, &str> = HashMap::new();
let client_os = self.client_os.as_str();
// Common params
params.insert("prot", "https:");
params.insert("jnlpReady", "jnlpReady");
params.insert("ok", "Login");
params.insert("direct", "yes");
params.insert("ipv6-support", "yes");
params.insert("clientVer", "4100");
params.insert("clientos", client_os);
params.insert("computer", &self.computer);
params.insert("host-id", &self.host_id);
// MFA
params.insert("inputStr", self.input_str.as_deref().unwrap_or_default());
if let Some(otp) = &self.otp {
params.insert("passwd", otp);
}
if let Some(os_version) = &self.os_version {
params.insert("os-version", os_version);
}
// NOTE: Do not include clientgpversion for now
// if let Some(client_version) = &self.client_version {
// params.insert("clientgpversion", client_version);
// }
params
pub(crate) fn otp(&self) -> Option<&str> {
self.otp.as_deref()
}
}
pub struct GpParamsBuilder {
is_gateway: bool,
user_agent: String,
client_os: ClientOs,
os_version: Option<String>,
client_version: Option<String>,
computer: String,
host_id: String,
os_profile: OsProfile,
csc_mode: CscMode,
ignore_tls_errors: bool,
certificate: Option<String>,
sslkey: Option<String>,
@@ -162,18 +148,11 @@ pub struct GpParamsBuilder {
}
impl GpParamsBuilder {
pub fn new() -> Self {
let computer = whoami::fallible::hostname().unwrap_or_else(|_| String::from("localhost"));
pub fn new(os_profile: OsProfile) -> Self {
Self {
is_gateway: false,
user_agent: GP_USER_AGENT.to_string(),
client_os: ClientOs::Linux,
os_version: Default::default(),
client_version: Default::default(),
computer,
// Stable per-machine UUID (same derivation the HIP report uses)
host_id: host_utils::derive_uuid(&[]),
os_profile,
csc_mode: Default::default(),
ignore_tls_errors: false,
certificate: Default::default(),
sslkey: Default::default(),
@@ -186,33 +165,8 @@ impl GpParamsBuilder {
self
}
pub fn user_agent(&mut self, user_agent: &str) -> &mut Self {
self.user_agent = user_agent.to_string();
self
}
pub fn client_os(&mut self, client_os: ClientOs) -> &mut Self {
self.client_os = client_os;
self
}
pub fn os_version<T: Into<Option<String>>>(&mut self, os_version: T) -> &mut Self {
self.os_version = os_version.into();
self
}
pub fn client_version<T: Into<Option<String>>>(&mut self, client_version: T) -> &mut Self {
self.client_version = client_version.into();
self
}
pub fn computer(&mut self, computer: &str) -> &mut Self {
self.computer = computer.to_string();
self
}
pub fn host_id(&mut self, host_id: &str) -> &mut Self {
self.host_id = host_id.to_string();
pub fn csc_mode(&mut self, csc_mode: CscMode) -> &mut Self {
self.csc_mode = csc_mode;
self
}
@@ -238,36 +192,26 @@ impl GpParamsBuilder {
pub fn build(&self) -> GpParams {
GpParams {
is_gateway: self.is_gateway,
user_agent: self.user_agent.clone(),
client_os: self.client_os.clone(),
os_version: self.os_version.clone(),
client_version: self.client_version.clone(),
computer: self.computer.clone(),
host_id: self.host_id.clone(),
os_profile: self.os_profile.clone(),
ignore_tls_errors: self.ignore_tls_errors,
certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(),
csc_mode: self.csc_mode,
is_gateway: self.is_gateway,
input_str: Default::default(),
otp: Default::default(),
}
}
}
impl Default for GpParamsBuilder {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<&GpParams> for Client {
type Error = anyhow::Error;
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(value.ignore_tls_errors)
.user_agent(&value.user_agent);
.user_agent(value.user_agent());
if let Some(cert) = value.certificate.as_deref() {
info!("Using client certificate authentication...");
@@ -279,3 +223,327 @@ impl TryFrom<&GpParams> for Client {
Ok(client)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::runtime_client_os;
fn profile(client_os: ClientOs) -> OsProfile {
OsProfile::builder(client_os).build()
}
#[test]
fn default_client_versions_match_observed_official_clients() {
assert_eq!(ClientOs::Linux.default_client_version(), "6.3.3-619");
assert_eq!(ClientOs::Windows.default_client_version(), "6.3.3-650");
assert_eq!(ClientOs::Mac.default_client_version(), "6.3.3-915");
}
#[test]
fn builder_uses_os_profile_client_version_when_unspecified() {
let params = GpParams::builder(profile(ClientOs::Mac)).build();
assert_eq!(params.client_version(), Some("6.3.3-915"));
}
#[test]
fn builder_keeps_explicit_client_version() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.2.9-1".to_string())
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.client_version(), Some("6.2.9-1"));
}
#[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();
assert_eq!(params.os_version(), Some(default_os_version.as_str()));
}
#[test]
fn os_profile_accessor_returns_profile() {
let params = GpParams::builder(profile(ClientOs::Linux)).build();
let profile = params.os_profile();
assert_eq!(profile.client_os(), ClientOs::Linux);
}
#[test]
fn delegates_identity_to_os_profile() {
let identity = HostIdentity::new(
"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();
assert!(!params.host_id().is_empty());
assert_eq!(params.host_identity().host_id(), "test-host-id");
assert_eq!(params.host_identity().serialno(), "test-serial");
assert_eq!(params.host_identity().mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn builder_accepts_pre_built_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyMac")
.build();
let expected_os_version = profile.os_version().to_string();
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyMac");
assert_eq!(params.os_version(), Some(expected_os_version.as_str()));
assert_eq!(params.client_os(), "Mac");
}
// ─── Delegation tests (Requirement 4.1) ──────────────────────────────────
#[test]
fn delegates_computer_to_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyComputer")
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyComputer");
assert_eq!(params.computer(), params.os_profile().computer());
}
#[test]
fn delegates_client_os_string_to_os_profile() {
let params = GpParams::builder(profile(ClientOs::Windows)).build();
assert_eq!(params.client_os(), "Windows");
assert_eq!(params.client_os(), params.os_profile().client_os().as_str());
}
#[test]
fn delegates_host_identity_to_os_profile() {
let identity = HostIdentity::new(
"delegated-computer".to_string(),
"delegated-host".to_string(),
"delegated-serial".to_string(),
"01:02:03:04:05:06".to_string(),
);
let params = GpParams::builder(
OsProfile::builder(ClientOs::Linux)
.host_identity(identity.clone())
.build(),
)
.build();
// The accessor returns the same HostIdentity stored on the inner OsProfile
assert_eq!(params.host_identity(), params.os_profile().host_identity());
assert_eq!(params.host_identity().host_id(), "delegated-host");
assert_eq!(params.host_identity().serialno(), "delegated-serial");
assert_eq!(params.host_identity().mac_addr(), "01:02:03:04:05:06");
}
// ─── Builder constructs OsProfile from individual fields (Req 4.1) ───────
#[test]
fn builder_uses_provided_os_profile() {
let identity = HostIdentity::new(
"identity-host".to_string(),
"host-7".to_string(),
"serial-7".to_string(),
"aa:bb:cc:11:22:33".to_string(),
);
let profile = OsProfile::builder(ClientOs::Linux)
.computer_name_override("linux-host")
.client_version("6.0.0-1".to_string())
.host_identity(identity)
.build();
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.client_version(), "6.0.0-1");
assert_eq!(profile.host_identity().host_id(), "host-7");
assert_eq!(profile.host_identity().serialno(), "serial-7");
assert_eq!(profile.host_identity().mac_addr(), "aa:bb:cc:11:22:33");
assert!(!profile.host_id().is_empty());
assert!(!profile.serialno().is_empty());
assert!(!profile.mac_addr().is_empty());
}
// ─── TryFrom<&GpParams> for Client (Requirement 4.7) ─────────────────────
#[test]
fn try_from_gp_params_constructs_reqwest_client() {
let params = GpParams::builder(profile(runtime_client_os())).build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client construction should succeed with default params");
}
#[test]
fn try_from_gp_params_with_ignore_tls_errors() {
let params = GpParams::builder(profile(runtime_client_os()))
.ignore_tls_errors(true)
.build();
let client = Client::try_from(&params);
assert!(
client.is_ok(),
"Client should construct successfully with ignore_tls_errors enabled"
);
}
#[test]
fn try_from_gp_params_with_custom_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
.user_agent("custom-agent/1.0")
.build(),
)
.build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client should construct with a custom user agent");
}
#[test]
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()))
.certificate("/nonexistent/path/to/cert.pem".to_string())
.build();
let client = Client::try_from(&params);
assert!(
client.is_err(),
"Client construction should fail when certificate path is invalid"
);
}
// ─── User Agent Delegation Tests (Requirements 3.2, 3.3, 3.4, 3.5, 3.6) ──
#[test]
fn user_agent_delegates_to_os_profile_for_default_build() {
let params = GpParams::builder(profile(runtime_client_os())).build();
assert_eq!(
params.user_agent(),
params.os_profile().user_agent(),
"GpParams::user_agent() should delegate to os_profile().user_agent()"
);
}
#[test]
fn builder_uses_profile_user_agent() {
let params = GpParams::builder(OsProfile::builder(runtime_client_os()).user_agent("custom").build()).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 expected_ua = profile.user_agent().to_string();
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), expected_ua);
}
#[test]
fn profile_user_agent_override_wins_before_gp_params_construction() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.1.0")
.user_agent("override")
.build();
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), "override");
}
#[test]
fn try_from_gp_params_succeeds_with_delegated_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
.user_agent("delegated-agent/2.0")
.build(),
)
.build();
let client = Client::try_from(&params);
assert!(
client.is_ok(),
"TryFrom<&GpParams> for Client should succeed with delegated user_agent"
);
}
// ─── Property-Based Tests ─────────────────────────────────────────────────
mod prop_tests {
use super::*;
use proptest::prelude::*;
fn arb_client_os() -> impl Strategy<Value = ClientOs> {
prop_oneof![Just(ClientOs::Linux), Just(ClientOs::Windows), Just(ClientOs::Mac),]
}
// **Validates: Requirements 3.2, 3.4**
//
// Property 4: GpParams delegates user_agent to OsProfile
// For any GpParams instance (whether built from individual fields or from a
// pre-built OsProfile, with or without a user_agent override),
// gp_params.user_agent() == gp_params.os_profile().user_agent().
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn gp_params_delegates_user_agent_to_os_profile(
client_os in arb_client_os(),
user_agent_override in proptest::option::of("[a-zA-Z0-9/_.-]{1,30}"),
) {
let identity = HostIdentity::new(
"prop-computer".to_string(),
"prop-host".to_string(),
"prop-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let mut profile_builder = OsProfile::builder(client_os)
.client_version("6.1.0-1")
.computer_name_override("test-host")
.host_identity(identity);
if let Some(ref ua) = user_agent_override {
profile_builder = profile_builder.user_agent(ua);
}
let params = GpParams::builder(profile_builder.build()).build();
prop_assert_eq!(
params.user_agent(),
params.os_profile().user_agent(),
"GpParams::user_agent() must always equal GpParams::os_profile().user_agent()"
);
}
}
// **Validates: Requirements 3.3**
//
// Property 5: GpParams uses the user agent from OsProfile.
// For any non-empty string set via OsProfileBuilder::user_agent(), the resulting
// GpParams::user_agent() returns that override value.
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 params = GpParams::builder(profile).build();
prop_assert_eq!(params.user_agent(), ua.as_str());
}
}
}
}
+2
View File
@@ -4,6 +4,8 @@ pub mod credential;
pub mod error;
pub mod gateway;
pub mod gp_params;
pub mod os_profile;
pub mod params;
pub mod portal;
pub mod process;
pub mod service;
@@ -0,0 +1,581 @@
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(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
RuntimeNativeHostIdentity::collect(host_id).into_host_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)
}
pub(crate) 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 std::process::Command;
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
NativeHostIdentitySnapshot {
host_id,
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
serial_number: collect_macos_serial_number(),
mac_address: native_mac,
}
}
}
fn macos_computer_name() -> Option<String> {
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
})
}
fn macos_builtin_mac() -> Option<String> {
macos_networksetup_mac("Wi-Fi")
.or_else(|| macos_networksetup_mac("AirPort"))
.or_else(macos_system_profiler_wifi_mac)
}
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
let output = Command::new("networksetup")
.arg("-listallhardwareports")
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = 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() -> Option<String> {
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
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 normalize_mac_colon(mac);
}
}
None
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).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(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,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) 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> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.iter()
.find_map(|path| read_linux_identity_file(path))
}
#[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);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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(None);
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()));
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,78 @@
pub(super) fn vmware_from_uuid(uuid: &str) -> Option<String> {
let parts: Vec<&str> = uuid.split('-').collect();
if parts.len() != 5
|| parts[0].len() != 8
|| parts[1].len() != 4
|| parts[2].len() != 4
|| parts[3].len() != 4
|| parts[4].len() != 12
|| !parts.iter().all(|part| part.chars().all(|ch| ch.is_ascii_hexdigit()))
{
return None;
}
let compact = [
reverse_hex_bytes(parts[0]),
reverse_hex_bytes(parts[1]),
reverse_hex_bytes(parts[2]),
parts[3].to_lowercase(),
parts[4].to_lowercase(),
]
.concat();
vmware_from_compact_hex(&compact)
}
pub(super) fn vmware_from_compact_hex(compact: &str) -> Option<String> {
let compact = compact.trim().to_lowercase();
if compact.len() != 32 || !compact.chars().all(|ch| ch.is_ascii_hexdigit()) {
return None;
}
Some(format!(
"VMware-{} {} {} {} {} {} {} {}-{} {} {} {} {} {} {} {}",
&compact[0..2],
&compact[2..4],
&compact[4..6],
&compact[6..8],
&compact[8..10],
&compact[10..12],
&compact[12..14],
&compact[14..16],
&compact[16..18],
&compact[18..20],
&compact[20..22],
&compact[22..24],
&compact[24..26],
&compact[26..28],
&compact[28..30],
&compact[30..32]
))
}
fn reverse_hex_bytes(value: &str) -> String {
value
.as_bytes()
.chunks(2)
.rev()
.map(|chunk| std::str::from_utf8(chunk).unwrap_or_default().to_lowercase())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vmware_serial_from_uuid_uses_smbios_byte_order() {
assert_eq!(
vmware_from_uuid("5a784d56-6461-19ac-9ea9-d36a3b9c6cef").unwrap(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn invalid_uuid_is_rejected() {
assert_eq!(vmware_from_uuid("not-a-uuid"), None);
}
}
+62
View File
@@ -0,0 +1,62 @@
use crate::{credential::Credential, gp_params::GpParams};
const EMPTY_PORTAL_COOKIE: &str = "empty";
fn portal_cookie_param(value: Option<&str>) -> String {
match value {
Some(value) if !value.is_empty() => value.to_string(),
_ => EMPTY_PORTAL_COOKIE.to_string(),
}
}
pub(crate) fn build(cred: &Credential, gp_params: &GpParams) -> Vec<(String, String)> {
let mut params = Vec::new();
params.push(("user".to_string(), cred.username().to_string()));
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match cred {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (
Some(gp_params.os_profile().saml_password()),
cred.prelogin_cookie(),
cred.portal_userauthcookie(),
None,
cred.token(),
),
Credential::AuthCookie(cred) => (
Some(
cred
.password()
.unwrap_or_else(|| gp_params.os_profile().saml_password()),
),
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::Cached(cred) => (
cred.password(),
None,
cred.auth_cookie().map(|cred| cred.user_auth_cookie()),
cred.auth_cookie().map(|cred| cred.prelogon_user_auth_cookie()),
None,
),
};
params.push(("passwd".to_string(), passwd.unwrap_or_default().to_string()));
params.push((
"prelogin-cookie".to_string(),
prelogin_cookie.unwrap_or_default().to_string(),
));
params.push((
"portal-userauthcookie".to_string(),
portal_cookie_param(portal_userauthcookie),
));
params.push((
"portal-prelogonuserauthcookie".to_string(),
portal_cookie_param(portal_prelogonuserauthcookie),
));
params.push(("token".to_string(), token.unwrap_or_default().to_string()));
params
}
+487
View File
@@ -0,0 +1,487 @@
use std::net::ToSocketAddrs;
use super::{RequestParams, credential as credential_params};
use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams};
/// Inputs required to build gateway login request parameters.
pub(crate) struct GatewayLoginInput<'a> {
pub gp_params: &'a GpParams,
pub cred: &'a Credential,
pub gateway_host: &'a str,
pub context: Option<&'a GatewayLoginContext>,
pub client_ip: Option<&'a str>,
pub extend_lifetime: bool,
}
/// Build request parameters for the gateway login endpoint.
///
/// 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.
pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams {
let profile = input.gp_params.os_profile();
let mut body: Vec<(String, String)> = Vec::new();
// Credential params (user, passwd, prelogin-cookie, portal-userauthcookie, etc.)
body.extend(credential_params::build(input.cred, input.gp_params));
// Common login params
body.push(("prot".into(), "https:".into()));
body.push(("jnlpReady".into(), "jnlpReady".into()));
body.push(("ok".into(), "Login".into()));
body.push(("direct".into(), "yes".into()));
body.push(("ipv6-support".into(), "yes".into()));
body.push(("clientVer".into(), "4100".into()));
body.push(("clientos".into(), profile.client_os().as_str().into()));
body.push(("computer".into(), profile.computer().into()));
body.push((
"inputStr".into(),
input.gp_params.input_str().unwrap_or_default().into(),
));
if let Some(otp) = input.gp_params.otp() {
body.push(("passwd".into(), otp.into()));
}
if let Some(os_version) = input.gp_params.os_version() {
body.push(("os-version".into(), os_version.into()));
}
// Server — resolve to IPv4 when profile requires it
let server = resolve_server(input);
body.push(("server".into(), server));
// Identity fields
body.push(("host-id".into(), profile.host_id().into()));
body.push(("serialno".into(), profile.serialno().into()));
body.push(("preferred-ip".into(), String::new()));
body.push(("preferred-ipv6".into(), String::new()));
// Client version
if let Some(client_version) = input.gp_params.client_version() {
body.push(("clientgpversion".into(), client_version.to_string()));
}
// Context-dependent fields
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));
body.push(("internal".into(), context.kind().as_login_param().to_string()));
body.push((
"selection-type".into(),
context.selection().as_login_param().to_string(),
));
body.push(("client-ipv6".into(), String::new()));
if let Some(connect_method) = context.connect_method() {
body.push(("connect-method".into(), connect_method.to_string()));
}
if let Some(client_version) = input.gp_params.client_version() {
// Ensure clientgpversion is set in the context block (override earlier value if present)
if let Some(pos) = body.iter().position(|(k, _)| k == "clientgpversion") {
body[pos].1 = client_version.to_string();
} else {
body.push(("clientgpversion".into(), client_version.to_string()));
}
}
if let Some(client_ip) = input.client_ip {
body.push(("client-ip".into(), client_ip.to_string()));
}
}
// Extend lifetime
if input.extend_lifetime {
body.push(("extend-lifetime".into(), "true".into()));
}
RequestParams { body, query: vec![] }
}
/// Resolve the gateway server to an IPv4 address if the profile requires it.
///
/// Falls back to the original gateway host if resolution fails.
fn resolve_server(input: &GatewayLoginInput) -> String {
if !input.gp_params.os_profile().gateway_server_uses_resolved_ipv4() {
return input.gateway_host.to_string();
}
if let Some(context) = input.context {
resolve_to_ipv4(context.host()).unwrap_or_else(|| input.gateway_host.to_string())
} else {
input.gateway_host.to_string()
}
}
/// Attempt DNS resolution of a hostname to its first IPv4 address.
fn resolve_to_ipv4(host: &str) -> Option<String> {
(host, 443)
.to_socket_addrs()
.ok()?
.find(|addr| addr.ip().is_ipv4())
.map(|addr| addr.ip().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
credential::{AuthCookieCredential, PasswordCredential},
gateway::{Gateway, GatewayKind, GatewaySelection},
os_profile::{ClientOs, HostIdentity, OsProfile},
};
fn test_identity() -> HostIdentity {
HostIdentity::new(
"test-computer".to_string(),
"host-id-123".to_string(),
"serial-456".to_string(),
"aa-bb-cc-dd-ee-ff".to_string(),
)
}
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os).host_identity(test_identity()).build()
}
fn make_gp_params() -> GpParams {
GpParams::builder(test_profile(ClientOs::Linux)).build()
}
fn make_credential() -> Credential {
Credential::Password(PasswordCredential::new("alice", "secret"))
}
#[test]
fn build_without_context_includes_identity_fields() {
let profile = test_profile(ClientOs::Linux);
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("host-id"), Some(profile.host_id()));
assert_eq!(find("serialno"), Some(profile.serialno()));
assert_eq!(find("preferred-ip"), Some(""));
assert_eq!(find("preferred-ipv6"), Some(""));
assert_eq!(find("token"), Some(""));
assert_eq!(find("server"), Some("vpn.example.com"));
}
#[test]
fn build_without_context_excludes_context_fields() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let has_key = |key: &str| result.body.iter().any(|(k, _)| k == key);
assert!(!has_key("host"));
assert!(!has_key("gw"));
assert!(!has_key("gateway-name"));
assert!(!has_key("internal"));
assert!(!has_key("selection-type"));
assert!(!has_key("connect-method"));
assert!(!has_key("client-ip"));
assert!(!has_key("client-ipv6"));
}
#[test]
fn build_with_context_includes_gateway_fqdn() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "us1.vpn.example.com",
context: Some(&context),
client_ip: Some("192.168.0.10"),
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("gw"), Some("us1.vpn.example.com"));
assert_eq!(find("gateway-name"), Some("us1.vpn.example.com"));
assert_eq!(find("host"), Some("us1.vpn.example.com"));
assert_eq!(find("internal"), Some("no"));
assert_eq!(find("selection-type"), Some("auto"));
assert_eq!(find("client-ip"), Some("192.168.0.10"));
assert_eq!(find("client-ipv6"), Some(""));
}
#[test]
fn mac_profile_uses_fqdn_for_gateway_display() {
let gp_params = GpParams::builder(test_profile(ClientOs::Mac)).build();
let cred = make_credential();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "us1.vpn.example.com",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("gw"), Some("us1.vpn.example.com"));
assert_eq!(find("gateway-name"), Some("us1.vpn.example.com"));
}
#[test]
fn linux_prelogin_credential_uses_profile_saml_password() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::Prelogin(crate::credential::PreloginCredential::new(
"alice",
Some("prelogin-cookie"),
None,
None,
));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("SAMLPASS"));
}
#[test]
fn portal_auth_cookie_login_leaves_gateway_prelogin_cookie_empty() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::AuthCookie(AuthCookieCredential::new("alice", "empty", "empty"));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("passwd"), Some("SAMLPASS"));
assert_eq!(find("prelogin-cookie"), Some(""));
assert_eq!(find("portal-userauthcookie"), Some("empty"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("empty"));
}
#[test]
fn portal_auth_cookie_login_reuses_portal_password_when_available() {
let gp_params = GpParams::builder(test_profile(ClientOs::Linux)).build();
let cred = Credential::AuthCookie(
AuthCookieCredential::new("alice", "portal-user-cookie", "portal-prelogon-cookie").with_password("secret"),
);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("passwd"), Some("secret"));
assert_eq!(find("prelogin-cookie"), Some(""));
assert_eq!(find("portal-userauthcookie"), Some("portal-user-cookie"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("portal-prelogon-cookie"));
}
#[test]
fn extend_lifetime_adds_param() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: true,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("extend-lifetime"), Some("true"));
}
#[test]
fn no_extend_lifetime_omits_param() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let has_key = |key: &str| result.body.iter().any(|(k, _)| k == key);
assert!(!has_key("extend-lifetime"));
}
#[test]
fn context_connect_method_included_when_present() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("GW".to_string(), "vpn.example.com".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual).with_connect_method(Some("on-demand"));
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("connect-method"), Some("on-demand"));
assert_eq!(find("selection-type"), Some("manual"));
}
#[test]
fn all_params_in_body_not_query() {
let gp_params = make_gp_params();
let cred = make_credential();
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "vpn.example.com",
context: None,
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
assert!(result.query.is_empty());
assert!(!result.body.is_empty());
}
#[test]
fn server_resolves_to_ipv4_with_context_using_localhost() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("Local".to_string(), "localhost".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "localhost",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let server = result
.body
.iter()
.find(|(k, _)| k == "server")
.map(|(_, v)| v.as_str())
.expect("server param should exist");
// localhost resolves to 127.0.0.1 (IPv4)
assert_eq!(server, "127.0.0.1");
}
#[test]
fn server_falls_back_to_host_when_resolution_fails() {
let gp_params = make_gp_params();
let cred = make_credential();
let gateway = Gateway::new("GW".to_string(), "nonexistent.invalid.test".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto);
let input = GatewayLoginInput {
gp_params: &gp_params,
cred: &cred,
gateway_host: "nonexistent.invalid.test",
context: Some(&context),
client_ip: None,
extend_lifetime: false,
};
let result = build(&input);
let server = result
.body
.iter()
.find(|(k, _)| k == "server")
.map(|(_, v)| v.as_str())
.expect("server param should exist");
// Falls back to the original gateway host when DNS resolution fails
assert_eq!(server, "nonexistent.invalid.test");
}
}
+125
View File
@@ -0,0 +1,125 @@
use super::RequestParams;
use crate::os_profile::{OsProfile, PreloginBrowserMode, PreloginParamLocation};
/// Build request parameters for the gateway prelogin endpoint.
///
/// Same as portal prelogin but uses the gateway-specific embedded browser value.
pub(crate) fn build(profile: &OsProfile, browser_mode: PreloginBrowserMode) -> RequestParams {
let default_browser = profile.gateway_default_browser(browser_mode);
let params: Vec<(String, String)> = vec![
("tmp".into(), "tmp".into()),
("clientVer".into(), "4100".into()),
("clientos".into(), profile.client_os().as_str().into()),
("os-version".into(), profile.os_version().into()),
("host-id".into(), profile.host_id().into()),
("ipv6-support".into(), "yes".into()),
("default-browser".into(), default_browser.into()),
("cas-support".into(), "yes".into()),
("data".into(), "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9".into()),
];
let mut query: Vec<(String, String)> = vec![];
if profile.kerberos_support_in_query() {
query.push(("kerberos-support".into(), "yes".into()));
}
match profile.prelogin_param_location() {
PreloginParamLocation::Body => RequestParams { body: params, query },
PreloginParamLocation::Query => RequestParams {
body: vec![],
query: params.into_iter().chain(query).collect(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::ClientOs;
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert_eq!(result.query.len(), 1);
assert_eq!(result.query[0], ("kerberos-support".into(), "yes".into()));
}
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
// 9 base params + 1 kerberos-support
assert_eq!(result.query.len(), 10);
}
#[test]
fn uses_embedded_gateway_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "0");
}
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "4");
}
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"tmp"));
assert!(keys.contains(&"clientVer"));
assert!(keys.contains(&"clientos"));
assert!(keys.contains(&"os-version"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"ipv6-support"));
assert!(keys.contains(&"default-browser"));
assert!(keys.contains(&"cas-support"));
assert!(keys.contains(&"data"));
}
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
.body
.iter()
.find(|(k, _)| k == "data")
.expect("data param should exist");
assert_eq!(data_param.1, "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9");
}
}
+15
View File
@@ -0,0 +1,15 @@
pub(crate) mod credential;
pub mod gateway_login;
pub mod gateway_prelogin;
pub mod portal_getconfig;
pub mod portal_prelogin;
/// Ordered request parameters split into body (form data) and query string.
///
/// Uses `Vec<(String, String)>` instead of `HashMap` to preserve parameter
/// ordering, as some servers may be sensitive to order.
#[derive(Debug, Clone, Default)]
pub struct RequestParams {
pub body: Vec<(String, String)>,
pub query: Vec<(String, String)>,
}
+304
View File
@@ -0,0 +1,304 @@
use super::{RequestParams, credential as credential_params};
use crate::{credential::Credential, gp_params::GpParams, os_profile::ClientOs, portal::csc::swg_nonce};
/// Build request parameters for the portal getconfig endpoint.
///
/// This builder produces the form body for `getconfig.esp`. It deliberately
/// excludes `server`, `prot`, `direct`, and `jnlpReady` which are not sent
/// by the official client for this endpoint.
///
/// For SAML (prelogin) credentials the password is set to `SAMLPASS` on Linux
/// 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 {
"0".to_string()
} else {
swg_nonce()
};
let mut body = credential_params::build(cred, gp_params);
body.push(("inputStr".into(), gp_params.input_str().unwrap_or_default().into()));
// Fixed params
body.push(("ok".into(), "Login".into()));
body.push(("clientVer".into(), "4100".into()));
// OS params
body.push(("clientos".into(), profile.client_os().as_str().into()));
body.push(("clientgpversion".into(), profile.client_version().into()));
body.push(("computer".into(), profile.computer().into()));
body.push(("os-version".into(), profile.os_version().into()));
body.push(("host-id".into(), profile.host_id().into()));
body.push(("ipv6-support".into(), "yes".into()));
body.push(("serialno".into(), profile.serialno().into()));
// CSC fields
body.push(("csc-digest".into(), String::new()));
body.push(("config-digest".into(), String::new()));
body.push((
"csc-support".into(),
if gp_params.effective_csc_support() { "yes" } else { "no" }.into(),
));
// Host and SWG
body.push(("host".into(), server.into()));
body.push(("swg-auth-token".into(), "0".into()));
body.push(("swg-nonce".into(), nonce));
RequestParams { body, query: vec![] }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
credential::{PasswordCredential, PreloginCredential},
gp_params::CscMode,
os_profile::{ClientOs, HostIdentity, OsProfile},
};
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os)
.computer_name_override("test-computer")
.client_version("6.3.3-100")
.host_identity(HostIdentity::new(
"test-computer".into(),
"test-host-id".into(),
"test-serial".into(),
"aa:bb:cc:dd:ee:ff".into(),
))
.build()
}
fn password_cred() -> Credential {
Credential::from(PasswordCredential::new("alice", "secret"))
}
fn prelogin_cred() -> Credential {
Credential::Prelogin(PreloginCredential::new(
"alice",
Some("my-prelogin-cookie"),
Some("my-userauthcookie"),
None,
))
}
#[test]
fn excludes_forbidden_params() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(!keys.contains(&"server"));
assert!(!keys.contains(&"prot"));
assert!(!keys.contains(&"direct"));
assert!(!keys.contains(&"jnlpReady"));
}
#[test]
fn includes_required_params() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"clientgpversion"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"serialno"));
assert!(keys.contains(&"token"));
}
#[test]
fn includes_identity_from_profile() {
let profile = test_profile(ClientOs::Mac);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("host-id"), Some(profile.host_id()));
assert_eq!(find("serialno"), Some(profile.serialno()));
assert_eq!(find("clientgpversion"), Some("6.3.3-100"));
assert_eq!(find("computer"), Some("test-computer"));
assert_eq!(find("os-version"), Some(profile.os_version()));
assert_eq!(find("clientos"), Some("Mac"));
}
#[test]
fn linux_saml_sets_passwd_to_samlpass() {
let profile = test_profile(ClientOs::Linux);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("SAMLPASS"));
}
#[test]
fn mac_saml_sets_passwd_to_empty() {
let profile = test_profile(ClientOs::Mac);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some(""));
}
#[test]
fn saml_without_portal_auth_cookies_uses_empty_sentinel() {
let profile = test_profile(ClientOs::Mac);
let cred = Credential::Prelogin(PreloginCredential::new("alice", Some("my-prelogin-cookie"), None, None));
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("portal-userauthcookie"), Some("empty"));
assert_eq!(find("portal-prelogonuserauthcookie"), Some("empty"));
}
#[test]
fn saml_blank_portal_auth_cookie_uses_empty_sentinel() {
let profile = test_profile(ClientOs::Mac);
let cred = Credential::Prelogin(PreloginCredential::new(
"alice",
Some("my-prelogin-cookie"),
Some(""),
None,
));
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let portal_cookie = result
.body
.iter()
.find(|(k, _)| k == "portal-userauthcookie")
.map(|(_, v)| v.as_str());
assert_eq!(portal_cookie, Some("empty"));
}
#[test]
fn windows_saml_sets_passwd_to_empty() {
let profile = test_profile(ClientOs::Windows);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some(""));
}
#[test]
fn password_cred_sends_actual_password() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let passwd = result.body.iter().find(|(k, _)| k == "passwd").map(|(_, v)| v.as_str());
assert_eq!(passwd, Some("secret"));
}
#[test]
fn includes_csc_support_fields() {
let profile = test_profile(ClientOs::Mac);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("csc-support"), Some("yes"));
assert_eq!(find("csc-digest"), Some(""));
assert_eq!(find("config-digest"), Some(""));
assert_eq!(find("swg-auth-token"), Some("0"));
assert!(find("swg-nonce").is_some());
}
#[test]
fn linux_uses_zero_swg_nonce() {
let profile = test_profile(ClientOs::Linux);
let cred = prelogin_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let nonce = result
.body
.iter()
.find(|(k, _)| k == "swg-nonce")
.map(|(_, v)| v.as_str());
assert_eq!(nonce, Some("0"));
}
#[test]
fn linux_defaults_csc_support_to_no() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let csc = result
.body
.iter()
.find(|(k, _)| k == "csc-support")
.map(|(_, v)| v.as_str());
assert_eq!(csc, Some("no"));
}
#[test]
fn csc_mode_override_works() {
let cred = password_cred();
let gp_params = GpParams::builder(test_profile(ClientOs::Linux))
.csc_mode(CscMode::Yes)
.build();
let result = build(&cred, &gp_params, "vpn.example.com");
let csc = result
.body
.iter()
.find(|(k, _)| k == "csc-support")
.map(|(_, v)| v.as_str());
assert_eq!(csc, Some("yes"));
}
#[test]
fn host_param_is_server_value() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let host = result.body.iter().find(|(k, _)| k == "host").map(|(_, v)| v.as_str());
assert_eq!(host, Some("vpn.example.com"));
}
#[test]
fn token_is_empty_for_password_cred() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
let token = result.body.iter().find(|(k, _)| k == "token").map(|(_, v)| v.as_str());
assert_eq!(token, Some(""));
}
#[test]
fn all_params_in_body_not_query() {
let profile = test_profile(ClientOs::Linux);
let cred = password_cred();
let gp_params = GpParams::builder(profile.clone()).build();
let result = build(&cred, &gp_params, "vpn.example.com");
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
}
+147
View File
@@ -0,0 +1,147 @@
use super::RequestParams;
use crate::os_profile::{OsProfile, PreloginBrowserMode, PreloginParamLocation};
/// Build request parameters for the portal prelogin endpoint.
///
/// Parameters are placed in the request body for Linux/macOS and in the query
/// string for Windows, based on `profile.prelogin_param_location()`.
///
/// When `profile.kerberos_support_in_query()` is true (macOS/Windows),
/// `kerberos-support=yes` is added as a query parameter.
pub(crate) fn build(profile: &OsProfile, browser_mode: PreloginBrowserMode) -> RequestParams {
let default_browser = profile.portal_default_browser(browser_mode);
let params: Vec<(String, String)> = vec![
("tmp".into(), "tmp".into()),
("clientVer".into(), "4100".into()),
("clientos".into(), profile.client_os().as_str().into()),
("os-version".into(), profile.os_version().into()),
("host-id".into(), profile.host_id().into()),
("ipv6-support".into(), "yes".into()),
("default-browser".into(), default_browser.into()),
("cas-support".into(), "yes".into()),
("data".into(), "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9".into()),
];
let mut query: Vec<(String, String)> = vec![];
if profile.kerberos_support_in_query() {
query.push(("kerberos-support".into(), "yes".into()));
}
match profile.prelogin_param_location() {
PreloginParamLocation::Body => RequestParams { body: params, query },
PreloginParamLocation::Query => RequestParams {
body: vec![],
query: params.into_iter().chain(query).collect(),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::ClientOs;
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert!(result.query.is_empty());
}
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
assert_eq!(result.query.len(), 1);
assert_eq!(result.query[0], ("kerberos-support".into(), "yes".into()));
}
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
// 9 base params + 1 kerberos-support
assert_eq!(result.query.len(), 10);
}
#[test]
fn uses_embedded_portal_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "-10");
}
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
.body
.iter()
.find(|(k, _)| k == "default-browser")
.expect("default-browser param should exist");
assert_eq!(browser_param.1, "4");
}
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
assert!(keys.contains(&"tmp"));
assert!(keys.contains(&"clientVer"));
assert!(keys.contains(&"clientos"));
assert!(keys.contains(&"os-version"));
assert!(keys.contains(&"host-id"));
assert!(keys.contains(&"ipv6-support"));
assert!(keys.contains(&"default-browser"));
assert!(keys.contains(&"cas-support"));
assert!(keys.contains(&"data"));
}
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
.body
.iter()
.find(|(k, _)| k == "data")
.expect("data param should exist");
assert_eq!(data_param.1, "eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9");
}
#[test]
fn kerberos_not_in_query_for_linux() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support");
assert!(!has_kerberos);
}
#[test]
fn kerberos_in_query_for_windows() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let result = build(&profile, PreloginBrowserMode::Embedded);
let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support");
assert!(has_kerberos);
}
}
+196 -26
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
@@ -11,9 +13,12 @@ use crate::{
error::PortalError,
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
params,
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
};
use super::csc;
#[derive(Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PortalConfig {
@@ -21,6 +26,7 @@ pub struct PortalConfig {
auth_cookie: AuthCookieCredential,
config_cred: Credential,
gateways: Vec<Gateway>,
connect_method: Option<String>,
config_digest: Option<String>,
/**
* Variants:
@@ -37,6 +43,10 @@ pub struct PortalConfig {
* Whether the portal policy allows extending the gateway session.
*/
allow_extend_session: Option<bool>,
/**
* Whether the portal policy enables default-browser authentication.
*/
default_browser: Option<bool>,
}
impl PortalConfig {
@@ -60,6 +70,10 @@ impl PortalConfig {
self.internal_host_detection
}
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub fn version(&self) -> Option<&str> {
self.version.as_deref()
}
@@ -68,6 +82,10 @@ impl PortalConfig {
self.allow_extend_session
}
pub fn default_browser(&self) -> Option<bool> {
self.default_browser
}
/// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region);
@@ -118,16 +136,17 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let url = format!("{}/global-protect/getconfig.esp", portal);
let client = Client::try_from(gp_params)?;
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &server);
params.insert("host", &server);
let request_params = params::portal_getconfig::build(cred, gp_params, &server);
let body_pairs: Vec<(&str, &str)> = request_params
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_form_params(&body_pairs));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
@@ -152,11 +171,86 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
debug!("Portal config response: {}", res_xml);
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
info!("Portal returned CSC criteria: {}", csc_criteria_summary(&root));
if !gp_params.effective_csc_support() {
bail!(PortalError::ConfigError(
"Portal returned CSC criteria but CSC support is disabled".to_string()
));
}
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml);
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root);
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root)
}
async fn retrieve_csc_config(
client: &Client,
portal: &str,
root: &Element,
username: &str,
gp_params: &GpParams,
) -> anyhow::Result<String> {
let csc_req = csc::build_csc_request(root, username, gp_params)?;
let swg_nonce = csc::swg_nonce();
let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce);
let url = format!("{}/global-protect/getconfig_csc.esp", portal);
info!("Portal CSC config request summary: {}", csc_req.summary());
info!("Portal CSC config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal CSC config error: {}", err.reason);
}
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})
}
fn redact_params(params: &HashMap<&str, &str>) -> String {
let params = params.iter().map(|(key, value)| (*key, *value)).collect::<Vec<_>>();
redact_form_params(&params)
}
fn csc_criteria_summary(root: &Element) -> String {
let auth_cookie = present(root.descendant_text("portal-csc-auth-cookie").as_deref());
let config_digest = present(root.descendant_text("config-digest").as_deref());
let custom_check_entries = root
.descendant("custom-checks")
.map(|custom_checks| custom_checks.descendants("entry").len())
.unwrap_or_default();
format!("auth_cookie={auth_cookie}, config_digest={config_digest}, custom_check_entries={custom_check_entries}")
}
fn present(value: Option<&str>) -> &'static str {
match value {
Some(value) if !value.is_empty() => "present",
_ => "empty",
}
}
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
let mut ihd_enabled = false;
let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true;
prefer_internal = internal_host_detect(&ihd_node)
prefer_internal = internal_host_detect(ihd_node)
}
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -169,27 +263,41 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
.descendant_text("portal-prelogonuserauthcookie")
.unwrap_or_default();
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);
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: if ihd_enabled { Some(prefer_internal) } else { None },
version,
allow_extend_session,
default_browser,
})
}
fn parse_default_browser(root: &Element) -> Option<bool> {
match root.descendant_text("default-browser")?.trim() {
"yes" => Some(true),
"no" => Some(false),
_ => None,
}
}
fn parse_allow_extend_session(root: &Element) -> Option<bool> {
match root.descendant_text("allow-extend-session")?.trim() {
"yes" => Some(true),
@@ -198,6 +306,13 @@ fn parse_allow_extend_session(root: &Element) -> Option<bool> {
}
}
fn parse_connect_method(root: &Element) -> Option<String> {
root
.descendant_text("connect-method")
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
}
// Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool {
let ip_info = [
@@ -208,23 +323,24 @@ fn internal_host_detect(element: &Element) -> bool {
info!("Found internal-host-detection, performing DNS lookup");
for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref()) {
if !ip_address.is_empty() && !host.is_empty() {
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
&& !ip_address.is_empty()
&& !host.is_empty()
{
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
}
}
@@ -267,4 +383,58 @@ mod tests {
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn parses_default_browser_yes() {
let root = parse_xml("<response><default-browser>yes</default-browser></response>");
assert_eq!(parse_default_browser(&root), Some(true));
}
#[test]
fn parses_default_browser_no() {
let root = parse_xml("<response><default-browser>no</default-browser></response>");
assert_eq!(parse_default_browser(&root), Some(false));
}
#[test]
fn leaves_absent_default_browser_unknown() {
let root = parse_xml("<response></response>");
assert_eq!(parse_default_browser(&root), None);
}
#[test]
fn parses_connect_method() {
let root = parse_xml("<policy><connect-method>on-demand</connect-method></policy>");
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
}
#[test]
fn parses_csc_policy_response_as_portal_config() {
let root = parse_xml(
r#"<policy>
<portal-userauthcookie>user-cookie</portal-userauthcookie>
<portal-prelogonuserauthcookie>prelogon-cookie</portal-prelogonuserauthcookie>
<gateways>
<external>
<list>
<entry name="US_East">
<description>us1.vpn.example.com</description>
</entry>
</list>
</external>
</gateways>
</policy>"#,
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
assert_eq!(config.gateways().len(), 1);
}
}
+735
View File
@@ -0,0 +1,735 @@
use std::{
collections::HashMap,
fmt::Write,
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use xmltree::{Element, EmitterConfig, XMLNode};
use crate::{gp_params::GpParams, utils::xml::ElementExt};
const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__";
pub(super) struct CscRequest {
pub(super) auth_cookie: String,
pub(super) config_digest: String,
pub(super) csc_digest: String,
pub(super) csc_data: String,
summary: CscBuildSummary,
host_id: String,
serial_number: String,
}
impl CscRequest {
pub(super) fn summary(&self) -> String {
format!(
"digest_len={}, xml_len={}, plist_entries={}, plist_present={}, plist_missing={}, process_entries={}, process_present={}, process_missing={}",
self.csc_digest.len(),
self.csc_data.len(),
self.summary.plist_entries,
self.summary.plist_present,
self.summary.plist_missing,
self.summary.process_entries,
self.summary.process_present,
self.summary.process_missing,
)
}
}
#[derive(Default)]
struct CscBuildSummary {
plist_entries: usize,
plist_present: usize,
plist_missing: usize,
process_entries: usize,
process_present: usize,
process_missing: usize,
}
struct CscDataInput<'a> {
criteria: &'a Element,
auth_cookie: &'a str,
username: &'a str,
gp_params: &'a GpParams,
host_id: &'a str,
serial_number: &'a str,
csc_digest: &'a str,
}
pub(super) trait CscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String>;
fn process_exists(&self, name: &str) -> bool;
}
struct SystemCscDataReader;
impl CscDataReader for SystemCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
read_macos_preference(domain, key)
}
fn process_exists(&self, name: &str) -> bool {
linux_process_names().iter().any(|process_name| process_name == name)
}
}
pub(crate) fn swg_nonce() -> String {
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis())
.unwrap_or_default();
(millis % 2_147_483_647).to_string()
}
pub(super) fn is_config_criteria(root: &Element) -> bool {
root.name == "config-criteria"
}
pub(super) fn build_csc_request(root: &Element, username: &str, gp_params: &GpParams) -> anyhow::Result<CscRequest> {
let reader = SystemCscDataReader;
build_csc_request_with_reader(root, username, gp_params, &reader)
}
pub(super) fn build_csc_request_with_reader(
root: &Element,
username: &str,
gp_params: &GpParams,
reader: &dyn CscDataReader,
) -> anyhow::Result<CscRequest> {
let auth_cookie = root
.descendant_text("portal-csc-auth-cookie")
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow::anyhow!("CSC criteria response does not contain portal-csc-auth-cookie"))?;
let config_digest = root.descendant_text("config-digest").unwrap_or_default();
let host_id = gp_params.host_id().to_string();
let serial_number = gp_params.serialno().to_string();
let mut summary = CscBuildSummary::default();
let csc_data = build_csc_data(
CscDataInput {
criteria: root,
auth_cookie: &auth_cookie,
username,
gp_params,
host_id: &host_id,
serial_number: &serial_number,
csc_digest: DIGEST_PLACEHOLDER,
},
reader,
&mut summary,
)?;
let csc_digest = pan_md5_hex(csc_data.as_bytes());
let csc_data = csc_data.replace(DIGEST_PLACEHOLDER, &csc_digest);
Ok(CscRequest {
auth_cookie,
config_digest,
csc_digest,
csc_data,
summary,
host_id,
serial_number,
})
}
pub(super) fn csc_params<'a>(
req: &'a CscRequest,
username: &'a str,
gp_params: &'a GpParams,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = HashMap::new();
params.insert("user", username);
params.insert("clientVer", "4100");
params.insert("clientos", gp_params.client_os());
params.insert("os-version", gp_params.os_version().unwrap_or_default());
params.insert("hostid", req.host_id.as_str());
params.insert("serialno", req.serial_number.as_str());
params.insert("portal-cc-auth-cookie", req.auth_cookie.as_str());
params.insert("config-digest", req.config_digest.as_str());
params.insert("csc-digest", req.csc_digest.as_str());
params.insert("csc-data", req.csc_data.as_str());
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
fn build_csc_data(
input: CscDataInput<'_>,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> anyhow::Result<String> {
let mut root = Element::new("hip-report");
push_text(&mut root, "portal-csc-auth-cookie", input.auth_cookie);
push_text(&mut root, "user-name", &urlencoding::encode(input.username));
push_text(&mut root, "client-os", &client_os_report_value(input.gp_params));
push_text(&mut root, "host-id", input.host_id);
push_text(&mut root, "device-serial-number", input.serial_number);
push_text(&mut root, "csc-digest", input.csc_digest);
root.children.push(XMLNode::Element(Element::new("categories")));
let custom_checks = build_custom_checks(input.criteria, input.gp_params, reader, summary);
if !custom_checks.children.is_empty() {
root.children.push(XMLNode::Element(custom_checks));
}
let mut bytes = Vec::new();
root.write_with_config(
&mut bytes,
EmitterConfig::new()
.perform_indent(true)
.indent_string("\t")
.write_document_declaration(true),
)?;
String::from_utf8(bytes)
.map(|xml| {
let mut xml = xml.replace("<categories />", "<categories>\n\t</categories>");
xml.push('\n');
xml
})
.map_err(Into::into)
}
fn build_custom_checks(
criteria: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut custom_checks = Element::new("custom-checks");
let Some(requested_checks) = criteria.descendant("custom-checks") else {
return custom_checks;
};
if gp_params.os_profile().supports_macos_plist_csc()
&& let Some(plist) = requested_checks
.child("mac-os")
.and_then(|mac_os| mac_os.child("plist"))
{
custom_checks
.children
.push(XMLNode::Element(build_plist_checks(plist, reader, summary)));
}
if gp_params.os_profile().supports_linux_process_csc()
&& let Some(process_list) = requested_checks
.child("linux")
.and_then(|linux| linux.child("process-list"))
.or_else(|| requested_checks.child("process-list"))
{
custom_checks.children.push(XMLNode::Element(build_process_list_checks(
process_list,
reader,
summary,
)));
}
if gp_params.os_profile().supports_windows_registry_csc()
&& let Some(registry_key) = requested_checks
.child("windows")
.and_then(|windows| windows.child("registry-key"))
.or_else(|| requested_checks.child("registry-key"))
{
custom_checks
.children
.push(XMLNode::Element(build_registry_key_checks(registry_key)));
}
custom_checks
}
fn build_plist_checks(plist: &Element, reader: &dyn CscDataReader, summary: &mut CscBuildSummary) -> Element {
let mut out = Element::new("plist");
for entry in plist.children("entry") {
let domain = entry.attr("name").unwrap_or_default();
let mut out_entry = Element::new("entry");
out_entry.attributes.insert("name".to_string(), domain.to_string());
let keys = plist_entry_keys(entry);
let values: Vec<_> = keys
.iter()
.map(|key| {
let value = reader.read_preference(domain, key);
(key.as_str(), value)
})
.collect();
let plist_exists = values.iter().any(|(_, value)| value.is_some());
summary.plist_entries += keys.len();
summary.plist_present += values.iter().filter(|(_, value)| value.is_some()).count();
summary.plist_missing += values.iter().filter(|(_, value)| value.is_none()).count();
push_text(&mut out_entry, "exist", yes_no(plist_exists));
push_text(&mut out_entry, "value", "");
let mut preference_value = Element::new("preference-value");
for (key, value) in values {
let mut pref_entry = Element::new("entry");
pref_entry.attributes.insert("name".to_string(), key.to_string());
push_text(&mut pref_entry, "exist", yes_no(value.is_some()));
push_text(&mut pref_entry, "value", value.as_deref().unwrap_or_default());
preference_value.children.push(XMLNode::Element(pref_entry));
}
out_entry.children.push(XMLNode::Element(preference_value));
out.children.push(XMLNode::Element(out_entry));
}
out
}
fn build_process_list_checks(
process_list: &Element,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("process-list");
for process_name in process_list_names(process_list) {
let exists = reader.process_exists(&process_name);
summary.process_entries += 1;
if exists {
summary.process_present += 1;
} else {
summary.process_missing += 1;
}
let mut entry = Element::new("entry");
entry.attributes.insert("name".to_string(), process_name.clone());
push_text(&mut entry, "exist", yes_no(exists));
push_text(&mut entry, "value", if exists { &process_name } else { "" });
out.children.push(XMLNode::Element(entry));
}
out
}
fn plist_entry_keys(entry: &Element) -> Vec<String> {
let keys: Vec<String> = entry
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.to_string())
.collect();
if keys.is_empty() {
entry
.attr("name")
.map(|name| vec![name.to_string()])
.unwrap_or_default()
} else {
keys
}
}
fn process_list_names(process_list: &Element) -> Vec<String> {
let mut names: Vec<String> = process_list
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.collect();
names.extend(
process_list
.children("entry")
.into_iter()
.filter_map(|entry| entry.attr("name"))
.map(str::to_string),
);
names.sort();
names.dedup();
names
}
fn build_registry_key_checks(registry_key: &Element) -> Element {
let mut out = Element::new("registry-key");
for name in registry_key_names(registry_key) {
let mut entry = Element::new("entry");
entry.attributes.insert("name".to_string(), name);
push_text(&mut entry, "exist", "no");
push_text(&mut entry, "value", "");
out.children.push(XMLNode::Element(entry));
}
out
}
fn registry_key_names(registry_key: &Element) -> Vec<String> {
let mut names: Vec<String> = registry_key
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.collect();
names.extend(
registry_key
.children("entry")
.into_iter()
.filter_map(|entry| entry.attr("name"))
.map(str::to_string),
);
names.sort();
names.dedup();
names
}
fn pan_md5_hex(value: &[u8]) -> String {
let digest = md5::compute(value);
let mut out = String::new();
for byte in digest.0 {
write!(&mut out, "{:x}", byte).expect("writing to String should not fail");
}
out
}
fn read_macos_preference(domain: &str, key: &str) -> Option<String> {
if cfg!(not(target_os = "macos")) {
return None;
}
let output = Command::new("defaults").args(["read", domain, key]).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn linux_process_names() -> Vec<String> {
let Ok(entries) = fs::read_dir("/proc") else {
return Vec::new();
};
entries
.filter_map(Result::ok)
.filter_map(|entry| {
entry
.file_name()
.to_str()
.filter(|name| name.chars().all(|ch| ch.is_ascii_digit()))
.map(|_| entry.path().join("stat"))
})
.filter_map(|path| fs::read_to_string(path).ok())
.filter_map(|stat| {
let start = stat.find('(')?;
let end = stat.rfind(')')?;
stat.get(start + 1..end).map(str::to_string)
})
.filter(|name| !name.is_empty())
.collect()
}
fn client_os_report_value(gp_params: &GpParams) -> String {
gp_params
.os_version()
.unwrap_or_else(|| gp_params.client_os())
.replace(' ', "+")
}
fn push_text(parent: &mut Element, name: &str, value: &str) {
let mut element = Element::new(name);
element.children.push(XMLNode::Text(value.to_string()));
parent.children.push(XMLNode::Element(element));
}
fn yes_no(value: bool) -> &'static str {
if value { "yes" } else { "no" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, HostIdentity, OsProfile},
};
struct TestCscDataReader {
values: HashMap<String, String>,
processes: Vec<String>,
}
impl CscDataReader for TestCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
self.values.get(&format!("{domain}:{key}")).cloned()
}
fn process_exists(&self, name: &str) -> bool {
self.processes.iter().any(|process| process == name)
}
}
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
fn gp_params(client_os: ClientOs) -> GpParams {
let profile = OsProfile::builder(client_os)
.host_identity(HostIdentity::new(
"test-computer".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
GpParams::builder(profile).build()
}
#[test]
fn detects_config_criteria_response() {
assert!(is_config_criteria(&parse_xml("<config-criteria/>")));
assert!(!is_config_criteria(&parse_xml("<policy/>")));
}
#[test]
fn builds_macos_plist_csc_report_with_existing_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings">
<key><member>ExampleKey</member></key>
</entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([(
"com.example.settings:ExampleKey".to_string(),
"ExampleValue".to_string(),
)]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "[email protected]", &gp_params(ClientOs::Mac), &reader).unwrap();
assert_eq!(req.auth_cookie, "cookie");
assert!(req.csc_data.contains("<user-name>alice%40example.com</user-name>"));
assert!(req.csc_data.contains("<client-os>Apple+Mac+OS+X+"));
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
#[test]
fn reports_missing_macos_plist_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>Missing</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
assert!(req.csc_data.contains("<exist>no</exist>"));
assert!(req.csc_data.contains("<value />") || req.csc_data.contains("<value></value>"));
}
#[test]
fn empty_csc_report_uses_official_format_for_digest() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks />
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
let digest_input = req.csc_data.replace(&req.csc_digest, DIGEST_PLACEHOLDER);
assert_eq!(req.csc_digest, pan_md5_hex(digest_input.as_bytes()));
assert!(
req
.csc_data
.contains("\n\t<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>")
);
assert!(req.csc_data.contains("\n\t<categories>\n\t</categories>\n"));
assert!(req.csc_data.ends_with("</hip-report>\n"));
}
#[test]
fn unsupported_client_os_ignores_macos_plist_branch() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>HipID</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([("com.example:HipID".to_string(), "present".to_string())]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(!req.csc_data.contains("<plist>"));
assert!(!req.csc_data.contains("<exist>no</exist>"));
assert!(!req.csc_data.contains("present"));
}
#[test]
fn builds_linux_process_list_report() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<linux>
<process-list>
<entry name="present-process" />
<entry name="missing-process" />
</process-list>
</linux>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: vec!["present-process".to_string()],
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(req.csc_data.contains(r#"<entry name="present-process">"#));
assert!(req.csc_data.contains("<value>present-process</value>"));
assert!(req.csc_data.contains(r#"<entry name="missing-process">"#));
assert!(req.summary().contains("process_entries=2"));
assert!(req.summary().contains("process_present=1"));
assert!(req.summary().contains("process_missing=1"));
}
#[test]
fn builds_windows_registry_key_report() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<windows>
<registry-key>
<entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\TenantInfo\00000000-0000-4000-8000-000000000000" />
</registry-key>
</windows>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Windows), &reader).unwrap();
assert!(req.csc_data.contains("<custom-checks>"));
assert!(req.csc_data.contains("<registry-key>"));
assert!(
req
.csc_data
.contains(r#"<entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\TenantInfo\00000000-0000-4000-8000-000000000000">"#)
);
assert!(req.csc_data.contains("<exist>no</exist>"));
assert!(req.csc_data.contains("<value />") || req.csc_data.contains("<value></value>"));
}
#[test]
fn uses_pan_non_padded_md5_digest() {
assert_eq!(pan_md5_hex(b""), "d41d8cd98f0b24e980998ecf8427e");
assert_ne!(pan_md5_hex(b""), format!("{:x}", md5::compute(b"")));
}
#[test]
fn builds_getconfig_csc_params() {
let req = CscRequest {
auth_cookie: "cookie".to_string(),
config_digest: "config-digest".to_string(),
csc_digest: "csc-digest".to_string(),
csc_data: "<hip-report><host-id>host</host-id><device-serial-number>serial</device-serial-number></hip-report>"
.to_string(),
summary: CscBuildSummary::default(),
host_id: "host".to_string(),
serial_number: "serial".to_string(),
};
let nonce = "123";
let gp_params = gp_params(ClientOs::Mac);
let params = csc_params(&req, "alice", &gp_params, nonce);
assert_eq!(params.get("user"), Some(&"alice"));
assert_eq!(params.get("hostid"), Some(&"host"));
assert_eq!(params.get("serialno"), Some(&"serial"));
assert_eq!(params.get("portal-cc-auth-cookie"), Some(&"cookie"));
assert_eq!(params.get("config-digest"), Some(&"config-digest"));
assert_eq!(params.get("csc-digest"), Some(&"csc-digest"));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
}
#[test]
fn generated_getconfig_csc_params_include_final_digest_and_data() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks />
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = gp_params(ClientOs::Linux);
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
let params = csc_params(&req, "alice", &gp_params, "123");
assert_eq!(params.get("csc-digest"), Some(&req.csc_digest.as_str()));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
}
+1
View File
@@ -1,4 +1,5 @@
mod config;
pub(crate) mod csc;
mod prelogin;
pub use config::*;
+135 -21
View File
@@ -8,20 +8,11 @@ use xmltree::Element;
use crate::{
error::PortalError,
gp_params::GpParams,
os_profile::PreloginBrowserMode,
params::{gateway_prelogin, portal_prelogin},
utils::{base64, normalize_server, parse_gp_response, xml::ElementExt},
};
const REQUIRED_PARAMS: [&str; 8] = [
"tmp",
"clientVer",
"clientos",
"os-version",
"host-id",
"ipv6-support",
"default-browser",
"cas-support",
];
#[derive(Debug, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SamlPrelogin {
@@ -96,27 +87,64 @@ impl Prelogin {
}
}
pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> {
#[derive(Debug, Clone, Copy, Default)]
pub struct PreloginOptions {
external_browser_requested: bool,
portal_default_browser_enabled: bool,
}
impl PreloginOptions {
pub fn external_browser_requested(mut self, external_browser_requested: bool) -> Self {
self.external_browser_requested = external_browser_requested;
self
}
pub fn portal_default_browser_enabled(mut self, portal_default_browser_enabled: bool) -> Self {
self.portal_default_browser_enabled = portal_default_browser_enabled;
self
}
fn browser_mode(self, is_gateway: bool) -> PreloginBrowserMode {
if self.external_browser_requested && (!is_gateway || self.portal_default_browser_enabled) {
PreloginBrowserMode::External
} else {
PreloginBrowserMode::Embedded
}
}
}
pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptions) -> anyhow::Result<Prelogin> {
let user_agent = gp_params.user_agent();
let is_gateway = gp_params.is_gateway();
let prelogin_type = if is_gateway { "Gateway" } else { "Portal" };
info!("{} prelogin with user_agent: {}", prelogin_type, user_agent);
let portal = normalize_server(portal)?;
let path = if is_gateway { "ssl-vpn" } else { "global-protect" };
let prelogin_url = format!("{portal}/{}/prelogin.esp", path);
let mut params = gp_params.to_params();
let browser_mode = options.browser_mode(is_gateway);
let request_params = if is_gateway {
gateway_prelogin::build(gp_params.os_profile(), browser_mode)
} else {
portal_prelogin::build(gp_params.os_profile(), browser_mode)
};
let default_browser = request_param(&request_params, "default-browser").unwrap_or("");
params.insert("tmp", "tmp");
params.insert("default-browser", "1");
params.insert("cas-support", "yes");
params.retain(|k, _| REQUIRED_PARAMS.iter().any(|required_param| required_param == k));
info!(
"{} prelogin with user_agent: {}, default_browser: {}",
prelogin_type, user_agent, default_browser
);
let client = Client::try_from(gp_params)?;
let res = client.post(&prelogin_url).form(&params).send().await.map_err(|e| {
let mut request = client.post(&prelogin_url);
if !request_params.query.is_empty() {
request = request.query(&request_params.query);
}
if !request_params.body.is_empty() {
request = request.form(&request_params.body);
}
let res = request.send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
@@ -144,6 +172,14 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
Ok(prelogin)
}
fn request_param<'a>(params: &'a crate::params::RequestParams, name: &str) -> Option<&'a str> {
params
.body
.iter()
.chain(params.query.iter())
.find_map(|(key, value)| (key == name).then_some(value.as_str()))
}
fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let root = Element::parse(res_xml.as_bytes())?;
@@ -203,3 +239,81 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
Ok(Prelogin::Standard(standard_prelogin))
}
#[cfg(test)]
mod tests {
use super::PreloginOptions;
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, HostIdentity, OsProfile, PreloginBrowserMode},
params::{gateway_prelogin, portal_prelogin},
};
fn gp_params(client_os: ClientOs) -> GpParams {
let profile = OsProfile::builder(client_os)
.host_identity(HostIdentity::new(
"test-computer".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
GpParams::builder(profile).build()
}
#[test]
fn portal_prelogin_params_include_official_profile_fields() {
let gp_params = gp_params(ClientOs::Linux);
let request_params = portal_prelogin::build(gp_params.os_profile(), PreloginBrowserMode::Embedded);
let body: std::collections::HashMap<&str, &str> = request_params
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let query: std::collections::HashMap<&str, &str> = request_params
.query
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
assert_eq!(body.get("host-id"), Some(&gp_params.os_profile().host_id()));
assert_eq!(body.get("default-browser"), Some(&"-10"));
assert_eq!(body.get("cas-support"), Some(&"yes"));
assert_eq!(body.get("data"), Some(&r#"eyJjYXNfZW1iZWRkZWRfYnJvd3NlciI6InllcyJ9"#));
// Linux does not place kerberos-support in the query string.
assert_eq!(query.get("kerberos-support"), None);
}
#[test]
fn gateway_prelogin_uses_gateway_default_browser() {
let gp_params = gp_params(ClientOs::Mac);
let request_params = gateway_prelogin::build(gp_params.os_profile(), PreloginBrowserMode::Embedded);
let body: std::collections::HashMap<&str, &str> = request_params
.body
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
assert_eq!(body.get("default-browser"), Some(&"0"));
}
#[test]
fn browser_mode_uses_external_for_portal_when_requested() {
let options = PreloginOptions::default().external_browser_requested(true);
assert_eq!(options.browser_mode(false), PreloginBrowserMode::External);
}
#[test]
fn browser_mode_requires_portal_policy_for_gateway_external() {
let options = PreloginOptions::default().external_browser_requested(true);
assert_eq!(options.browser_mode(true), PreloginBrowserMode::Embedded);
let options = options.portal_default_browser_enabled(true);
assert_eq!(options.browser_mode(true), PreloginBrowserMode::External);
}
}
+48 -23
View File
@@ -4,7 +4,7 @@ use anyhow::bail;
use common::constants::GP_AUTH_BINARY;
use tokio::process::Command;
use crate::{auth::SamlAuthResult, credential::Credential};
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
use super::command_traits::CommandExt;
@@ -13,9 +13,9 @@ pub struct SamlAuthLauncher<'a> {
auth_executable: Option<&'a str>,
gateway: bool,
saml_request: Option<&'a str>,
user_agent: Option<&'a str>,
os: Option<&'a str>,
os_version: Option<&'a str>,
host_id: Option<&'a str>,
client_version: Option<&'a str>,
fix_openssl: bool,
ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")]
@@ -35,9 +35,9 @@ impl<'a> SamlAuthLauncher<'a> {
auth_executable: None,
gateway: false,
saml_request: None,
user_agent: None,
os: None,
os_version: None,
host_id: None,
client_version: None,
fix_openssl: false,
ignore_tls_errors: false,
#[cfg(feature = "webview-auth")]
@@ -66,18 +66,10 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
pub fn user_agent(mut self, user_agent: &'a str) -> Self {
self.user_agent = Some(user_agent);
self
}
pub fn os(mut self, os: &'a str) -> Self {
self.os = Some(os);
self
}
pub fn os_version(mut self, os_version: Option<&'a str>) -> Self {
self.os_version = os_version;
pub fn os_profile(mut self, profile: &'a OsProfile) -> Self {
self.os = Some(profile.client_os().as_str());
self.host_id = Some(profile.host_identity().host_id());
self.client_version = Some(profile.client_version());
self
}
@@ -133,16 +125,16 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--saml-request").arg(saml_request);
}
if let Some(user_agent) = self.user_agent {
auth_cmd.arg("--user-agent").arg(user_agent);
}
if let Some(os) = self.os {
auth_cmd.arg("--os").arg(os);
}
if let Some(os_version) = self.os_version {
auth_cmd.arg("--os-version").arg(os_version);
if let Some(host_id) = self.host_id {
auth_cmd.arg("--host-id").arg(host_id);
}
if let Some(client_version) = self.client_version {
auth_cmd.arg("--client-version").arg(client_version);
}
if self.fix_openssl {
@@ -195,3 +187,36 @@ impl<'a> SamlAuthLauncher<'a> {
Credential::try_from(auth_result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::os_profile::{ClientOs, OsProfileBuilder};
#[test]
fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
assert_eq!(launcher.os, Some("Linux"));
}
#[test]
fn os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
assert_eq!(launcher.host_id, Some(profile.host_identity().host_id()));
}
#[test]
fn os_profile_sets_client_version_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
assert_eq!(launcher.client_version, Some("6.0.0"));
}
}
+85 -8
View File
@@ -3,12 +3,18 @@ use std::env;
use anyhow::bail;
use uzers::User;
#[derive(Debug, PartialEq, Eq)]
enum RealUserLookup {
Uid(u32),
Name(String),
}
pub fn get_user_by_name(username: &str) -> anyhow::Result<User> {
uzers::get_user_by_name(username).ok_or_else(|| anyhow::anyhow!("User ({}) not found", username))
}
pub fn get_non_root_user() -> anyhow::Result<User> {
let current_user = whoami::username();
let current_user = current_username()?;
let user = if current_user == "root" {
get_real_user()?
@@ -24,16 +30,87 @@ pub fn get_non_root_user() -> anyhow::Result<User> {
}
pub fn get_current_user() -> anyhow::Result<User> {
let current_user = whoami::username();
let current_user = current_username()?;
get_user_by_name(&current_user)
}
fn current_username() -> anyhow::Result<String> {
whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))
}
fn get_real_user() -> anyhow::Result<User> {
// Read the UID from SUDO_UID or PKEXEC_UID environment variable if available.
let uid = match env::var("SUDO_UID") {
Ok(uid) => uid.parse::<u32>()?,
_ => env::var("PKEXEC_UID")?.parse::<u32>()?,
};
match real_user_lookup(|key| env::var(key).ok())? {
RealUserLookup::Uid(uid) => uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found")),
RealUserLookup::Name(name) => get_user_by_name(&name),
}
}
fn real_user_lookup(env_var: impl Fn(&str) -> Option<String>) -> anyhow::Result<RealUserLookup> {
if let Some(uid) = env_var("SUDO_UID") {
return Ok(RealUserLookup::Uid(uid.parse::<u32>()?));
}
if let Some(uid) = env_var("PKEXEC_UID") {
return Ok(RealUserLookup::Uid(uid.parse::<u32>()?));
}
if let Some(user) = env_var("DOAS_USER").filter(|user| !user.trim().is_empty()) {
return Ok(RealUserLookup::Name(user));
}
bail!("User not found")
}
#[cfg(test)]
mod tests {
use super::*;
fn lookup(vars: &[(&str, &str)]) -> anyhow::Result<RealUserLookup> {
real_user_lookup(|key| {
vars
.iter()
.find(|(name, _)| *name == key)
.map(|(_, value)| value.to_string())
})
}
#[test]
fn real_user_lookup_uses_sudo_uid() {
assert_eq!(lookup(&[("SUDO_UID", "1000")]).unwrap(), RealUserLookup::Uid(1000));
}
#[test]
fn real_user_lookup_uses_pkexec_uid() {
assert_eq!(lookup(&[("PKEXEC_UID", "1001")]).unwrap(), RealUserLookup::Uid(1001));
}
#[test]
fn real_user_lookup_uses_doas_user() {
assert_eq!(
lookup(&[("DOAS_USER", "alice")]).unwrap(),
RealUserLookup::Name("alice".to_string())
);
}
#[test]
fn real_user_lookup_prefers_uid_over_doas_user() {
assert_eq!(
lookup(&[("SUDO_UID", "1000"), ("PKEXEC_UID", "1001"), ("DOAS_USER", "alice")]).unwrap(),
RealUserLookup::Uid(1000)
);
assert_eq!(
lookup(&[("PKEXEC_UID", "1001"), ("DOAS_USER", "alice")]).unwrap(),
RealUserLookup::Uid(1001)
);
}
#[test]
fn real_user_lookup_ignores_blank_doas_user() {
assert!(lookup(&[("DOAS_USER", " ")]).is_err());
}
uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found"))
#[test]
fn real_user_lookup_errors_without_root_origin_env() {
assert!(lookup(&[]).is_err());
}
}
+43 -18
View File
@@ -3,7 +3,10 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::{gateway::Gateway, gp_params::ClientOs};
use crate::{
gateway::Gateway,
os_profile::{ClientOs, OsProfile},
};
use super::vpn_state::ConnectInfo;
@@ -36,6 +39,7 @@ pub struct ConnectArgs {
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
host_id: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
@@ -65,6 +69,7 @@ impl ConnectArgs {
os: None,
os_version: None,
client_version: None,
host_id: None,
certificate: None,
sslkey: None,
key_password: None,
@@ -110,6 +115,10 @@ impl ConnectArgs {
self.client_version.clone()
}
pub fn host_id(&self) -> Option<String> {
self.host_id.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
@@ -201,23 +210,12 @@ impl ConnectRequest {
self
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.args.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.args.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.args.os_version = os_version.into();
self
}
pub fn with_client_version(mut self, client_version: &str) -> Self {
self.args.client_version = Some(client_version.to_string());
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
self.args.os = Some(profile.client_os());
self.args.os_version = Some(profile.os_version().to_string());
self.args.client_version = Some(profile.client_version().to_string());
self.args.host_id = Some(profile.host_identity().host_id().to_string());
self.args.user_agent = Some(profile.user_agent().to_string());
self
}
@@ -314,6 +312,12 @@ mod tests {
use serde_json::json;
use super::*;
use crate::os_profile::OsProfileBuilder;
fn test_connect_info() -> ConnectInfo {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
}
#[test]
fn connect_request_serializes_allow_extend_session() {
@@ -324,4 +328,25 @@ mod tests {
assert_eq!(value["args"]["allowExtendSession"], json!(true));
}
#[test]
fn with_os_profile_sets_user_agent_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
}
#[test]
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
assert_eq!(
req.args().host_id(),
Some(profile.host_identity().host_id().to_string())
);
}
}
+15 -1
View File
@@ -1,6 +1,17 @@
use serde::{Deserialize, Serialize};
use crate::service::vpn_state::VpnState;
use crate::{os_profile::HostIdentity, service::vpn_state::VpnState};
/// The single DTO carrying all host facts gpservice ships to gpgui.
///
/// Populated by gpservice at WS connection time and sent inside `VpnEnv`.
/// gpgui stores it in a process-wide `OnceLock` and routes `AppSettings`,
/// `Constants`, and `OsProfile` construction through it.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HostInfo {
/// Host identity collected by gpservice for the runtime OS.
pub host_identity: HostIdentity,
}
/// Represents the VPN environment configuration.
/// When a client connects, the gpservice sends the current VPN environment
@@ -19,4 +30,7 @@ pub struct VpnEnv {
/// The gpauth executable path
/// Used by the client to launch gpauth for authentication
pub auth_executable: String,
/// Host identity collected by gpservice.
pub host_info: HostInfo,
}
+7 -35
View File
@@ -4,8 +4,6 @@ use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
@@ -16,9 +14,6 @@ pub struct SessionWarning {
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
@@ -30,9 +25,6 @@ impl SessionRequestArgs {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
@@ -45,21 +37,6 @@ impl SessionRequestArgs {
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
@@ -88,18 +65,6 @@ impl SessionRequestArgs {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
@@ -299,4 +264,11 @@ mod tests {
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
#[test]
fn with_user_agent_sets_session_user_agent() {
let args = SessionRequestArgs::new("cookie".to_string()).with_user_agent("agent/1.0".to_string());
assert_eq!(args.user_agent(), Some("agent/1.0".to_string()));
}
}
-108
View File
@@ -1,108 +0,0 @@
use std::sync::OnceLock;
const DEFAULT_MACOS_VERSION: &str = "13.4.0";
#[cfg(not(target_os = "linux"))]
const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS";
#[cfg(not(target_os = "windows"))]
const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro";
const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0";
const DEFAULT_MACHINE_ID: &str = "DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF";
static MACHINE_ID: OnceLock<&'static str> = OnceLock::new();
static MACOS_VERSION: OnceLock<&'static str> = OnceLock::new();
static MACOS_OS_STRING: OnceLock<String> = OnceLock::new();
static LINUX_OS_STRING: OnceLock<String> = OnceLock::new();
static WINDOWS_VERSION: OnceLock<&'static str> = OnceLock::new();
static WINDOWS_OS_STRING: OnceLock<String> = OnceLock::new();
/// On macOS, get the OS version, or fallback to default
/// On other OSes, always return default
pub fn get_macos_version() -> &'static str {
MACOS_VERSION.get_or_init(|| {
#[cfg(target_os = "macos")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_MACOS_VERSION,
v => v.to_string().leak(),
}
}
#[cfg(not(target_os = "macos"))]
DEFAULT_MACOS_VERSION
})
}
pub fn get_macos_os_string() -> &'static str {
MACOS_OS_STRING.get_or_init(|| format!("Apple Mac OS X {}", get_macos_version()))
}
/// On Linux, use the real distro name if possible
/// On other OSes, fallback to default
pub fn get_linux_os_string() -> &'static str {
LINUX_OS_STRING.get_or_init(|| {
#[cfg(target_os = "linux")]
{
format!("Linux {}", whoami::distro())
}
#[cfg(not(target_os = "linux"))]
{
format!("Linux {}", DEFAULT_LINUX_DISTRO)
}
})
}
/// On Windows, get the OS version, or fallback to default
/// On other OSes, always return default
pub fn get_windows_version() -> &'static str {
WINDOWS_VERSION.get_or_init(|| {
#[cfg(target_os = "windows")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION,
v => format!("{}.0", v).leak(),
}
}
#[cfg(not(target_os = "windows"))]
DEFAULT_WINDOWS_VERSION
})
}
/// On Windows, use the real edition if possible
/// On other OSes, fallback to default
/// The trailing space is intentional
pub fn get_windows_os_string() -> &'static str {
WINDOWS_OS_STRING.get_or_init(|| {
#[cfg(target_os = "windows")]
{
let edition = os_info::get()
.edition()
.map(|e| e.to_string())
.unwrap_or_else(|| whoami::distro());
format!("Microsoft {} , 64-bit", edition)
}
#[cfg(not(target_os = "windows"))]
{
format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO)
}
})
}
/// Get machine ID or fallback to default
pub fn get_machine_id() -> &'static str {
MACHINE_ID.get_or_init(|| {
machine_uid::get()
.map(|id| id.to_string().leak() as &'static str)
.unwrap_or(DEFAULT_MACHINE_ID)
})
}
/// Generate a UUID v5 based on machine ID and provided seeds
pub fn derive_uuid(seeds: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", get_machine_id(), seeds.join("-"));
let uuid = Uuid::new_v5(&namespace, name.as_bytes());
uuid.hyphenated().to_string()
}
-1
View File
@@ -5,7 +5,6 @@ pub mod checksum;
pub mod crypto;
pub mod endpoint;
pub mod env_utils;
pub mod host_utils;
pub mod lock_file;
pub mod openssl;
pub mod redact;
+54
View File
@@ -123,6 +123,46 @@ pub fn redact_uri(uri: &str) -> String {
url.to_string()
}
pub fn redact_form_params(params: &[(&str, &str)]) -> String {
let mut pairs = params
.iter()
.map(|(key, value)| (*key, redact_form_value(key, value)))
.collect::<Vec<_>>();
pairs.sort_by(|(left, _), (right, _)| left.cmp(right));
form_urlencoded::Serializer::new(String::new())
.extend_pairs(pairs)
.finish()
}
fn redact_form_value(key: &str, value: &str) -> String {
if value.is_empty() || is_safe_form_param(key) {
return value.to_string();
}
format!("redacted-{}", value.len())
}
fn is_safe_form_param(key: &str) -> bool {
matches!(
key,
"clientVer"
| "clientos"
| "config-digest"
| "csc-digest"
| "csc-support"
| "direct"
| "ipv6-support"
| "jnlpReady"
| "ok"
| "os-version"
| "prot"
| "swg-auth-token"
| "swg-nonce"
)
}
fn redact_query(query: Option<&str>) -> Option<String> {
let query = query?;
@@ -190,6 +230,20 @@ mod tests {
assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x");
}
#[test]
fn it_should_redact_form_params() {
let params = [
("portal-userauthcookie", "secret-cookie"),
("csc-support", "yes"),
("prelogin-cookie", ""),
];
assert_eq!(
redact_form_params(&params),
"csc-support=yes&portal-userauthcookie=redacted-13&prelogin-cookie="
);
}
#[test]
fn it_should_redact_data_uri() {
let uri = "data:text/plain;a";
+31 -8
View File
@@ -24,26 +24,49 @@ mod unix {
use anyhow::bail;
use gtk::{
EventBox,
glib::Cast,
glib::{self, Cast},
traits::{EventBoxExt, GtkWindowExt, WidgetExt},
};
use log::info;
use tauri::WebviewWindow;
use tokio::process::Command;
/// Wrapper to mark a non-Send closure as Send for dispatch to the GTK main thread.
///
/// SAFETY: The caller must ensure the closure is only executed on the GTK main
/// thread. This is guaranteed by `glib::MainContext::default().invoke()`.
struct SendFn(Box<dyn FnOnce()>);
unsafe impl Send for SendFn {}
impl SendFn {
fn invoke(self) {
(self.0)();
}
}
pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland {
let gtk_win = win.gtk_window()?;
if let Some(header) = gtk_win.titlebar() {
let _ = header.downcast::<EventBox>().map(|event_box| {
event_box.set_above_child(false);
});
}
gtk_win.hide();
gtk_win.show_all();
// GTK operations must run on the main thread. When this function is called
// from a background thread (e.g., rspc handler on a tokio worker), calling
// GTK widget methods directly causes crashes in GTK's CSS subsystem
// (gtk_css_value_inherit_free assertion failure). Dispatch to the main
// thread via glib::MainContext to ensure thread safety.
let send_fn = SendFn(Box::new(move || {
if let Some(header) = gtk_win.titlebar() {
let _ = header.downcast::<EventBox>().map(|event_box| {
event_box.set_above_child(false);
});
}
gtk_win.hide();
gtk_win.show_all();
}));
glib::MainContext::default().invoke(move || send_fn.invoke());
} else {
if !win.is_visible()? {
win.show()?;
+4 -4
View File
@@ -46,10 +46,10 @@ impl ElementExt for Element {
}
for child in &self.children {
if let Some(element) = child.as_element() {
if let Some(found) = element.descendant(name) {
return Some(found);
}
if let Some(element) = child.as_element()
&& let Some(found) = element.descendant(name)
{
return Some(found);
}
}