feat: generate HIP reports through OpenConnect callbacks

This commit is contained in:
Kevin Yue committed 2026-10-02 01:38:20 +08:00
1 parent 05814e9da7
commit b750cfbf16
46 files changed
+2511 -1184

No files matched your search

+1
View File
@@ -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
+127 -61
View File
@@ -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());
}
+114 -21
View File
@@ -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());
+296
View File
@@ -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);
}
}
+2
View File
@@ -8,3 +8,5 @@ pub mod auth_launcher;
pub mod gui_launcher;
pub mod service_launcher;
pub mod users;
pub mod collection;
-1
View File
@@ -10,7 +10,6 @@ gpapi = { path = "../gpapi" }
anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
log.workspace = true
netdev.workspace = true
serde.workspace = true
serde_json.workspace = true
+167 -169
View File
@@ -1,10 +1,11 @@
use anyhow::{bail, ensure};
use askama::Template;
use gpapi::os_profile::{ClientOs, OsProfile};
use log::debug;
use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use std::{io, time::Duration};
use gpapi::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
use xmltree::Element;
#[cfg(target_os = "macos")]
@@ -82,49 +83,62 @@ fn unique_child<'a>(parent: &'a Element, name: &str) -> anyhow::Result<&'a Eleme
Ok(child)
}
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
"md5-sum",
"user-name",
"domain",
"host-name",
"host-id",
"ip-address",
"ipv6-address",
"generate-time",
];
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
/// Refresh only session and current-host fields in a saved HIP report.
/// User-edited categories, products, and network-interface entries remain intact.
/// Refresh current identity/session values without running product collectors.
pub fn refresh_edited_report(edited_xml: &str, input: &ReportInput) -> anyhow::Result<String> {
let budget = CollectionBudget::new(Duration::from_secs(60));
refresh_edited_report_with_control(edited_xml, input, &budget)
}
pub fn refresh_edited_report_with_control(
edited_xml: &str,
input: &ReportInput,
control: &dyn CollectionControl,
) -> anyhow::Result<String> {
control.check()?;
let mut edited = validate_edited_report(edited_xml)?;
let current = validate_edited_report(&generate_report(input)?)?;
for field in CURRENT_TOP_LEVEL_FIELDS {
copy_field(&mut edited, &current, field)?;
let cookie_params = cookie_params(input);
let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity();
control.check()?;
let domain = format!("{}.internal", identity.domain);
let generate_time = get_current_time_components().0;
for (name, value) in [
("md5-sum", input.context.md5()),
("user-name", report_user_name(input, &cookie_params)),
("domain", domain.as_str()),
("host-name", identity.host_name.as_str()),
("host-id", identity.host_id.as_str()),
("ip-address", identity.default_ipv4()),
("ipv6-address", identity.default_ipv6()),
("generate-time", generate_time.as_str()),
] {
set_field(&mut edited, name, value)?;
}
let edited_host = host_info_mut(&mut edited)?;
let current_host = host_info(&current)?;
for field in CURRENT_HOST_INFO_FIELDS {
copy_field(edited_host, current_host, field)?;
let host_info = host_info_mut(&mut edited)?;
for (name, value) in [
("client-version", input.profile.client_version()),
("os", identity.os_version.as_str()),
("os-vendor", identity.os_vendor.as_str()),
("domain", domain.as_str()),
("host-name", identity.host_name.as_str()),
("host-id", identity.host_id.as_str()),
] {
set_field(host_info, name, value)?;
}
let refreshed = write_xml(&edited)?;
validate_edited_report(&refreshed)?;
control.check()?;
Ok(refreshed)
}
fn copy_field(target: &mut Element, source: &Element, name: &str) -> anyhow::Result<()> {
let value = unique_child(source, name)?.children.clone();
fn set_field(target: &mut Element, name: &str, value: &str) -> anyhow::Result<()> {
let field = target
.get_mut_child(name)
.ok_or_else(|| anyhow::anyhow!("HIP report is missing <{name}>"))?;
field.children = value;
field.children = vec![xmltree::XMLNode::Text(value.to_owned())];
Ok(())
}
#[cfg(test)]
fn host_info(root: &Element) -> anyhow::Result<&Element> {
unique_child(root, "categories")?
.children
@@ -194,24 +208,39 @@ pub struct ReportInput {
/// Generate the same XML report used by `gpclient hip`.
pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
let cookie_params: HashMap<String, String> = serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default();
let budget = CollectionBudget::new(Duration::from_secs(60));
generate_report_with_control(input, &budget)
}
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
control.check()?;
let cookie_params = cookie_params(input);
let (generate_time, day, month, year) = get_current_time_components();
let user_name = match input.context {
ReportContext::Preview => "[available after connection]",
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
};
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect();
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?;
let template = HipReportTemplate {
client_version: input.profile.client_version(),
generate_time,
day,
month,
year,
user_name,
user_name: report_user_name(input, &cookie_params),
host_info,
md5: input.context.md5(),
};
format_xml(&template.render()?)
let report = format_xml(&template.render()?)?;
control.check()?;
Ok(report)
}
fn cookie_params(input: &ReportInput) -> HashMap<String, String> {
serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default()
}
fn report_user_name<'a>(input: &ReportInput, cookie_params: &'a HashMap<String, String>) -> &'a str {
match input.context {
ReportContext::Preview => "[available after connection]",
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
}
}
#[derive(Template)]
@@ -397,7 +426,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
/// Single entry point for collecting host info — dispatches per-OS
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
fn collect(&self) -> HostInfo {
fn collect_identity(&self) -> HostInfo {
let runtime_iface = self.collect_network_interface();
let primary = self.adapt_primary_interface(&runtime_iface);
@@ -412,10 +441,10 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
software_version: self.profile.software_version().to_string(),
domain: self.domain_for_profile(),
network_interfaces: interfaces,
defender: self.defender_for_profile(),
clamav: self.clamav_for_profile(),
sentinel: self.sentinel_for_profile(),
ufw: self.ufw_for_profile(),
defender: None,
clamav: None,
sentinel: None,
ufw: None,
}
}
@@ -463,102 +492,81 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
}
}
fn defender_for_profile(&self) -> Option<DefenderInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_microsoft_defender_blocking(),
ClientOs::Mac | ClientOs::Windows => None,
fn collect(&self, control: &dyn CollectionControl) -> io::Result<HostInfo> {
control.check()?;
let mut info = self.collect_identity();
control.check()?;
let commands = CollectorCommands::new(control);
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
info.defender = detect_microsoft_defender(&commands)?;
info.clamav = detect_clamav(&commands)?;
info.ufw = detect_ufw(&commands)?;
}
}
fn clamav_for_profile(&self) -> Option<ClamAvInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_clamav(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
fn ufw_for_profile(&self) -> Option<UfwInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_ufw(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
fn sentinel_for_profile(&self) -> Option<SentinelInfo> {
#[cfg(target_os = "macos")]
if self.profile.client_os() == ClientOs::Mac && self.profile.is_native() {
return sentinel_macos::detect();
info.sentinel = sentinel_macos::detect(&commands)?;
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
return sentinel_unix::detect();
info.sentinel = sentinel_unix::detect(&commands)?;
}
None
control.check()?;
Ok(info)
}
}
fn detect_clamav() -> Option<ClamAvInfo> {
let version_out = Command::new("clamscan").arg("--version").output().ok()?;
if !version_out.status.success() {
debug!("clamscan not found or failed");
return None;
}
let version_str = String::from_utf8(version_out.stdout).ok()?;
let (version, definitions_version) = parse_clamav_version(&version_str)?;
let rtp_out = Command::new("systemctl")
.args(["is-active", "clamav-onaccess.service"])
.output()
.ok()?;
let real_time_protection = rtp_out.status.success();
Some(ClamAvInfo {
fn detect_clamav(commands: &CollectorCommands<'_>) -> io::Result<Option<ClamAvInfo>> {
let Some(version_str) = command_text(commands, "clamscan", &["--version"])? else {
return Ok(None);
};
let Some((version, definitions_version)) = parse_clamav_version(&version_str) else {
return Ok(None);
};
let real_time_protection = commands
.run("systemctl", &["is-active", "clamav-onaccess.service"])?
.is_some_and(|output| output.status.success());
Ok(Some(ClamAvInfo {
version,
definitions_version,
real_time_protection,
})
}))
}
fn detect_ufw() -> Option<UfwInfo> {
let version_out = Command::new("ufw").arg("version").output().ok()?;
if !version_out.status.success() {
debug!("ufw not found or failed");
return None;
}
let version_str = String::from_utf8(version_out.stdout).ok()?;
let version = parse_ufw_version(&version_str)?;
let is_root = uzers::get_effective_uid() == 0;
let status_out = ufw_status_command(is_root).output().ok()?;
if !status_out.status.success() {
if is_root {
log::warn!("ufw status failed while running as root");
} else {
log::warn!("sudo -n ufw status failed. You may need to configure sudoers to allow execution without a password.");
}
return None;
}
let status_str = String::from_utf8(status_out.stdout).ok()?;
let is_enabled = parse_ufw_status(&status_str)?;
Some(UfwInfo { version, is_enabled })
}
fn ufw_status_command(is_root: bool) -> Command {
let mut command = if is_root {
Command::new("ufw")
} else {
let mut command = Command::new("sudo");
command.args(["-n", "ufw"]);
command
fn detect_ufw(commands: &CollectorCommands<'_>) -> io::Result<Option<UfwInfo>> {
let Some(version_str) = command_text(commands, "ufw", &["version"])? else {
return Ok(None);
};
let Some(version) = parse_ufw_version(&version_str) else {
return Ok(None);
};
let Some(ufw) = commands.resolve("ufw") else {
return Ok(None);
};
let output = if uzers::get_effective_uid() == 0 {
commands.run_path(&ufw, &["status"])?
} else {
commands.run("sudo", &["-n", &ufw.to_string_lossy(), "status"])?
};
let Some(output) = output.filter(|output| output.status.success()) else {
return Ok(None);
};
let Some(is_enabled) = String::from_utf8(output.stdout)
.ok()
.as_deref()
.and_then(parse_ufw_status)
else {
return Ok(None);
};
Ok(Some(UfwInfo { version, is_enabled }))
}
command.arg("status").env("LC_ALL", "C");
command
fn command_text(commands: &CollectorCommands<'_>, name: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(name, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn parse_clamav_version(output: &str) -> Option<(String, Option<String>)> {
@@ -603,24 +611,11 @@ fn parse_ufw_status(output: &str) -> Option<bool> {
}
}
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
let output = Command::new("mdatp")
.arg("health")
.arg("--output")
.arg("json")
.output()
.ok()?;
if !output.status.success() {
debug!("mdatp health command failed");
return None;
}
let json = String::from_utf8(output.stdout).ok()?;
let defender = parse_defender_info(&json)?;
debug!("Detected Microsoft Defender: {:?}", defender);
Some(defender)
fn detect_microsoft_defender(commands: &CollectorCommands<'_>) -> io::Result<Option<DefenderInfo>> {
let Some(json) = command_text(commands, "mdatp", &["health", "--output", "json"])? else {
return Ok(None);
};
Ok(parse_defender_info(&json))
}
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
@@ -702,9 +697,19 @@ fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> Strin
#[cfg(test)]
mod tests {
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
"md5-sum",
"user-name",
"domain",
"host-name",
"host-id",
"ip-address",
"ipv6-address",
"generate-time",
];
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
use super::*;
use gpapi::os_profile::OsProfileBuilder;
use std::ffi::OsStr;
fn make_input(profile: OsProfile) -> ReportInput {
ReportInput {
@@ -728,7 +733,7 @@ mod tests {
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.os_vendor, "Linux");
}
@@ -739,7 +744,7 @@ mod tests {
let profile = make_profile(ClientOs::Mac);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.os_vendor, "Apple");
}
@@ -750,7 +755,7 @@ mod tests {
let profile = make_profile(ClientOs::Windows);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.os_vendor, "Microsoft");
}
@@ -761,7 +766,7 @@ mod tests {
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.host_id, profile.host_id());
}
@@ -775,7 +780,7 @@ mod tests {
let profile = make_profile(client_os);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.host_id, profile.host_id());
}
@@ -800,7 +805,7 @@ mod tests {
fn mac_report_renders_detected_sentinel_products() {
let input = make_input(make_profile(ClientOs::Mac));
let cookie_params = HashMap::new();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
host_info.sentinel = Some(SentinelInfo {
version: "25.3.4.8365".to_string(),
real_time_protection: true,
@@ -831,7 +836,7 @@ mod tests {
fn linux_report_renders_detected_sentinel_antimalware() {
let input = make_input(make_profile(ClientOs::Linux));
let cookie_params = HashMap::new();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
host_info.sentinel = Some(SentinelInfo {
version: "25.2.2.14".to_string(),
real_time_protection: true,
@@ -911,9 +916,22 @@ mod tests {
.children
.push(xmltree::XMLNode::Element(custom_category));
let earliest = chrono::Local::now().naive_local().and_utc().timestamp();
let refreshed_xml = refresh_edited_report(&write_xml(&saved).unwrap(), &input).unwrap();
let latest = chrono::Local::now().naive_local().and_utc().timestamp();
let refreshed = validate_edited_report(&refreshed_xml).unwrap();
for field in CURRENT_TOP_LEVEL_FIELDS {
let timestamp = chrono::NaiveDateTime::parse_from_str(
&unique_child(&refreshed, "generate-time").unwrap().get_text().unwrap(),
"%m/%d/%Y %H:%M:%S",
)
.unwrap()
.and_utc()
.timestamp();
assert!((earliest..=latest).contains(&timestamp));
for field in CURRENT_TOP_LEVEL_FIELDS
.iter()
.filter(|field| **field != "generate-time")
{
assert_eq!(
unique_child(&refreshed, field).unwrap().get_text(),
unique_child(&current, field).unwrap().get_text()
@@ -992,24 +1010,4 @@ mod tests {
assert_eq!(parse_ufw_status("Status: inactive\n"), Some(false));
assert_eq!(parse_ufw_status("Status: unknown\n"), None);
}
#[test]
fn runs_ufw_status_directly_as_root() {
let command = ufw_status_command(true);
assert_eq!(command.get_program(), OsStr::new("ufw"));
assert!(command.get_args().eq(["status"].into_iter().map(OsStr::new)));
}
#[test]
fn runs_ufw_status_through_non_interactive_sudo_as_non_root() {
let command = ufw_status_command(false);
assert_eq!(command.get_program(), OsStr::new("sudo"));
assert!(
command
.get_args()
.eq(["-n", "ufw", "status"].into_iter().map(OsStr::new))
);
}
}
+30 -24
View File
@@ -1,34 +1,44 @@
use std::{
fs,
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::Path,
process::Command,
};
use gpapi::process::collection::CollectorCommands;
use super::SentinelInfo;
const SENTINELCTL: &str = "/Library/Sentinel/sentinel-agent.bundle/Contents/MacOS/sentinelctl";
pub(super) fn detect() -> Option<SentinelInfo> {
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
if !trusted_cli(Path::new(SENTINELCTL)) {
return None;
return Ok(None);
}
let status = run(&["status"])?;
let status = parse_status(&status)?;
let Some(status) = run(commands, &["status"])? else {
return Ok(None);
};
let Some(status) = parse_status(&status) else {
return Ok(None);
};
let real_time_protection = if status.active {
let scan_status = run(&["scan-on-write"])?;
parse_yes_no(scan_status.trim().strip_prefix("scan-on-write:")?)?
let Some(scan_status) = run(commands, &["scan-on-write"])? else {
return Ok(None);
};
let Some(enabled) = scan_status.trim().strip_prefix("scan-on-write:").and_then(parse_yes_no) else {
return Ok(None);
};
enabled
} else {
false
};
let firewall_enabled = run(&["firewall", "enabled"]).as_deref().and_then(parse_yes_no);
Some(SentinelInfo {
let firewall_enabled = run(commands, &["firewall", "enabled"])?
.as_deref()
.and_then(parse_yes_no);
Ok(Some(SentinelInfo {
version: status.version,
real_time_protection,
firewall_enabled,
})
}))
}
fn trusted_cli(path: &Path) -> bool {
@@ -47,17 +57,13 @@ fn trusted_cli(path: &Path) -> bool {
})
}
fn run(args: &[&str]) -> Option<String> {
let output = Command::new(SENTINELCTL)
.args(args)
.env("LC_ALL", "C")
.env_remove("SENTINEL_OUTPUT_JSON")
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
fn run(commands: &CollectorCommands<'_>, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run_path(Path::new(SENTINELCTL), args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
struct AgentStatus {
+34 -24
View File
@@ -1,33 +1,47 @@
use std::{
fs,
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
process::Command,
};
use gpapi::process::collection::CollectorCommands;
use super::SentinelInfo;
const SENTINEL_DIR: &str = "/opt/sentinelone";
pub(super) fn detect() -> Option<SentinelInfo> {
let cli = trusted_cli()?;
let version = parse_version(&run(&cli, &["version"])?)?;
let agent_enabled = parse_enabled(&run(&cli, &["control", "status"])?, "Agent state")?;
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
let Some(cli) = trusted_cli() else {
return Ok(None);
};
let Some(version) = run(commands, &cli, &["version"])?.as_deref().and_then(parse_version) else {
return Ok(None);
};
let Some(agent_enabled) = run(commands, &cli, &["control", "status"])?
.as_deref()
.and_then(|status| parse_enabled(status, "Agent state"))
else {
return Ok(None);
};
let real_time_protection = if agent_enabled {
let policy = run(&cli, &["policy", "status"])?;
let on_write = parse_enabled(&policy, "On-Write:")?;
let on_execute = parse_enabled(&policy, "On-Execute:")?;
let Some(policy) = run(commands, &cli, &["policy", "status"])? else {
return Ok(None);
};
let (Some(on_write), Some(on_execute)) = (
parse_enabled(&policy, "On-Write:"),
parse_enabled(&policy, "On-Execute:"),
) else {
return Ok(None);
};
on_write || on_execute
} else {
false
};
Some(SentinelInfo {
Ok(Some(SentinelInfo {
version,
real_time_protection,
firewall_enabled: None,
})
}))
}
fn trusted_cli() -> Option<PathBuf> {
@@ -72,17 +86,13 @@ fn trusted_dir(path: &Path, owner: u32) -> bool {
metadata.is_dir() && metadata.uid() == owner && metadata.permissions().mode() & 0o022 == 0
}
fn run(cli: &Path, args: &[&str]) -> Option<String> {
let output = Command::new(cli)
.args(args)
.env("LC_ALL", "C")
.env_remove("SENTINEL_OUTPUT_JSON")
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
fn run(commands: &CollectorCommands<'_>, cli: &Path, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run_path(cli, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn parse_version(output: &str) -> Option<String> {
+1
View File
@@ -7,6 +7,7 @@ links = "openconnect"
[dependencies]
log.workspace = true
libc = "0.2"
is_executable.workspace = true
[build-dependencies]
+8
View File
@@ -157,6 +157,14 @@ fn main() {
let deps_dir = PathBuf::from(manifest_dir).join("deps");
let oc_dst = build_openconnect(&deps_dir, &out_dir);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}",
oc_dst.join("build").display()
);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}",
out_dir.join("openconnect_build").display()
);
// Only statically link libxml2 if `LIBXML2_STATIC` is set
if env::var("LIBXML2_STATIC").is_ok() {
+437
View File
@@ -0,0 +1,437 @@
use crate::{HipControl, HipRequest, HipScript, HipSource, Vpn};
use std::{
ffi::{CString, c_char, c_int, c_void},
io,
marker::PhantomData,
panic::{AssertUnwindSafe, catch_unwind},
};
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_collect_hip_report(
script: *const HipScriptRaw,
request: *const HipRequestRaw,
control: *const HipControlRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int;
}
#[repr(C)]
pub(crate) struct HipRequestRaw {
cookie: *const c_char,
client_ip: *const c_char,
client_ipv6: *const c_char,
md5: *const c_char,
client_version: *const c_char,
client_os: *const c_char,
os_version: *const c_char,
host_id: *const c_char,
local_hostname: *const c_char,
}
#[repr(C)]
pub(crate) struct HipControlRaw {
pub data: *mut c_void,
pub check: unsafe extern "C" fn(*mut c_void) -> c_int,
}
pub(crate) type HipGenerateFn =
extern "C" fn(*mut c_void, *const HipRequestRaw, *const HipControlRaw, *mut c_char, usize, *mut usize) -> c_int;
#[repr(C)]
#[derive(Debug)]
pub(crate) struct HipScriptRaw {
pub path: *const c_char,
pub uid: u32,
pub uid_present: c_int,
pub validation_data: *mut c_void,
pub validate: Option<extern "C" fn(*mut c_void, *const HipControlRaw) -> c_int>,
pub environment: *const *const c_char,
pub cwd: *const c_char,
}
impl Default for HipScriptRaw {
fn default() -> Self {
Self {
path: std::ptr::null(),
uid: 0,
uid_present: 0,
validation_data: std::ptr::null_mut(),
validate: None,
environment: std::ptr::null(),
cwd: std::ptr::null(),
}
}
}
impl HipScriptRaw {
pub fn from_script(script: &HipScript) -> Self {
Self {
path: script.path.as_ptr(),
uid: script.user.unwrap_or(0),
uid_present: script.user.is_some().into(),
validation_data: script as *const _ as *mut _,
validate: script.validator.as_ref().map(|_| validate_hip_script as _),
environment: std::ptr::null(),
cwd: script.cwd.as_ref().map_or(std::ptr::null(), |value| value.as_ptr()),
}
}
}
pub(crate) fn script_environment(script: &HipScript) -> Vec<*const c_char> {
match &script.environment {
Some(values) => values
.iter()
.map(|value| value.as_ptr())
.chain(std::iter::once(std::ptr::null()))
.collect(),
None => Vec::new(),
}
}
fn error_code(error: io::Error) -> c_int {
let errno = error.raw_os_error().unwrap_or_else(|| match error.kind() {
io::ErrorKind::Interrupted => libc::EINTR,
io::ErrorKind::TimedOut => libc::ETIMEDOUT,
io::ErrorKind::InvalidInput | io::ErrorKind::InvalidData => libc::EINVAL,
io::ErrorKind::PermissionDenied => libc::EPERM,
io::ErrorKind::NotFound => libc::ENOENT,
_ => libc::EIO,
});
-errno
}
unsafe fn request_string(pointer: *const c_char) -> io::Result<Option<String>> {
if pointer.is_null() {
return Ok(None);
}
unsafe { std::ffi::CStr::from_ptr(pointer) }
.to_str()
.map(|s| Some(s.to_owned()))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid HIP request encoding"))
}
unsafe fn read_hip_request(raw: &HipRequestRaw) -> io::Result<HipRequest> {
unsafe {
Ok(HipRequest {
cookie: request_string(raw.cookie)?.unwrap_or_default(),
client_ip: request_string(raw.client_ip)?,
client_ipv6: request_string(raw.client_ipv6)?,
md5: request_string(raw.md5)?.unwrap_or_default(),
client_version: request_string(raw.client_version)?.unwrap_or_default(),
client_os: request_string(raw.client_os)?.unwrap_or_default(),
os_version: request_string(raw.os_version)?.unwrap_or_default(),
host_id: request_string(raw.host_id)?,
local_hostname: request_string(raw.local_hostname)?,
})
}
}
pub(crate) extern "C" fn generate_hip_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
let vpn = unsafe { &*(data as *const Vpn) };
let HipSource::Generator(generate) = &vpn.hip_source else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
};
let request = unsafe { read_hip_request(&*request)? };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
let report = generate(&request, &control)?;
control.check()?;
if report.len() > capacity {
return Err(io::Error::from_raw_os_error(libc::E2BIG));
}
unsafe {
std::ptr::copy_nonoverlapping(report.as_ptr(), output.cast(), report.len());
*written = report.len();
}
Ok(())
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
extern "C" fn validate_hip_script(data: *mut c_void, control: *const HipControlRaw) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let script = unsafe { &*(data as *const HipScript) };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
if let Some(validate) = &script.validator {
validate(&control)?;
}
control.check()
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
pub(crate) fn preview_hip_script(
script: &HipScript,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let mut raw = HipScriptRaw::from_script(script);
let environment = script_environment(script);
if !environment.is_empty() {
raw.environment = environment.as_ptr();
}
collect_hip_report(&raw, None, std::ptr::null_mut(), request, check)
}
fn collect_hip_report(
script_raw: &HipScriptRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let values = [
Some(request.cookie.as_str()),
request.client_ip.as_deref(),
request.client_ipv6.as_deref(),
Some(request.md5.as_str()),
Some(request.client_version.as_str()),
Some(request.client_os.as_str()),
Some(request.os_version.as_str()),
request.host_id.as_deref(),
request.local_hostname.as_deref(),
]
.into_iter()
.map(|value| value.map(CString::new).transpose())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP request contains NUL"))?;
let ptr = |i: usize| values[i].as_ref().map_or(std::ptr::null(), |value| value.as_ptr());
let raw = HipRequestRaw {
cookie: ptr(0),
client_ip: ptr(1),
client_ipv6: ptr(2),
md5: ptr(3),
client_version: ptr(4),
client_os: ptr(5),
os_version: ptr(6),
host_id: ptr(7),
local_hostname: ptr(8),
};
let control = HipControlRaw {
data: &check as *const _ as *mut _,
check: preview_check,
};
let mut output = vec![0u8; 1024 * 1024 + 1];
let mut written = 0;
let result = unsafe {
vpn_collect_hip_report(
script_raw,
&raw,
&control,
generate,
data,
output.as_mut_ptr().cast(),
1024 * 1024,
&mut written,
)
};
if result < 0 {
return Err(io::Error::from_raw_os_error(-result));
}
output.truncate(written);
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
}
unsafe extern "C" fn preview_check(data: *mut c_void) -> c_int {
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
match catch_unwind(AssertUnwindSafe(check)) {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
#[cfg(test)]
mod hip_tests {
use super::*;
use std::{
fs,
os::unix::fs::PermissionsExt,
sync::atomic::{AtomicUsize, Ordering},
time::{Duration, Instant},
};
fn provider(generate: impl Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync + 'static) -> Vpn {
Vpn::builder("vpn.example", "cookie")
.script_path("/bin/sh".to_owned())
.hip_source(HipSource::Generator(std::sync::Arc::new(generate)))
.build()
.unwrap()
}
fn collect(vpn: &Vpn, script: &HipScriptRaw, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
collect_hip_report(
script,
Some(generate_hip_report),
vpn as *const _ as *mut _,
&HipRequest::default(),
check,
)
}
struct ScriptFixture(std::path::PathBuf);
impl ScriptFixture {
fn new(contents: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let directory = std::env::temp_dir().join(format!(
"gp-hip-script-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&directory).unwrap();
let path = directory.join("script");
fs::write(&path, format!("#!/bin/sh\n{contents}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self(directory)
}
fn script(&self, user: Option<u32>) -> HipScript {
HipScript::new(self.0.join("script").to_str().unwrap().to_owned(), user).unwrap()
}
}
impl Drop for ScriptFixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn callback_outputs_are_bounded_and_validated_by_c() {
let raw = HipScriptRaw::default();
for (report, errno) in [
(String::new(), libc::EINVAL),
("x\0x".to_owned(), libc::EINVAL),
("x".repeat(1024 * 1024 + 1), libc::E2BIG),
] {
let vpn = provider(move |_, _| Ok(report.clone()));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap_err().raw_os_error(), Some(errno));
}
let vpn = provider(|_, _| Ok("x".repeat(1024 * 1024)));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap().len(), 1024 * 1024);
}
#[test]
fn callback_panics_and_control_errors_do_not_cross_ffi() {
let vpn = provider(|_, _| panic!("test generator panic"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
let vpn = provider(|_, _| Err(io::Error::from(io::ErrorKind::TimedOut)));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::ETIMEDOUT)
);
let vpn = provider(|_, _| panic!("Canceled provider must not run"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn explicit_script_wins_and_uid_presence_is_preserved() {
let fixture = ScriptFixture::new("printf '<script/>'");
let script = fixture.script(None);
let raw = HipScriptRaw::from_script(&script);
assert_eq!(raw.uid_present, 0);
let vpn = provider(|_, _| panic!("Script must win"));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
let script = fixture.script(Some(unsafe { libc::getuid() }));
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
assert_eq!(script.preview(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
}
#[test]
fn validator_refusal_prevents_execution_and_errors_propagate() {
let fixture = ScriptFixture::new("touch executed; printf '<script/>'");
let script = fixture
.script(None)
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
assert_eq!(
script
.preview(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EPERM)
);
assert!(!fixture.0.join("executed").exists());
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
assert_eq!(
script
.preview(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
}
#[test]
fn child_environment_and_cwd_are_explicit_without_parent_mutation() {
let fixture = ScriptFixture::new("printf '%s:%s' \"$HIP_TEST_VALUE\" \"$PWD\"");
let cwd = fs::canonicalize(&fixture.0).unwrap().to_str().unwrap().to_owned();
let script = fixture
.script(None)
.with_environment(crate::HipScriptEnvironment {
variables: vec![("HIP_TEST_VALUE".into(), "child".into())],
cwd: cwd.clone(),
})
.unwrap();
assert_eq!(
script.preview(&HipRequest::default(), &|| Ok(())).unwrap(),
format!("child:{cwd}")
);
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
}
#[test]
fn script_empty_nul_and_nonzero_outputs_fail() {
for contents in ["true", "printf '\\000'", "printf '<script/>'; exit 1"] {
let fixture = ScriptFixture::new(contents);
assert_eq!(
fixture
.script(None)
.preview(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EINVAL)
);
}
}
#[test]
fn cancellation_and_deadline_kill_descendants_and_reap_child() {
for errno in [libc::EINTR, libc::ETIMEDOUT] {
let fixture = ScriptFixture::new("sleep 20 &\nwait\nprintf '<script/>'");
let start = Instant::now();
let check = || {
if start.elapsed() > Duration::from_millis(80) {
Err(io::Error::from_raw_os_error(errno))
} else {
Ok(())
}
};
assert_eq!(
fixture
.script(None)
.preview(&HipRequest::default(), &check)
.unwrap_err()
.raw_os_error(),
Some(errno)
);
assert!(start.elapsed() < Duration::from_secs(2));
}
}
}
+9 -3
View File
@@ -1,6 +1,10 @@
mod hip;
use crate::Vpn;
use hip::HipGenerateFn;
pub(crate) use hip::{HipControlRaw, HipScriptRaw, generate_hip_report, preview_hip_script, script_environment};
use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
@@ -28,8 +32,8 @@ pub(crate) struct ConnectOptions {
pub key_password: *const c_char,
pub servercert: *const c_char,
pub csd_uid: u32,
pub csd_wrapper: *const c_char,
pub hip_script: HipScriptRaw,
pub generate_hip: Option<HipGenerateFn>,
pub reconnect_timeout: u32,
pub mtu: u32,
@@ -94,7 +98,9 @@ pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *cons
}
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
if let Ok(report) = std::str::from_utf8(bytes) {
vpn.on_hip_report_submitted(report);
if catch_unwind(AssertUnwindSafe(|| vpn.on_hip_report_submitted(report))).is_err() {
warn!("HIP submission observer failed");
}
}
}
+27 -5
View File
@@ -86,8 +86,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
INFO("VPNC_SCRIPT: %s", options->script);
INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->csd_uid);
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
INFO("CSD_USER: %d", options->hip_script.uid);
INFO("CSD_WRAPPER: %s", options->hip_script.path);
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
INFO("MTU: %d", options->mtu);
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
@@ -168,9 +168,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_xmlpost(vpninfo, 0);
}
if (options->csd_wrapper) {
openconnect_setup_csd(vpninfo, options->csd_uid, 1,
options->csd_wrapper);
openconnect_set_gp_hip_generator(vpninfo, options->user_data, options->generate_hip);
if (options->hip_script.path) {
result = openconnect_set_gp_hip_script(vpninfo, options->hip_script.path,
options->hip_script.uid_present, options->hip_script.uid,
options->hip_script.validation_data, options->hip_script.validate,
options->hip_script.environment, options->hip_script.cwd);
if (result)
goto cleanup;
}
if (options->mtu > 0) {
@@ -225,3 +230,20 @@ int vpn_write_cancel(int fd)
} while (written < 0 && errno == EINTR);
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
int vpn_collect_hip_report(const vpn_hip_script *script,
const struct openconnect_gp_hip_request *request,
const struct openconnect_gp_hip_control *control, openconnect_gp_hip_generate_fn generate, void *data,
char *output, size_t capacity, size_t *written)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("HIP preview", NULL, NULL, NULL, print_progress, NULL);
int result;
if (!vpninfo)
return -ENOMEM;
openconnect_set_gp_hip_generator(vpninfo, data, generate);
result = openconnect_set_gp_hip_script(vpninfo, script->path, script->uid_present,
script->uid, script->validation_data, script->validate, script->environment, script->cwd);
if (!result) result = openconnect_collect_gp_hip_report(vpninfo, request, control, output, capacity, written);
openconnect_vpninfo_free(vpninfo);
return result;
}
+14 -2
View File
@@ -19,6 +19,16 @@ typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
size_t length);
typedef struct vpn_hip_script {
const char *path;
uid_t uid;
int uid_present;
void *validation_data;
openconnect_gp_hip_validate_fn validate;
const char *const *environment;
const char *cwd;
} vpn_hip_script;
typedef struct vpn_options {
void *user_data;
vpn_hip_report_callback on_hip_report_submitted;
@@ -42,8 +52,8 @@ typedef struct vpn_options {
const char *key_password;
const char *servercert;
const uid_t csd_uid;
const char *csd_wrapper;
vpn_hip_script hip_script;
openconnect_gp_hip_generate_fn generate_hip;
const int reconnect_timeout;
const int mtu;
@@ -55,6 +65,8 @@ typedef struct vpn_options {
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data);
+115
View File
@@ -0,0 +1,115 @@
use std::{ffi::CString, io, marker::PhantomData, rc::Rc, sync::Arc};
use crate::{ffi, vpn_utils::check_executable};
pub type HipGenerator = dyn Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync;
type HipValidator = dyn Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync;
#[derive(Default)]
pub enum HipSource {
#[default]
Disabled,
Generator(Arc<HipGenerator>),
Script(HipScript),
}
/// Current gateway and negotiated identity inputs for one report invocation.
#[derive(Clone, Default)]
pub struct HipRequest {
pub cookie: String,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub md5: String,
pub client_version: String,
pub client_os: String,
pub os_version: String,
pub host_id: Option<String>,
pub local_hostname: Option<String>,
}
/// Borrowed cancellation and deadline control. It must stay on the invocation thread.
pub struct HipControl<'a> {
pub(crate) raw: &'a ffi::HipControlRaw,
pub(crate) _thread: PhantomData<Rc<()>>,
}
impl HipControl<'_> {
pub fn check(&self) -> io::Result<()> {
let result = unsafe { (self.raw.check)(self.raw.data) };
if result < 0 {
Err(io::Error::from_raw_os_error(-result))
} else {
Ok(())
}
}
}
pub struct HipScriptEnvironment {
pub variables: Vec<(String, String)>,
pub cwd: String,
}
pub struct HipScript {
pub(crate) path: CString,
pub(crate) user: Option<u32>,
pub(crate) validator: Option<Arc<HipValidator>>,
pub(crate) environment: Option<Vec<CString>>,
pub(crate) cwd: Option<CString>,
}
impl HipScript {
pub fn new(path: String, user: Option<u32>) -> io::Result<Self> {
if !std::fs::metadata(&path)?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP executable is not a regular file",
));
}
check_executable(&path)?;
let path = c_string(path)?;
Ok(Self {
path,
user,
validator: None,
environment: None,
cwd: None,
})
}
pub fn with_validator(
mut self,
validator: impl Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync + 'static,
) -> Self {
self.validator = Some(Arc::new(validator));
self
}
/// A child-local replacement environment and working directory, never process-global changes.
pub fn with_environment(mut self, environment: HipScriptEnvironment) -> io::Result<Self> {
let variables = environment
.variables
.into_iter()
.map(|(key, value)| {
if key.is_empty() || key.contains('=') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid HIP environment key",
));
}
c_string(format!("{key}={value}"))
})
.collect::<io::Result<Vec<_>>>()?;
self.environment = Some(variables);
self.cwd = Some(c_string(environment.cwd)?);
Ok(self)
}
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
pub fn preview(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::preview_hip_script(self, request, check)
}
}
fn c_string(value: String) -> io::Result<CString> {
CString::new(value).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP value contains NUL"))
}
+2
View File
@@ -1,6 +1,8 @@
mod ffi;
mod hip;
mod vpn;
mod vpn_utils;
pub use hip::*;
pub use vpn::*;
pub use vpn_utils::*;
+25 -48
View File
@@ -6,8 +6,8 @@ use std::{
use log::{info, warn};
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
use crate::vpn_utils::{check_executable, find_vpnc_script};
use crate::{HipSource, ffi};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
@@ -119,8 +119,7 @@ pub struct Vpn {
key_password: Option<CString>,
servercert: Option<CString>,
csd_uid: u32,
csd_wrapper: Option<CString>,
pub(crate) hip_source: HipSource,
reconnect_timeout: u32,
mtu: u32,
@@ -141,8 +140,14 @@ impl Vpn {
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
self.callback.write().unwrap().replace(Box::new(on_connected));
let options = self.build_connect_options();
let mut options = self.build_connect_options();
let environment = match &self.hip_source {
HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(),
};
if !environment.is_empty() {
options.hip_script.environment = environment.as_ptr();
}
ffi::connect(&options)
}
@@ -205,8 +210,14 @@ impl Vpn {
key_password: Self::option_to_ptr(&self.key_password),
servercert: Self::option_to_ptr(&self.servercert),
csd_uid: self.csd_uid,
csd_wrapper: Self::option_to_ptr(&self.csd_wrapper),
hip_script: match &self.hip_source {
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
_ => Default::default(),
},
generate_hip: match &self.hip_source {
HipSource::Generator(_) => Some(ffi::generate_hip_report),
_ => None,
},
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -263,9 +274,7 @@ pub struct VpnBuilder {
sslkey: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
hip_source: HipSource,
reconnect_timeout: u32,
mtu: u32,
@@ -297,9 +306,7 @@ impl VpnBuilder {
sslkey: None,
key_password: None,
hip: false,
csd_uid: 0,
csd_wrapper: None,
hip_source: HipSource::Disabled,
reconnect_timeout: 300,
mtu: 0,
@@ -377,18 +384,8 @@ impl VpnBuilder {
self
}
pub fn hip(mut self, hip: bool) -> Self {
self.hip = hip;
self
}
pub fn csd_uid(mut self, csd_uid: u32) -> Self {
self.csd_uid = csd_uid;
self
}
pub fn csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
self.csd_wrapper = csd_wrapper.into();
pub fn hip_source(mut self, hip_source: HipSource) -> Self {
self.hip_source = hip_source;
self
}
@@ -435,23 +432,6 @@ impl VpnBuilder {
}
}
fn determine_csd_wrapper(&self) -> Result<Option<&str>, VpnError> {
if !self.hip {
return Ok(None);
}
match &self.csd_wrapper {
Some(csd_wrapper) if !csd_wrapper.is_empty() => {
check_executable(csd_wrapper).map_err(|e| VpnError::new(e.to_string()))?;
Ok(Some(csd_wrapper))
}
_ => {
let s = find_csd_wrapper().ok_or_else(|| VpnError::new(String::from("Failed to find csd wrapper")))?;
Ok(Some(s))
}
}
}
pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.determine_script()?.to_owned();
let script = if self.script_is_path {
@@ -459,7 +439,6 @@ impl VpnBuilder {
} else {
script
};
let csd_wrapper = self.determine_csd_wrapper()?.map(|s| s.to_owned());
let user_agent = self.user_agent.unwrap_or_default();
let os = self.os.unwrap_or("linux".to_string());
@@ -485,8 +464,7 @@ impl VpnBuilder {
key_password: self.key_password.as_deref().map(Self::to_cstring),
servercert: None,
csd_uid: self.csd_uid,
csd_wrapper: csd_wrapper.as_deref().map(Self::to_cstring),
hip_source: self.hip_source,
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -611,8 +589,7 @@ mod tests {
sslkey: None,
key_password: None,
servercert: None,
csd_uid: 0,
csd_wrapper: None,
hip_source: HipSource::Disabled,
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
-19
View File
@@ -19,21 +19,6 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
for location in locations.iter() {
let path = Path::new(location);
@@ -49,10 +34,6 @@ pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(VPNC_SCRIPT_LOCATIONS)
}
pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(CSD_WRAPPER_LOCATIONS)
}
/// If file exists, check if it is executable
pub fn check_executable(file: &str) -> Result<(), io::Error> {
let path = Path::new(file);
+78
View File
@@ -0,0 +1,78 @@
"""Local TLS GlobalProtect fixture accepting HIP and raw SSL tunnel setup."""
import socket
import ssl
import sys
import threading
from urllib.parse import parse_qs
cert, key, records = sys.argv[1:]
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, key)
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen()
state = {"configs": 0, "checks": 0, "reports": 0}
lock = threading.Lock()
def serve(connection):
try:
with context.wrap_socket(connection, server_side=True) as stream:
buffer = b""
while True:
while b"\r\n\r\n" not in buffer:
data = stream.recv(4096)
if not data:
return
buffer += data
headers, buffer = buffer.split(b"\r\n\r\n", 1)
method, path, _ = headers.split(b"\r\n", 1)[0].decode().split()
if method == "GET" and path.startswith("/ssl-tunnel-connect.sslvpn?"):
stream.sendall(b"START_TUNNEL")
while stream.recv(4096):
pass
return
length = 0
for header in headers.split(b"\r\n")[1:]:
name, value = header.split(b":", 1)
if name.lower() == b"content-length":
length = int(value)
while len(buffer) < length:
buffer += stream.recv(4096)
body, buffer = buffer[:length], buffer[length:]
form = parse_qs(body.decode())
status = "200 OK"
with lock:
if path == "/ssl-vpn/getconfig.esp":
state["configs"] += 1
ip = "10.0.0.1"
response = f"<response><ip-address>{ip}</ip-address><gw-address>127.0.0.1</gw-address><ssl-tunnel-url>/ssl-tunnel-connect.sslvpn</ssl-tunnel-url></response>"
elif path == "/ssl-vpn/hipreportcheck.esp":
state["checks"] += 1
needed = "no" if state["checks"] == 4 else "yes"
response = f"<response><hip-report-needed>{needed}</hip-report-needed></response>"
elif path == "/ssl-vpn/hipreport.esp":
state["reports"] += 1
seq = state["reports"]
expected_ip = "10.0.0.1"
assert form.get("authcookie") == ["test" if seq < 3 else "refreshed"]
expected = f'<hip seq="{seq}" ip="{expected_ip}"/>'
assert form.get("report") == [expected], form
assert form.get("client-ip") == [expected_ip], form
with open(records, "a", encoding="utf-8") as output:
output.write(expected + "\n")
if seq == 4:
status = "403 Forbidden"
response = "<response/>"
else:
raise AssertionError(path)
payload = response.encode()
stream.sendall(f"HTTP/1.1 {status}\r\nContent-Length: {len(payload)}\r\nContent-Type: text/xml\r\nConnection: keep-alive\r\n\r\n".encode() + payload)
except (ConnectionError, ssl.SSLError):
pass
print(listener.getsockname()[1], flush=True)
while True:
connection, _ = listener.accept()
threading.Thread(target=serve, args=(connection,), daemon=True).start()
+74
View File
@@ -0,0 +1,74 @@
/* Integration harness: exercise setup and the actual connected periodic branch. */
#include <config.h>
#include "openconnect-internal.h"
#include <assert.h>
#include <stdarg.h>
struct state { int generated, accepted; };
static int accept_cert(void *data, const char *reason) { return 0; }
static void progress(void *data, int level, const char *format, ...) {
if (level > PRG_INFO) return;
va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args);
}
static int generate(void *data, const struct openconnect_gp_hip_request *request,
const struct openconnect_gp_hip_control *control, char *output, size_t capacity, size_t *written)
{
struct state *state = data;
int length;
assert(!control->check(control->data));
assert(!strcmp(request->client_os, "Linux"));
assert(!strcmp(request->client_version, "6.3.3"));
assert(!strcmp(request->host_id, "test-host"));
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
state->generated++;
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
assert(length > 0 && length < capacity);
*written = length;
return 0;
}
static void submitted(void *data, const char *report, size_t length) {
struct state *state = data;
assert(report && length > 0);
state->accepted++;
}
static int periodic(struct openconnect_info *vpninfo) {
int timeout = 1000;
vpninfo->trojan_interval = 1;
vpninfo->last_trojan = time(NULL) - 2;
return gpst_mainloop(vpninfo, &timeout, 0);
}
int main(int argc, char **argv) {
struct state state = {0};
struct openconnect_info *vpninfo;
assert(argc == 2);
openconnect_init_ssl();
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
assert(vpninfo);
assert(!openconnect_set_protocol(vpninfo, "gp"));
assert(!openconnect_set_reported_os(vpninfo, "linux"));
assert(!openconnect_parse_url(vpninfo, argv[1]));
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&portal=test&domain=test&computer=test"));
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.3"));
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
openconnect_disable_dtls(vpninfo);
openconnect_set_gp_hip_generator(vpninfo, &state, generate);
openconnect_set_gp_hip_report_callback(vpninfo, &state, submitted);
assert(!openconnect_make_cstp_connection(vpninfo));
assert(vpninfo->ssl_fd >= 0 && state.generated == 1 && state.accepted == 1);
assert(!periodic(vpninfo));
assert(state.generated == 2 && state.accepted == 2);
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
openconnect_close_https(vpninfo, 0);
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&portal=test&domain=test&computer=test"));
assert(!openconnect_make_cstp_connection(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fourth gateway check says no report needed. */
assert(!periodic(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fifth submission is rejected; observer must not see it. */
assert(periodic(vpninfo));
assert(state.generated == 4 && state.accepted == 3);
openconnect_vpninfo_free(vpninfo);
return 0;
}
+139
View File
@@ -0,0 +1,139 @@
use std::{
fs,
io::{BufRead, BufReader},
os::unix::process::CommandExt,
path::PathBuf,
process::{Child, Command, Stdio},
sync::mpsc,
time::{Duration, Instant},
};
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
unsafe {
libc::kill(-(self.0.id() as i32), libc::SIGKILL);
}
let _ = self.0.kill();
let _ = self.0.wait();
}
}
struct TestDirectory(PathBuf);
impl Drop for TestDirectory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn c_protocol_submits_initial_periodic_and_reconnect_reports() {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
let directory = TestDirectory(std::env::temp_dir().join(format!("gp-hip-protocol-{}", std::process::id())));
fs::create_dir(&directory.0).unwrap();
let executable = directory.0.join("hip-protocol");
let flags = Command::new("pkg-config")
.args([
"--cflags",
"libxml-2.0",
if cfg!(target_os = "macos") { "openssl" } else { "gnutls" },
])
.output()
.unwrap();
assert!(flags.status.success());
let compile_command = Command::new(build.join("libtool"))
.args(["--mode=link", "cc"])
.arg(manifest.join("tests/hip_protocol.c"))
.arg("-I")
.arg(&build)
.arg("-I")
.arg(&source)
.arg("-I")
.arg(source.join("json"))
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
.arg(build.join("libopenconnect.la"))
.arg("-o")
.arg(&executable)
.process_group(0)
.stdout(Stdio::from(fs::File::create(directory.0.join("compile.log")).unwrap()))
.stderr(Stdio::from(
fs::File::options()
.append(true)
.open(directory.0.join("compile.log"))
.unwrap(),
))
.spawn()
.unwrap();
let mut compile_command = ChildGuard(compile_command);
wait_bounded(
&mut compile_command,
Duration::from_secs(30),
&directory.0.join("compile.log"),
);
let records = directory.0.join("submissions");
let certificates = manifest.join("deps/openconnect/tests/certs");
let server = Command::new("python3")
.arg(manifest.join("tests/hip_gateway.py"))
.arg(certificates.join("server-cert.pem"))
.arg(certificates.join("server-key.pem"))
.arg(&records)
.process_group(0)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.unwrap();
let mut server = ChildGuard(server);
let stdout = server.0.stdout.take().unwrap();
let (tx, rx) = mpsc::channel();
let reader = std::thread::spawn(move || {
let mut port = String::new();
let result = BufReader::new(stdout).read_line(&mut port).map(|_| port);
let _ = tx.send(result);
});
let port = match rx.recv_timeout(Duration::from_secs(3)) {
Ok(result) => result.expect("Fake gateway startup failed"),
Err(error) => {
let _ = server.0.kill();
let _ = server.0.wait();
let _ = reader.join();
panic!("Fake gateway startup timed out: {error}");
}
};
reader.join().unwrap();
let port: u16 = port.trim().parse().expect("Fake gateway did not start");
let log = fs::File::create(directory.0.join("client.log")).unwrap();
let mut client = ChildGuard(
Command::new(build.join("libtool"))
.args(["--mode=execute"])
.arg(executable)
.arg(format!("https://127.0.0.1:{port}"))
.process_group(0)
.stdout(log.try_clone().unwrap())
.stderr(log)
.spawn()
.unwrap(),
);
wait_bounded(&mut client, Duration::from_secs(15), &directory.0.join("client.log"));
let reports = fs::read_to_string(records).unwrap();
assert_eq!(
reports,
"<hip seq=\"1\" ip=\"10.0.0.1\"/>\n<hip seq=\"2\" ip=\"10.0.0.1\"/>\n<hip seq=\"3\" ip=\"10.0.0.1\"/>\n<hip seq=\"4\" ip=\"10.0.0.1\"/>\n"
);
}
fn wait_bounded(child: &mut ChildGuard, timeout: Duration, log: &std::path::Path) {
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = child.0.try_wait().unwrap() {
assert!(status.success(), "{}", fs::read_to_string(log).unwrap());
return;
}
assert!(
Instant::now() < deadline,
"HIP protocol test process timed out: {}",
fs::read_to_string(log).unwrap()
);
std::thread::sleep(Duration::from_millis(20));
}
}