fix: improve CSC criteria support

This commit is contained in:
Kevin Yue committed 2026-05-11 21:38:35 +08:00
1 parent 1efb9a86e6
commit 5974a60b59
10 files changed
+460 -106

No files matched your search

+12 -12
View File
@@ -262,6 +262,18 @@ impl From<PasswordCredential> for Credential {
}
}
impl From<&AuthCookieCredential> for Credential {
fn from(value: &AuthCookieCredential) -> Self {
Self::AuthCookie(value.clone())
}
}
impl From<&CachedCredential> for Credential {
fn from(value: &CachedCredential) -> Self {
Self::Cached(value.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -300,15 +312,3 @@ mod tests {
assert_eq!(params.get("token"), Some(&"cas-token"));
}
}
impl From<&AuthCookieCredential> for Credential {
fn from(value: &AuthCookieCredential) -> Self {
Self::AuthCookie(value.clone())
}
}
impl From<&CachedCredential> for Credential {
fn from(value: &CachedCredential) -> Self {
Self::Cached(value.clone())
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ 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 {
+22
View File
@@ -58,6 +58,7 @@ pub struct GpParams {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
// Used for MFA
input_str: Option<String>,
otp: Option<String>,
@@ -100,6 +101,13 @@ impl GpParams {
self.client_version.as_deref()
}
pub fn csc_preference_override(&self, domain: &str, key: &str) -> Option<&str> {
self
.csc_preference_overrides
.get(&csc_preference_key(domain, key))
.map(String::as_str)
}
pub fn set_input_str(&mut self, input_str: &str) {
self.input_str = Some(input_str.to_string());
}
@@ -152,6 +160,7 @@ pub struct GpParamsBuilder {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
}
impl GpParamsBuilder {
@@ -169,6 +178,7 @@ impl GpParamsBuilder {
certificate: Default::default(),
sslkey: Default::default(),
key_password: Default::default(),
csc_preference_overrides: Default::default(),
}
}
@@ -222,6 +232,13 @@ impl GpParamsBuilder {
self
}
pub fn csc_preference_override(&mut self, domain: &str, key: &str, value: &str) -> &mut Self {
self
.csc_preference_overrides
.insert(csc_preference_key(domain, key), value.to_string());
self
}
pub fn build(&self) -> GpParams {
GpParams {
is_gateway: self.is_gateway,
@@ -234,12 +251,17 @@ impl GpParamsBuilder {
certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(),
csc_preference_overrides: self.csc_preference_overrides.clone(),
input_str: Default::default(),
otp: Default::default(),
}
}
}
fn csc_preference_key(domain: &str, key: &str) -> String {
format!("{domain}:{key}")
}
impl Default for GpParamsBuilder {
fn default() -> Self {
Self::new()
+20 -18
View File
@@ -203,6 +203,7 @@ async fn retrieve_csc_config(
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| {
@@ -252,7 +253,7 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
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(|| {
@@ -313,23 +314,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),
}
}
}
+314 -58
View File
@@ -1,5 +1,6 @@
use std::{
collections::HashMap,
fmt::Write,
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
@@ -19,20 +20,62 @@ pub(super) struct CscRequest {
pub(super) config_digest: String,
pub(super) csc_digest: String,
pub(super) csc_data: String,
summary: CscBuildSummary,
host_id: String,
serial_number: String,
}
pub(super) trait PreferenceReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<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,
)
}
}
struct SystemPreferenceReader;
#[derive(Default)]
struct CscBuildSummary {
plist_entries: usize,
plist_present: usize,
plist_missing: usize,
process_entries: usize,
process_present: usize,
process_missing: usize,
}
impl PreferenceReader for SystemPreferenceReader {
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(super) fn swg_nonce() -> String {
@@ -49,7 +92,7 @@ pub(super) fn is_config_criteria(root: &Element) -> bool {
}
pub(super) fn build_csc_request(root: &Element, username: &str, gp_params: &GpParams) -> anyhow::Result<CscRequest> {
let reader = SystemPreferenceReader;
let reader = SystemCscDataReader;
build_csc_request_with_reader(root, username, gp_params, &reader)
}
@@ -57,7 +100,7 @@ pub(super) fn build_csc_request_with_reader(
root: &Element,
username: &str,
gp_params: &GpParams,
reader: &dyn PreferenceReader,
reader: &dyn CscDataReader,
) -> anyhow::Result<CscRequest> {
let auth_cookie = root
.descendant_text("portal-csc-auth-cookie")
@@ -67,17 +110,21 @@ pub(super) fn build_csc_request_with_reader(
let host_id = collect_host_id(gp_params);
let serial_number = collect_serial_number();
let mut summary = CscBuildSummary::default();
let csc_data = build_csc_data(
root,
&auth_cookie,
username,
gp_params,
&host_id,
&serial_number,
DIGEST_PLACEHOLDER,
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 = format!("{:x}", md5::compute(csc_data.as_bytes()));
let csc_digest = pan_md5_hex(csc_data.as_bytes());
let csc_data = csc_data.replace(DIGEST_PLACEHOLDER, &csc_digest);
Ok(CscRequest {
@@ -85,6 +132,7 @@ pub(super) fn build_csc_request_with_reader(
config_digest,
csc_digest,
csc_data,
summary,
host_id,
serial_number,
})
@@ -115,26 +163,24 @@ pub(super) fn csc_params<'a>(
}
fn build_csc_data(
criteria: &Element,
auth_cookie: &str,
username: &str,
gp_params: &GpParams,
host_id: &str,
serial_number: &str,
csc_digest: &str,
reader: &dyn PreferenceReader,
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", auth_cookie);
push_text(&mut root, "user-name", &urlencoding::encode(username));
push_text(&mut root, "client-os", &client_os_report_value(gp_params));
push_text(&mut root, "host-id", host_id);
push_text(&mut root, "device-serial-number", serial_number);
push_text(&mut root, "csc-digest", csc_digest);
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")));
root
.children
.push(XMLNode::Element(build_custom_checks(criteria, gp_params, reader)));
root.children.push(XMLNode::Element(build_custom_checks(
input.criteria,
input.gp_params,
reader,
summary,
)));
let mut bytes = Vec::new();
root.write_with_config(
@@ -147,26 +193,49 @@ fn build_csc_data(
String::from_utf8(bytes).map_err(Into::into)
}
fn build_custom_checks(criteria: &Element, gp_params: &GpParams, reader: &dyn PreferenceReader) -> Element {
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 let Some(mac_os) = requested_checks.child("mac-os") {
if let Some(plist) = mac_os.child("plist") {
custom_checks.children.push(XMLNode::Element(build_plist_checks(
plist,
gp_params.client_os() == "Mac",
reader,
)));
}
if gp_params.client_os() == "Mac"
&& 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, gp_params, reader, summary)));
}
if gp_params.client_os() == "Linux"
&& 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,
)));
}
custom_checks
}
fn build_plist_checks(plist: &Element, can_read: bool, reader: &dyn PreferenceReader) -> Element {
fn build_plist_checks(
plist: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("plist");
for entry in plist.children("entry") {
@@ -178,15 +247,17 @@ fn build_plist_checks(plist: &Element, can_read: bool, reader: &dyn PreferenceRe
let values: Vec<_> = keys
.iter()
.map(|key| {
let value = if can_read {
reader.read_preference(domain, key)
} else {
None
};
let value = gp_params
.csc_preference_override(domain, key)
.map(str::to_string)
.or_else(|| 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", "");
@@ -207,6 +278,32 @@ fn build_plist_checks(plist: &Element, can_read: bool, reader: &dyn PreferenceRe
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")
@@ -225,6 +322,37 @@ fn plist_entry_keys(entry: &Element) -> Vec<String> {
}
}
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 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 collect_host_id(gp_params: &GpParams) -> String {
match gp_params.client_os() {
"Mac" => netdev::get_default_interface()
@@ -298,6 +426,30 @@ fn read_macos_preference(domain: &str, key: &str) -> Option<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()
@@ -320,14 +472,19 @@ mod tests {
use super::*;
use crate::gp_params::{ClientOs, GpParams};
struct TestPreferenceReader {
struct TestCscDataReader {
values: HashMap<String, String>,
processes: Vec<String>,
}
impl PreferenceReader for TestPreferenceReader {
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 {
@@ -354,8 +511,8 @@ mod tests {
<custom-checks>
<mac-os>
<plist>
<entry name="com.paloaltonetworks.GlobalProtect.settings">
<key><member>HipID</member></key>
<entry name="com.example.settings">
<key><member>ExampleKey</member></key>
</entry>
</plist>
</mac-os>
@@ -363,11 +520,12 @@ mod tests {
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestPreferenceReader {
let reader = TestCscDataReader {
values: HashMap::from([(
"com.paloaltonetworks.GlobalProtect.settings:HipID".to_string(),
"MicroStrategyGP".to_string(),
"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();
@@ -376,7 +534,7 @@ mod tests {
assert!(req.csc_data.contains("<user-name>alice%40example.com</user-name>"));
assert!(req.csc_data.contains("<client-os>Apple+Mac+OS+X+26.4.1</client-os>"));
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>MicroStrategyGP</value>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
assert!(
req
.csc_data
@@ -399,7 +557,10 @@ mod tests {
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestPreferenceReader { values: HashMap::new() };
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
@@ -408,7 +569,37 @@ mod tests {
}
#[test]
fn unsupported_client_os_reports_macos_plist_missing() {
fn macos_plist_override_works_without_native_preference() {
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::new(),
processes: Vec::new(),
};
let gp_params = GpParams::builder()
.client_os(ClientOs::Mac)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.csc_preference_override("com.example.settings", "ExampleKey", "ExampleValue")
.build();
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
}
#[test]
fn unsupported_client_os_ignores_macos_plist_branch() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
@@ -421,16 +612,54 @@ mod tests {
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestPreferenceReader {
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("<exist>no</exist>"));
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 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 {
@@ -439,6 +668,7 @@ mod tests {
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(),
};
@@ -456,4 +686,30 @@ mod tests {
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));
}
}
+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);
}
}