mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 22:46:14 -05:00
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:
92 files changed
+9847
-2868
No files matched your search
@@ -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(¶ms).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(¶ms));
|
||||
|
||||
let res = client.post(&url).form(¶ms).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(¶ms)
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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,4 +1,5 @@
|
||||
mod config;
|
||||
pub(crate) mod csc;
|
||||
mod prelogin;
|
||||
|
||||
pub use config::*;
|
||||
|
||||
@@ -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(¶ms).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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user