mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat: generate HIP reports through OpenConnect callbacks
This commit is contained in:
46 files changed
+2511
-1184
No files matched your search
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"] }
|
||||
common = { path = "../common" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -20,8 +23,39 @@ impl HostIdentity {
|
||||
Self::collect_with_host_id(None)
|
||||
}
|
||||
|
||||
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
|
||||
Self::collect_with_host_id_and_control(None, control)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
|
||||
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
|
||||
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
|
||||
Ok(identity) => identity,
|
||||
Err(error) => {
|
||||
log::warn!("Host identity collection was unavailable: {error}");
|
||||
Self::default_with_host_id(host_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort convenience callers retain the established derived identity
|
||||
/// when native collection is unavailable. Controlled HIP callers get errors.
|
||||
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
|
||||
Self::from_parts(
|
||||
fallback_hostname(),
|
||||
resolve_host_id(host_id, fallback_host_id),
|
||||
String::new(),
|
||||
primary_mac_colon().unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id_and_control(
|
||||
host_id: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<Self> {
|
||||
control.check()?;
|
||||
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -29,7 +63,8 @@ impl HostIdentity {
|
||||
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 {
|
||||
/// Construct a host identity from an already collected or negotiated snapshot.
|
||||
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
let host_id = non_empty(host_id, fallback_host_id());
|
||||
let computer = non_empty(computer, fallback_hostname());
|
||||
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
|
||||
@@ -163,12 +198,12 @@ fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> 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,
|
||||
};
|
||||
use crate::process::collection::{CollectionControl, CollectorCommands};
|
||||
use std::io;
|
||||
|
||||
pub(super) struct RuntimeNativeHostIdentity;
|
||||
|
||||
@@ -177,74 +212,80 @@ mod platform {
|
||||
ClientOs::Mac
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<NativeHostIdentitySnapshot> {
|
||||
let commands = CollectorCommands::new(control);
|
||||
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
|
||||
control.check()?;
|
||||
let host_id = resolve_host_id(host_id_override, || {
|
||||
native_mac
|
||||
.clone()
|
||||
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
|
||||
});
|
||||
NativeHostIdentitySnapshot {
|
||||
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
|
||||
let serial_number = collect_macos_serial_number(&commands)?;
|
||||
control.check()?;
|
||||
Ok(NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
|
||||
serial_number: collect_macos_serial_number(),
|
||||
computer,
|
||||
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;
|
||||
}
|
||||
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
|
||||
Ok(
|
||||
commands
|
||||
.run(program, args)?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok()),
|
||||
)
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
for name in ["ComputerName", "LocalHostName"] {
|
||||
if let Some(value) = output(commands, "scutil", &["--get", name])?
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
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;
|
||||
{
|
||||
return Ok(Some(value));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
|
||||
for name in ["Wi-Fi", "AirPort"] {
|
||||
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
|
||||
return Ok(Some(mac));
|
||||
}
|
||||
}
|
||||
}
|
||||
macos_system_profiler_wifi_mac(commands)
|
||||
}
|
||||
|
||||
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
|
||||
let mut in_port = false;
|
||||
for line in stdout.lines() {
|
||||
if let Some(port) = line.strip_prefix("Hardware Port: ") {
|
||||
in_port = port == port_name;
|
||||
in_port = port == name;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn macos_system_profiler_wifi_mac() -> 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()?;
|
||||
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut in_wifi = false;
|
||||
for line in stdout.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -252,29 +293,24 @@ mod platform {
|
||||
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
return Ok(normalize_mac_colon(mac));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
Ok(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| {
|
||||
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(stdout.lines().find_map(|line| {
|
||||
line
|
||||
.split_once("IOPlatformSerialNumber")
|
||||
.and_then(|(_, value)| value.split_once('='))
|
||||
.map(|(_, value)| value.trim().trim_matches('"').to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +327,17 @@ mod platform {
|
||||
ClientOs::Windows
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let host_id = resolve_host_id(host_id_override, Self::host_id);
|
||||
NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
@@ -373,7 +419,17 @@ mod platform {
|
||||
ClientOs::Linux
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
|
||||
debug!("Runtime host-id source: explicit override ({})", host_id);
|
||||
}
|
||||
@@ -476,6 +532,15 @@ mod platform {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_identity_collection_propagates_cancellation() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = HostIdentity::collect_with_control(&control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_produces_non_empty_identity() {
|
||||
let identity = HostIdentity::collect();
|
||||
@@ -528,7 +593,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn native_snapshot_uses_host_id_as_derivation_seed() {
|
||||
let native = RuntimeNativeHostIdentity::collect(None);
|
||||
let native =
|
||||
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
|
||||
|
||||
assert!(!native.host_id.is_empty());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ mod serial_number;
|
||||
|
||||
pub use host_identity::HostIdentity;
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -366,6 +369,7 @@ impl OsProfile {
|
||||
pub struct OsProfileBuilder {
|
||||
client_os: ClientOs,
|
||||
client_version: Option<String>,
|
||||
os_version_override: Option<String>,
|
||||
computer_name_override: Option<String>,
|
||||
host_id_override: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
@@ -377,6 +381,7 @@ impl OsProfileBuilder {
|
||||
Self {
|
||||
client_os,
|
||||
client_version: None,
|
||||
os_version_override: None,
|
||||
computer_name_override: None,
|
||||
host_id_override: None,
|
||||
host_identity: None,
|
||||
@@ -394,6 +399,13 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Preserve an explicitly negotiated operating system version.
|
||||
pub fn os_version(mut self, version: impl Into<String>) -> Self {
|
||||
let version = version.into();
|
||||
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
|
||||
self
|
||||
}
|
||||
|
||||
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
|
||||
self.host_identity = Some(identity);
|
||||
self
|
||||
@@ -411,31 +423,67 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Build a best-effort profile with a bounded native collection budget.
|
||||
/// Use `build_with_control` when interruption or timeout must be reported.
|
||||
pub fn build(self) -> OsProfile {
|
||||
match self
|
||||
.clone()
|
||||
.build_with_control(&CollectionBudget::new(Duration::from_secs(60)))
|
||||
{
|
||||
Ok(profile) => profile,
|
||||
Err(error) => {
|
||||
log::warn!("OS profile collection was unavailable: {error}");
|
||||
let identity = self
|
||||
.host_identity
|
||||
.clone()
|
||||
.unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref()));
|
||||
let (os_version, software_version) = match self.client_os {
|
||||
ClientOs::Mac => (
|
||||
format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
|
||||
DEFAULT_MACOS_VERSION.into(),
|
||||
),
|
||||
os => (target::os_version(os), target::software_version(os)),
|
||||
};
|
||||
self.finish(identity, os_version, software_version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result<OsProfile> {
|
||||
control.check()?;
|
||||
let host_identity = match (&self.host_identity, &self.host_id_override) {
|
||||
(Some(identity), _) => identity.clone(),
|
||||
(None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?,
|
||||
};
|
||||
let (os_version, software_version) = if self.client_os == ClientOs::Mac {
|
||||
let version = macos_version_with_control(control)?;
|
||||
(format!("Apple Mac OS X {version}"), version)
|
||||
} else {
|
||||
(
|
||||
target::os_version(self.client_os),
|
||||
target::software_version(self.client_os),
|
||||
)
|
||||
};
|
||||
control.check()?;
|
||||
Ok(self.finish(host_identity, os_version, software_version))
|
||||
}
|
||||
|
||||
fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile {
|
||||
let client_version = self
|
||||
.client_version
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().to_string());
|
||||
|
||||
let host_identity = match (self.host_identity, self.host_id_override) {
|
||||
(Some(identity), _) => identity,
|
||||
(None, host_id) => HostIdentity::collect_with_host_id(host_id.as_deref()),
|
||||
};
|
||||
.filter(|version| !version.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().into());
|
||||
let profile_identity =
|
||||
ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override);
|
||||
let os_version = target::os_version(self.client_os);
|
||||
let software_version = target::software_version(self.client_os);
|
||||
let os_vendor = target::os_vendor(self.client_os);
|
||||
|
||||
let os_version = self.os_version_override.unwrap_or(default_os_version);
|
||||
let user_agent = self
|
||||
.user_agent
|
||||
.unwrap_or_else(|| format!("{}/{} ({})", GP_USER_AGENT, client_version, os_version));
|
||||
|
||||
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
|
||||
OsProfile {
|
||||
client_os: self.client_os,
|
||||
os_version,
|
||||
software_version,
|
||||
os_vendor,
|
||||
os_vendor: target::os_vendor(self.client_os),
|
||||
client_version,
|
||||
host_identity,
|
||||
profile_identity,
|
||||
@@ -500,14 +548,28 @@ fn runtime_distro_or(fallback: &str) -> String {
|
||||
}
|
||||
|
||||
fn macos_version() -> String {
|
||||
if runtime_client_os() == ClientOs::Mac {
|
||||
match os_info::get().version() {
|
||||
os_info::Version::Unknown => DEFAULT_MACOS_VERSION.to_string(),
|
||||
v => v.to_string(),
|
||||
}
|
||||
} else {
|
||||
DEFAULT_MACOS_VERSION.to_string()
|
||||
macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| {
|
||||
log::warn!("Operating system version collection was unavailable: {error}");
|
||||
DEFAULT_MACOS_VERSION.into()
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result<String> {
|
||||
control.check()?;
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let commands = crate::process::collection::CollectorCommands::new(control);
|
||||
let version = commands
|
||||
.run("sw_vers", &["-productVersion"])?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok())
|
||||
.map(|version| version.trim().to_string())
|
||||
.filter(|version| !version.is_empty());
|
||||
control.check()?;
|
||||
Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into()))
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Ok(DEFAULT_MACOS_VERSION.into())
|
||||
}
|
||||
|
||||
fn macos_os_string() -> String {
|
||||
@@ -691,6 +753,37 @@ mod target_identity {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
|
||||
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.build_with_control(&cancelled)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let expired = CollectionBudget::new(Duration::ZERO);
|
||||
let error = OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build_with_control(&expired)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.host_identity(identity)
|
||||
.client_version("6.3.3")
|
||||
.os_version("negotiated-system-version")
|
||||
.build();
|
||||
assert_eq!(profile.os_version(), "negotiated-system-version");
|
||||
assert!(profile.user_agent().contains("negotiated-system-version"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csc_support_defaults_match_official_profiles() {
|
||||
assert!(!ClientOs::Linux.default_csc_support());
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::{self, Read},
|
||||
os::unix::{
|
||||
fs::{MetadataExt, PermissionsExt},
|
||||
process::CommandExt,
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
/// Invocation control borrowed by collection; interruption must never be treated
|
||||
/// as an unavailable optional product.
|
||||
pub trait CollectionControl {
|
||||
fn check(&self) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
self()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CollectionBudget {
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl CollectionBudget {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
deadline: Instant::now() + timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CollectionControl for CollectionBudget {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
if Instant::now() >= self.deadline {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Device information collection timed out",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
|
||||
const TOOL_DIRECTORIES: &[&str] = &[
|
||||
"/usr/bin",
|
||||
"/usr/sbin",
|
||||
"/bin",
|
||||
"/sbin",
|
||||
"/usr/local/bin",
|
||||
"/usr/local/sbin",
|
||||
];
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
TOOL_DIRECTORIES
|
||||
.iter()
|
||||
.find_map(|directory| resolve_executable(&Path::new(directory).join(name), uzers::get_effective_uid() == 0))
|
||||
}
|
||||
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = self.resolve(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let home = if uzers::get_effective_uid() == 0 {
|
||||
if cfg!(target_os = "macos") {
|
||||
"/var/root"
|
||||
} else {
|
||||
"/root"
|
||||
}
|
||||
} else {
|
||||
"/"
|
||||
};
|
||||
let mut command = Command::new(path);
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
|
||||
.env("LC_ALL", "C")
|
||||
.env("HOME", home)
|
||||
.current_dir("/")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.process_group(0);
|
||||
let child = match command.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut child = CollectionChild(child);
|
||||
let mut stdout = child.0.stdout.take().expect("collector stdout was piped");
|
||||
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
fcntl(
|
||||
&stdout,
|
||||
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
let mut eof = false;
|
||||
let mut status = None;
|
||||
loop {
|
||||
self.control.check()?;
|
||||
if !eof {
|
||||
match stdout.read(&mut buffer) {
|
||||
Ok(0) => eof = true,
|
||||
Ok(length) => {
|
||||
if output.len() + length > COMMAND_OUTPUT_LIMIT {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Device information collector output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
continue;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if status.is_none() {
|
||||
status = child.0.try_wait()?;
|
||||
}
|
||||
if eof && let Some(status) = status {
|
||||
return Ok(Some(Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
}));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
|
||||
let resolved = fs::canonicalize(path).ok()?;
|
||||
let metadata = fs::metadata(&resolved).ok()?;
|
||||
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Known command directories, canonicalized and restricted to trusted root
|
||||
/// ownership when used for privileged execution.
|
||||
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
|
||||
let directories = TOOL_DIRECTORIES.iter().filter_map(|directory| {
|
||||
let resolved = fs::canonicalize(directory).ok()?;
|
||||
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
|
||||
}
|
||||
|
||||
fn root_owned_path(path: &Path) -> bool {
|
||||
path.ancestors().all(|part| {
|
||||
fs::symlink_metadata(part).is_ok_and(|metadata| {
|
||||
metadata.uid() == 0 && metadata.permissions().mode() & 0o022 == 0 && !metadata.file_type().is_symlink()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
struct CollectionChild(Child);
|
||||
|
||||
impl Drop for CollectionChild {
|
||||
fn drop(&mut self) {
|
||||
// Also stop descendants retaining the pipe after the direct child exits.
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn root_command_path_contains_only_trusted_canonical_directories() {
|
||||
let path = command_path(true).unwrap();
|
||||
let directories: Vec<_> = std::env::split_paths(&path).collect();
|
||||
assert!(!directories.is_empty());
|
||||
for directory in directories {
|
||||
assert!(directory.is_dir());
|
||||
assert!(root_owned_path(&directory));
|
||||
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_resolution_returns_target_not_mutable_symlink() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let link = dir.path().join("tool");
|
||||
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
|
||||
let resolved = resolve_executable(&link, false).unwrap();
|
||||
fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
|
||||
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
|
||||
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_running_collector() {
|
||||
let started = Instant::now();
|
||||
let control = || {
|
||||
if started.elapsed() >= Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = CollectorCommands::new(&control)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_has_private_environment_and_cwd() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let output = CollectorCommands::new(&budget)
|
||||
.run_path(
|
||||
Path::new("/bin/sh"),
|
||||
&[
|
||||
"-c",
|
||||
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deadline_stops_collector_instead_of_hanging() {
|
||||
let budget = CollectionBudget::new(Duration::from_millis(100));
|
||||
let started = Instant::now();
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_output_is_bounded() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_is_not_an_optional_missing_product() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,5 @@ pub mod auth_launcher;
|
||||
pub mod gui_launcher;
|
||||
pub mod service_launcher;
|
||||
pub mod users;
|
||||
|
||||
pub mod collection;
|
||||
Reference in new issue
Block a user