diff --git a/.gitignore b/.gitignore index 05afd4d..6d7fb00 100644 --- a/.gitignore +++ b/.gitignore @@ -24,4 +24,7 @@ data/ logs/ config/ - +# Local environment and secret files (Zero secret leakage invariant) +.env +.env.* +!.env.example diff --git a/Cargo.lock b/Cargo.lock index 0679a5c..2775d88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1033,6 +1033,7 @@ dependencies = [ "killswitch-adjudication", "killswitch-conformal", "killswitch-core", + "killswitch-kernel-patcher", "killswitch-orchestrator", "killswitch-server", "killswitch-telemetry", @@ -1078,6 +1079,22 @@ dependencies = [ "winreg", ] +[[package]] +name = "killswitch-kernel-patcher" +version = "0.1.0" +dependencies = [ + "libc", + "reqwest", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tracing", + "windows-sys 0.59.0", + "winreg", +] + [[package]] name = "killswitch-orchestrator" version = "0.1.0" @@ -1124,6 +1141,7 @@ dependencies = [ "killswitch-adjudication", "killswitch-conformal", "killswitch-core", + "killswitch-kernel-patcher", "killswitch-telemetry", "killswitch-types", "parking_lot", diff --git a/Cargo.toml b/Cargo.toml index 34b501a..574b337 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ killswitch-orchestrator = { path = "crates/killswitch-orchestrator" } killswitch-server = { path = "crates/killswitch-server" } killswitch-cli = { path = "crates/killswitch-cli" } killswitch-conformal = { path = "crates/killswitch-conformal" } +killswitch-kernel-patcher = { path = "crates/killswitch-kernel-patcher" } # OpenTelemetry & OpenLineage Integration @@ -82,6 +83,8 @@ windows = { version = "0.58", features = [ "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_Security", + "Win32_Security_Isolation", + "Win32_Security_Authorization", "Win32_Security_WinTrust", "Win32_Security_Cryptography", "Win32_System_LibraryLoader", diff --git a/crates/killswitch-cli/Cargo.toml b/crates/killswitch-cli/Cargo.toml index 13b1ccd..f99da42 100644 --- a/crates/killswitch-cli/Cargo.toml +++ b/crates/killswitch-cli/Cargo.toml @@ -25,6 +25,7 @@ killswitch-telemetry = { workspace = true } killswitch-orchestrator = { workspace = true } killswitch-server = { workspace = true } killswitch-conformal = { workspace = true } +killswitch-kernel-patcher = { workspace = true } # Web & async runtime axum = { workspace = true, features = ["macros"] } diff --git a/crates/killswitch-cli/src/bin/killswitch.rs b/crates/killswitch-cli/src/bin/killswitch.rs index 70f09a3..91bf156 100644 --- a/crates/killswitch-cli/src/bin/killswitch.rs +++ b/crates/killswitch-cli/src/bin/killswitch.rs @@ -288,6 +288,30 @@ enum Commands { #[arg(long)] token: Option, }, + + /// Scan OS kernel vulnerabilities against NVD API 2.0 / CISA KEV and orchestrate native patching + #[command(name = "patch-kernel", visible_alias = "kernel-patch")] + PatchKernel { + /// Output planned OS patch command without executing or modifying system state + #[arg(long)] + dry_run: bool, + + /// Filter findings to CISA Known Exploited Vulnerabilities (KEV) only + #[arg(long)] + kev_only: bool, + + /// Minimum CVSS v3.1 base score threshold (e.g. 7.0) + #[arg(long)] + min_cvss: Option, + + /// Override target CPE 2.3 string (defaults to auto-detected host kernel) + #[arg(long)] + cpe: Option, + + /// Orchestrate native OS kernel patch workflow after scanning + #[arg(long)] + apply: bool, + }, } #[derive(Subcommand, Debug)] @@ -631,7 +655,77 @@ async fn main() -> Result<()> { }) => { killswitch_cli::siquery_cli::handle_siquery(query, &format, tables, sweep, token)?; } + Some(Commands::PatchKernel { + dry_run, + kev_only, + min_cvss, + cpe, + apply, + }) => { + killswitch_cli::commands::handle_patch_kernel(dry_run, kev_only, min_cvss, cpe, apply) + .await?; + } } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[test] + fn test_patch_kernel_cli_parsing() { + let cli = Cli::try_parse_from([ + "killswitch", + "patch-kernel", + "--dry-run", + "--kev-only", + "--min-cvss", + "7.5", + "--cpe", + "cpe:2.3:o:microsoft:windows_11_23h2:*:*:*:*:*:*:*:*", + "--apply", + ]) + .expect("Failed to parse patch-kernel subcommand"); + + match cli.command { + Some(Commands::PatchKernel { + dry_run, + kev_only, + min_cvss, + cpe, + apply, + }) => { + assert!(dry_run); + assert!(kev_only); + assert_eq!(min_cvss, Some(7.5)); + assert_eq!( + cpe.as_deref(), + Some("cpe:2.3:o:microsoft:windows_11_23h2:*:*:*:*:*:*:*:*") + ); + assert!(apply); + } + other => panic!("Expected Commands::PatchKernel, got {:?}", other), + } + } + + #[test] + fn test_patch_kernel_secret_hygiene_no_nvd_api_key_flag() { + // Assert that passing --nvd-api-key is rejected as an unrecognized argument + let res = Cli::try_parse_from([ + "killswitch", + "patch-kernel", + "--nvd-api-key", + "secret_test_key", + ]); + assert!(res.is_err(), "Expected error for --nvd-api-key CLI flag"); + let err_msg = res.unwrap_err().to_string(); + assert!( + err_msg.contains("unexpected argument") + || err_msg.contains("not recognized") + || err_msg.contains("--nvd-api-key") + ); + } +} diff --git a/crates/killswitch-cli/src/commands/mod.rs b/crates/killswitch-cli/src/commands/mod.rs index 05047a5..92e6e9f 100644 --- a/crates/killswitch-cli/src/commands/mod.rs +++ b/crates/killswitch-cli/src/commands/mod.rs @@ -4,6 +4,9 @@ use crate::client::KillSwitchClient; use crate::verify::SubsystemVerifier; use anyhow::{bail, Result}; +pub mod patch_kernel; +pub use patch_kernel::handle_patch_kernel; + pub async fn handle_status(client: &KillSwitchClient) -> Result<()> { let status = client.get_status().await?; println!("\n================================================================================"); diff --git a/crates/killswitch-cli/src/commands/patch_kernel.rs b/crates/killswitch-cli/src/commands/patch_kernel.rs new file mode 100644 index 0000000..dcdf78f --- /dev/null +++ b/crates/killswitch-cli/src/commands/patch_kernel.rs @@ -0,0 +1,172 @@ +//! # OS Kernel Vulnerability Scanning & Native Patch Orchestration CLI Handler + +use anyhow::Result; +use killswitch_kernel_patcher::{ + is_elevated, HostKernelInfo, KernelPatcher, PatcherError, ScanOptions, +}; + +/// Handles the `killswitch patch-kernel` CLI subcommand. +/// +/// Discovers the running OS kernel, queries the NVD API 2.0 for matching CVEs / CISA KEV entries, +/// formats structured findings, and optionally invokes OS-native kernel patch workflows. +/// +/// # Secret Hygiene Invariant +/// `NVD_API_KEY` is NEVER accepted as a CLI parameter (preventing OS process-table leaks). +/// It is read strictly from `std::env::var("NVD_API_KEY")`. +pub async fn handle_patch_kernel( + dry_run: bool, + kev_only: bool, + min_cvss: Option, + cpe: Option, + apply: bool, +) -> Result<()> { + // 1. Host Kernel Discovery + let host_info = match HostKernelInfo::detect_host_kernel() { + Ok(info) => info, + Err(e) => { + eprintln!("❌ Host kernel detection failed: {}", e); + return Err(e.into()); + } + }; + + let target_cpe = cpe.unwrap_or_else(|| host_info.cpe23.clone()); + let has_env_key = std::env::var("NVD_API_KEY").is_ok(); + + println!("\n================================================================================"); + println!("🛡️ HOST KERNEL DISCOVERY & NVD VULNERABILITY SCANNER"); + println!("================================================================================"); + println!(" OS Family: {}", host_info.os_family); + println!(" OS Version: {}", host_info.os_version); + println!(" Kernel Release: {}", host_info.kernel_release); + println!(" Architecture: {}", host_info.architecture); + println!(" Target CPE 2.3: {}", target_cpe); + println!( + " NVD API Key: {}", + if has_env_key { + "Configured via NVD_API_KEY environment variable" + } else { + "None (public rate-limited mode)" + } + ); + if kev_only { + println!(" Filter Mode: CISA KEV Only"); + } + if let Some(cvss) = min_cvss { + println!(" Min CVSS Score: {:.1}", cvss); + } + println!("================================================================================\n"); + + // 2. Vulnerability Scan against NVD API 2.0 + println!( + "🔍 Querying NVD API 2.0 for kernel vulnerabilities affecting '{}'...", + target_cpe + ); + + let options = ScanOptions { + cpe: Some(target_cpe.clone()), + min_cvss_score: min_cvss, + kev_only, + api_key: std::env::var("NVD_API_KEY").ok(), + timeout_secs: 30, + }; + + let patcher = KernelPatcher::new(); + match patcher.scan_kernel_vulnerabilities(&options).await { + Ok(vulns) => { + if vulns.is_empty() { + println!("✅ Zero vulnerabilities found matching the specified criteria."); + } else { + let kev_count = vulns.iter().filter(|v| v.is_cisa_kev).count(); + println!( + "\n⚠️ Found {} vulnerabilities affecting target kernel ({} CISA KEV):\n", + vulns.len(), + kev_count + ); + for v in &vulns { + println!("--------------------------------------------------------------------------------"); + let score_str = match v.cvss_v31_score { + Some(score) => format!("{:.1}", score), + None => "N/A".to_string(), + }; + let sev_str = v.cvss_v31_severity.as_deref().unwrap_or("UNKNOWN"); + + if v.is_cisa_kev { + println!( + "🚨 [CISA KEV] {} | CVSS v3.1: {} ({})", + v.cve_id, score_str, sev_str + ); + if let Some(ref name) = v.cisa_vulnerability_name { + println!(" Vulnerability Name: {}", name); + } + if let Some(ref added) = v.cisa_exploit_add { + println!(" Added to KEV: {}", added); + } + if let Some(ref due) = v.cisa_action_due { + println!(" Remediation Due: {}", due); + } + if let Some(ref action) = v.cisa_required_action { + println!(" Required Action: {}", action); + } + } else { + println!("⚠️ {} | CVSS v3.1: {} ({})", v.cve_id, score_str, sev_str); + } + if !v.description.is_empty() { + println!(" Description: {}", v.description); + } + } + println!("--------------------------------------------------------------------------------\n"); + } + } + Err(PatcherError::RateLimited) => { + eprintln!("⚠️ Rate limited by NIST NVD API 2.0. Set the NVD_API_KEY environment variable to increase NIST rate limits."); + } + Err(e) => { + eprintln!("⚠️ NVD vulnerability scan query notice: {}", e); + } + } + + // 3. Patch Orchestration + let should_patch = apply || dry_run; + if should_patch { + let is_dry_run = dry_run || !apply; + println!("🔧 Orchestrating native OS kernel patch workflow..."); + if is_dry_run { + println!(" [DRY-RUN SIMULATION - No kernel or OS changes will be applied]"); + } else if !is_elevated() { + eprintln!("❌ Insufficient privileges: OS-native kernel patch execution requires Administrator/root privileges."); + return Err(PatcherError::InsufficientPrivileges.into()); + } + + let exec_result = patcher.apply_os_kernel_patch(is_dry_run).await?; + println!( + "\n================================================================================" + ); + println!("🛡️ NATIVE KERNEL PATCH ORCHESTRATION RESULT"); + println!( + "================================================================================" + ); + println!(" Target Subsystem: {}", exec_result.os_subsystem); + println!( + " Mode: {}", + if exec_result.dry_run { + "Dry-Run Simulation" + } else { + "Live Execution" + } + ); + println!( + " Command: {} {}", + exec_result.command, + exec_result.args.join(" ") + ); + println!(" Success: {}", exec_result.success); + println!(" Output:\n{}", exec_result.output); + println!( + "================================================================================\n" + ); + } else { + println!("💡 Tip: Pass '--apply --dry-run' (or '--dry-run') to preview OS-native patch command, or '--apply' with elevated privileges to execute.\n"); + } + + Ok(()) +} diff --git a/crates/killswitch-cli/src/verify.rs b/crates/killswitch-cli/src/verify.rs index 3b98606..55be482 100644 --- a/crates/killswitch-cli/src/verify.rs +++ b/crates/killswitch-cli/src/verify.rs @@ -97,10 +97,22 @@ impl SubsystemVerifier { /// Executes subsystem diagnostics, optionally including Phase 8 (CAGE Governance). pub async fn run_with_governance(cage_governance: bool) -> Result { + struct SelfDiagnosticGuard { + had_env: bool, + } + impl Drop for SelfDiagnosticGuard { + fn drop(&mut self) { + killswitch_core::wfp::set_in_process_self_diagnostic(false); + if !self.had_env { + std::env::remove_var("KILLSWITCH_SELF_DIAGNOSTIC"); + } + } + } + let had_env = std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok(); + killswitch_core::wfp::set_in_process_self_diagnostic(true); std::env::set_var("KILLSWITCH_SELF_DIAGNOSTIC", "1"); - let res = Self::run_with_governance_inner(cage_governance).await; - std::env::remove_var("KILLSWITCH_SELF_DIAGNOSTIC"); - res + let _guard = SelfDiagnosticGuard { had_env }; + Self::run_with_governance_inner(cage_governance).await } async fn run_with_governance_inner(cage_governance: bool) -> Result { diff --git a/crates/killswitch-core/src/agent_registry.rs b/crates/killswitch-core/src/agent_registry.rs index 5649cf0..edc5acd 100644 --- a/crates/killswitch-core/src/agent_registry.rs +++ b/crates/killswitch-core/src/agent_registry.rs @@ -358,14 +358,19 @@ impl TrackedAgentTreeRegistry { self.cache_tainted_descendant(pid, parent_pid, &resolved_name, depth + 1); return AgentLineageClass::ConfirmedThreatSubtree; } - if let Some(ancestor_taint) = self.tainted_descendants.get(&parent_pid) { - let anchor = ancestor_taint.root_pid; + // Drop the DashMap read guard immediately before cache_tainted_descendant() writes back + // into tainted_descendants, preventing same-shard RwLock self-deadlock on child chains. + let ancestor_taint_info = self + .tainted_descendants + .get(&parent_pid) + .map(|t| (t.root_pid, t.depth_from_root)); + if let Some((anchor, anchor_depth)) = ancestor_taint_info { if self.tracked_roots.contains_key(&anchor) { self.cache_tainted_descendant( pid, anchor, &resolved_name, - ancestor_taint.depth_from_root + depth + 1, + anchor_depth + depth + 1, ); return AgentLineageClass::TaintedAgentDescendant; } @@ -374,7 +379,7 @@ impl TrackedAgentTreeRegistry { pid, anchor, &resolved_name, - ancestor_taint.depth_from_root + depth + 1, + anchor_depth + depth + 1, ); return AgentLineageClass::ConfirmedThreatSubtree; } @@ -908,4 +913,30 @@ mod tests { assert!(!reg.mark_confirmed_threat(std::process::id(), "self")); assert!(!reg.is_tracked_pid(std::process::id())); } + + #[test] + fn test_tainted_descendant_cache_propagation_no_same_shard_deadlock() { + let reg = TrackedAgentTreeRegistry::new(); + let sys = System::new(); + let root_pid = 940_000; + let tainted_parent = 940_001; + assert!(reg.register_agent_root(root_pid, "agent-root")); + assert!(reg.register_child(tainted_parent, root_pid)); + assert_eq!( + reg.classify_pid_with_system(tainted_parent, Some("bash"), &[], &sys), + AgentLineageClass::TaintedAgentDescendant + ); + + // Pigeonhole principle: fan out >256 child PIDs from the same cached + // tainted parent via extra_edges so at least one child guarantees a + // DashMap shard collision with tainted_parent across <=64-CPU hosts. + for offset in 2u32..=320u32 { + let child_pid = root_pid + offset; + let edges = [(tainted_parent, child_pid)]; + assert_eq!( + reg.classify_pid_with_system(child_pid, Some("sh"), &edges, &sys), + AgentLineageClass::TaintedAgentDescendant + ); + } + } } diff --git a/crates/killswitch-core/src/exec_sensor.rs b/crates/killswitch-core/src/exec_sensor.rs index 7900a07..f817cd5 100644 --- a/crates/killswitch-core/src/exec_sensor.rs +++ b/crates/killswitch-core/src/exec_sensor.rs @@ -13,12 +13,16 @@ use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +#[cfg(not(target_os = "macos"))] +use std::time::Duration; +use std::time::{SystemTime, UNIX_EPOCH}; use killswitch_types::KillSwitchError; use parking_lot::RwLock; use serde::{Deserialize, Serialize}; -use tracing::{debug, info}; +#[cfg(not(target_os = "macos"))] +use tracing::debug; +use tracing::info; /// Default maximum entries stored in the in-memory execution sensor FIFO ring buffer. pub const EXEC_SENSOR_DEFAULT_CAPACITY: usize = 2048; @@ -543,6 +547,9 @@ impl NativeProcessSensor for MacOsProcessSensor { fn stop(&self) { self.running.store(false, Ordering::SeqCst); + if let Some(handle) = self.worker_handle.lock().take() { + let _ = handle.join(); + } } fn is_running(&self) -> bool { diff --git a/crates/killswitch-core/src/job_sandbox.rs b/crates/killswitch-core/src/job_sandbox.rs index 82992cd..bbe5db9 100644 --- a/crates/killswitch-core/src/job_sandbox.rs +++ b/crates/killswitch-core/src/job_sandbox.rs @@ -16,10 +16,12 @@ use crate::freeze::NativeProcessFreezer; use crate::killchain::{is_critical_system_pid, is_immutable_os_kernel_pid}; use killswitch_types::errors::{KillSwitchError, KillSwitchResult}; use killswitch_types::status::{ProcessFreezer, ProcessIsolationState}; +#[cfg(any(target_os = "windows", target_os = "linux"))] use parking_lot::Mutex; use std::collections::{HashMap, HashSet, VecDeque}; use std::process::{Child, Command}; use std::sync::atomic::{AtomicU64, Ordering}; +#[cfg(any(target_os = "windows", target_os = "linux"))] use std::sync::OnceLock; use sysinfo::{Pid, ProcessRefreshKind, System}; @@ -172,6 +174,14 @@ pub fn spawn_confined_process( #[cfg(not(target_os = "windows"))] { + #[cfg(target_os = "linux")] + { + use std::os::unix::process::CommandExt; + let prepared = crate::landlock::PreparedLinuxSandbox::prepare_seccomp_only(true, false); + unsafe { + command.pre_exec(move || prepared.apply_in_pre_exec()); + } + } let child = command.spawn()?; let pid = child.id(); TrackedAgentTreeRegistry::global().register_agent_root_with_sandbox( @@ -344,6 +354,10 @@ pub fn freeze_subtree_kernel( freezer: &dyn ProcessFreezer, ) -> SubtreeFreezeReport { let root_pid = *seed_pids.first().unwrap_or(&0); + #[cfg_attr( + not(any(target_os = "windows", target_os = "linux")), + allow(unused_mut) + )] let mut kernel_mechanism: &'static str = { #[cfg(target_os = "windows")] { @@ -363,6 +377,10 @@ pub fn freeze_subtree_kernel( } }; + #[cfg_attr( + not(any(target_os = "windows", target_os = "linux")), + allow(unused_mut) + )] let mut job_bound_pids = Vec::new(); #[cfg(target_os = "windows")] @@ -965,6 +983,772 @@ impl Drop for WindowsJobSandbox { } } +// ============================================================================= +// Cross-OS Capabilityless Sandbox Launch (`AppContainer` + Job / Landlock / Seatbelt) +// ============================================================================= + +/// Configuration for launching an AI agent command inside a strict OS sandbox +/// (Windows AppContainer + Job Object; Linux cgroup v2 + Landlock + seccomp; macOS Seatbelt). +#[derive(Debug, Clone)] +pub struct SandboxedAgentConfig { + pub agent_id: String, + pub program: String, + pub args: Vec, + pub current_dir: Option, + pub readable_paths: Vec, + pub writable_paths: Vec, + pub active_process_limit: Option, + pub allow_network: bool, + pub kill_on_close: bool, +} + +impl SandboxedAgentConfig { + pub fn new(agent_id: impl Into, program: impl Into) -> Self { + Self { + agent_id: agent_id.into(), + program: program.into(), + args: Vec::new(), + current_dir: None, + readable_paths: Vec::new(), + writable_paths: Vec::new(), + active_process_limit: None, + allow_network: false, + kill_on_close: true, + } + } +} + +/// Live confined AI agent root handle returned by `spawn_sandboxed_agent_process`. +pub struct SandboxedAgentProcess { + pub pid: u32, + pub sandbox_id: String, + pub isolation_mode: &'static str, + pub is_appcontainer: bool, + #[cfg(target_os = "windows")] + process_handle_raw: usize, + #[cfg(target_os = "windows")] + appcontainer_profile: Option, + #[cfg(target_os = "windows")] + job: Option, + #[cfg(not(target_os = "windows"))] + child: Option, + #[cfg(target_os = "linux")] + cgroup: Option, +} + +impl SandboxedAgentProcess { + #[inline] + pub fn pid(&self) -> u32 { + self.pid + } + + pub fn member_pids(&self) -> KillSwitchResult> { + #[cfg(target_os = "windows")] + if let Some(ref job) = self.job { + let mut pids = job.member_pids()?; + for p in enumerate_live_descendants(self.pid) { + if !pids.contains(&p) { + pids.push(p); + } + } + return Ok(pids); + } + #[cfg(target_os = "linux")] + if let Some(ref cg) = self.cgroup { + let mut pids = cg.member_pids().unwrap_or_default(); + for p in enumerate_live_descendants(self.pid) { + if !pids.contains(&p) { + pids.push(p); + } + } + return Ok(pids); + } + Ok(enumerate_live_descendants(self.pid)) + } + + /// Terminates the confined agent process tree atomically and reclaims sandbox profiles. + pub fn terminate(&mut self, exit_code: u32) -> KillSwitchResult<()> { + #[cfg(target_os = "windows")] + { + use windows::core::PCWSTR; + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::Security::Isolation::DeleteAppContainerProfile; + use windows::Win32::System::Threading::{TerminateProcess, WaitForSingleObject}; + + let res = if let Some(ref job) = self.job { + job.terminate(exit_code) + } else { + Ok(()) + }; + if self.process_handle_raw != 0 { + let h_proc = HANDLE(self.process_handle_raw as *mut core::ffi::c_void); + unsafe { + let _ = TerminateProcess(h_proc, exit_code); + let _ = WaitForSingleObject(h_proc, 2000); + let _ = CloseHandle(h_proc); + } + self.process_handle_raw = 0; + } + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + if let Some(profile) = self.appcontainer_profile.take() { + let w_name: Vec = profile.encode_utf16().chain(std::iter::once(0)).collect(); + unsafe { + let _ = DeleteAppContainerProfile(PCWSTR(w_name.as_ptr())); + } + } + res + } + #[cfg(not(target_os = "windows"))] + { + #[cfg(target_os = "linux")] + if let Some(ref cg) = self.cgroup { + let _ = cg.terminate(); + } + let _ = exit_code; + for pid in enumerate_live_descendants(self.pid).into_iter().rev() { + if pid != self.pid { + #[cfg(unix)] + unsafe { + let _ = libc::kill(pid as libc::pid_t, libc::SIGKILL); + } + } + } + if let Some(ref mut child) = self.child { + let _ = child.kill(); + let _ = child.wait(); + } + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + Ok(()) + } + } + + /// Waits for the sandboxed root process to exit and returns its OS exit code. + pub fn wait_exit_code(&mut self) -> KillSwitchResult { + #[cfg(target_os = "windows")] + { + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::System::Threading::{ + GetExitCodeProcess, WaitForSingleObject, INFINITE, + }; + if self.process_handle_raw == 0 { + return Err(KillSwitchError::NativeOsError( + "Sandboxed Windows process handle already closed".to_string(), + )); + } + let h_proc = HANDLE(self.process_handle_raw as *mut core::ffi::c_void); + unsafe { + let _ = WaitForSingleObject(h_proc, INFINITE); + let mut code: u32 = 1; + let _ = GetExitCodeProcess(h_proc, &mut code); + let _ = CloseHandle(h_proc); + self.process_handle_raw = 0; + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + Ok(code as i32) + } + } + #[cfg(not(target_os = "windows"))] + { + let status = if let Some(ref mut child) = self.child { + child.wait()? + } else { + return Err(KillSwitchError::NativeOsError( + "Sandboxed child handle already consumed".to_string(), + )); + }; + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt; + Ok(status + .code() + .or_else(|| status.signal().map(|sig| 128 + sig)) + .unwrap_or(1)) + } + #[cfg(not(unix))] + { + Ok(status.code().unwrap_or(1)) + } + } + } +} + +impl Drop for SandboxedAgentProcess { + fn drop(&mut self) { + #[cfg(target_os = "windows")] + { + use windows::core::PCWSTR; + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::Security::Isolation::DeleteAppContainerProfile; + use windows::Win32::System::Threading::WaitForSingleObject; + + let kill_on_close = self + .job + .as_ref() + .map(|j| j.config.kill_on_close) + .unwrap_or(false); + drop(self.job.take()); + if self.process_handle_raw != 0 { + let h_proc = HANDLE(self.process_handle_raw as *mut core::ffi::c_void); + unsafe { + if kill_on_close { + let _ = WaitForSingleObject(h_proc, 1000); + } + let _ = CloseHandle(h_proc); + } + self.process_handle_raw = 0; + } + if kill_on_close { + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + if let Some(profile) = self.appcontainer_profile.take() { + let w_name: Vec = + profile.encode_utf16().chain(std::iter::once(0)).collect(); + unsafe { + let _ = DeleteAppContainerProfile(PCWSTR(w_name.as_ptr())); + } + } + } + } + #[cfg(not(target_os = "windows"))] + { + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + } + } +} + +/// Formats a Windows `CreateProcessW` command line from `program` and `args` using +/// Win32 `CommandLineToArgvW` backslash escaping rules. +pub fn format_windows_command_line(program: &str, args: &[String]) -> String { + fn push_quoted_arg(out: &mut String, arg: &str) { + if !out.is_empty() { + out.push(' '); + } + let needs_quotes = arg.is_empty() + || arg + .chars() + .any(|c| c == ' ' || c == '\t' || c == '"' || c == '\n' || c == '\r'); + if !needs_quotes { + out.push_str(arg); + return; + } + out.push('"'); + let mut backslashes = 0usize; + for ch in arg.chars() { + match ch { + '\\' => backslashes += 1, + '"' => { + for _ in 0..(backslashes * 2 + 1) { + out.push('\\'); + } + out.push('"'); + backslashes = 0; + } + _ => { + for _ in 0..backslashes { + out.push('\\'); + } + backslashes = 0; + out.push(ch); + } + } + } + for _ in 0..(backslashes * 2) { + out.push('\\'); + } + out.push('"'); + } + + let mut cmdline = String::new(); + push_quoted_arg(&mut cmdline, program); + for a in args { + push_quoted_arg(&mut cmdline, a); + } + cmdline +} + +/// Capabilityless Windows AppContainer + Job Object sandbox. +/// +/// Launches children with: +/// - Zero AppContainer capabilities (`Capabilities = NULL, CapabilityCount = 0`) blocking network/UNC/documents +/// - `EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_NO_WINDOW` +/// - Mandatory `AssignProcessToJobObject` + `IsProcessInJob == TRUE` + `TokenIsAppContainer != 0` +/// verification strictly BEFORE `ResumeThread` +/// - Automatic suspended termination, `FreeSid`, `DeleteProcThreadAttributeList`, and +/// `DeleteAppContainerProfile` rollback on any failure. +#[cfg(target_os = "windows")] +pub struct WindowsAppContainerSandbox; + +#[cfg(target_os = "windows")] +impl WindowsAppContainerSandbox { + fn sanitize_profile_name(sandbox_id: &str) -> String { + let cleaned: String = sandbox_id + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_' || *c == '.') + .collect(); + let raw = format!("ks.ac.{cleaned}"); + if raw.len() > 64 { + raw[..64].to_string() + } else { + raw + } + } + + pub fn spawn( + config: &SandboxedAgentConfig, + sandbox_id: &str, + ) -> KillSwitchResult { + use windows::core::{PCWSTR, PWSTR}; + use windows::Win32::Foundation::{CloseHandle, BOOL, HANDLE}; + use windows::Win32::Security::Isolation::{ + CreateAppContainerProfile, DeleteAppContainerProfile, + DeriveAppContainerSidFromAppContainerName, + }; + use windows::Win32::Security::{ + FreeSid, GetTokenInformation, TokenIsAppContainer, PSID, SECURITY_CAPABILITIES, + TOKEN_QUERY, + }; + use windows::Win32::System::JobObjects::{AssignProcessToJobObject, IsProcessInJob}; + use windows::Win32::System::Threading::{ + CreateProcessW, DeleteProcThreadAttributeList, InitializeProcThreadAttributeList, + OpenProcessToken, ResumeThread, TerminateProcess, UpdateProcThreadAttribute, + CREATE_NO_WINDOW, CREATE_SUSPENDED, EXTENDED_STARTUPINFO_PRESENT, + LPPROC_THREAD_ATTRIBUTE_LIST, PROCESS_INFORMATION, + PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, STARTUPINFOEXW, + }; + + if config.allow_network { + tracing::warn!( + agent_id = %config.agent_id, + "AppContainer sandbox ignores allow_network=true and enforces zero-capability isolation" + ); + } + + let profile_name = Self::sanitize_profile_name(sandbox_id); + let w_profile: Vec = profile_name + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let w_display: Vec = format!("KillSwitch Sandbox ({})", config.agent_id) + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let w_desc: Vec = "KillSwitch Zero-Capability Agent AppContainer\0" + .encode_utf16() + .collect(); + + struct ProfileRollbackGuard { + w_profile: Vec, + active: bool, + } + impl Drop for ProfileRollbackGuard { + fn drop(&mut self) { + if self.active { + unsafe { + let _ = DeleteAppContainerProfile(PCWSTR(self.w_profile.as_ptr())); + } + } + } + } + + struct SidGuard(PSID); + impl Drop for SidGuard { + fn drop(&mut self) { + if !self.0 .0.is_null() { + unsafe { + let _ = FreeSid(self.0); + } + self.0 = PSID(std::ptr::null_mut()); + } + } + } + + struct AttrListGuard { + lp_attr: LPPROC_THREAD_ATTRIBUTE_LIST, + _backing: Vec, + } + impl Drop for AttrListGuard { + fn drop(&mut self) { + if !self.lp_attr.is_invalid() { + unsafe { DeleteProcThreadAttributeList(self.lp_attr) }; + self.lp_attr = LPPROC_THREAD_ATTRIBUTE_LIST(std::ptr::null_mut()); + } + } + } + + // 1. Allocate AppContainer profile & SID (fail-closed, zero uncontained fallback). + const HRESULT_ALREADY_EXISTS: i32 = 0x8007_00B7u32 as i32; + let psid = match unsafe { + CreateAppContainerProfile( + PCWSTR(w_profile.as_ptr()), + PCWSTR(w_display.as_ptr()), + PCWSTR(w_desc.as_ptr()), + None, // Zero capabilities -> capabilityless sandbox + ) + } { + Ok(sid) => sid, + Err(err) if err.code().0 == HRESULT_ALREADY_EXISTS => unsafe { + DeriveAppContainerSidFromAppContainerName(PCWSTR(w_profile.as_ptr())).map_err( + |e| { + KillSwitchError::NativeOsError(format!( + "DeriveAppContainerSidFromAppContainerName failed for '{profile_name}': {e}" + )) + }, + )? + }, + Err(err) => { + return Err(KillSwitchError::NativeOsError(format!( + "Fail-closed: CreateAppContainerProfile failed for '{profile_name}': {err}" + ))); + } + }; + + let mut profile_rollback = ProfileRollbackGuard { + w_profile, + active: true, + }; + let sid_guard = SidGuard(psid); + if sid_guard.0 .0.is_null() { + return Err(KillSwitchError::NativeOsError( + "Fail-closed: CreateAppContainerProfile returned null PSID".to_string(), + )); + } + + // 2. Create hardened Win32 Job Object BEFORE process launch. + let mut job_cfg = JobSandboxConfig::new(sandbox_id.to_string(), config.agent_id.clone()); + job_cfg.active_process_limit = config.active_process_limit; + job_cfg.kill_on_close = config.kill_on_close; + let job = WindowsJobSandbox::create(job_cfg)?; + + // 3. Allocate & populate PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES. + let mut attr_size: usize = 0; + let _ = unsafe { + InitializeProcThreadAttributeList( + LPPROC_THREAD_ATTRIBUTE_LIST(std::ptr::null_mut()), + 1, + 0, + &mut attr_size, + ) + }; + if attr_size == 0 { + return Err(KillSwitchError::NativeOsError( + "InitializeProcThreadAttributeList returned zero attribute size".to_string(), + )); + } + let words = attr_size.div_ceil(std::mem::size_of::()); + let mut backing = vec![0usize; words]; + let lp_attr = LPPROC_THREAD_ATTRIBUTE_LIST(backing.as_mut_ptr().cast()); + unsafe { InitializeProcThreadAttributeList(lp_attr, 1, 0, &mut attr_size) }.map_err( + |e| { + KillSwitchError::NativeOsError(format!( + "InitializeProcThreadAttributeList failed: {e}" + )) + }, + )?; + let attr_guard = AttrListGuard { + lp_attr, + _backing: backing, + }; + + let sec_caps = SECURITY_CAPABILITIES { + AppContainerSid: sid_guard.0, + Capabilities: std::ptr::null_mut(), + CapabilityCount: 0, + Reserved: 0, + }; + unsafe { + UpdateProcThreadAttribute( + attr_guard.lp_attr, + 0, + PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES as usize, + Some((&sec_caps as *const SECURITY_CAPABILITIES).cast()), + std::mem::size_of::(), + None, + None, + ) + } + .map_err(|e| { + KillSwitchError::NativeOsError(format!( + "UpdateProcThreadAttribute(SECURITY_CAPABILITIES) failed: {e}" + )) + })?; + + let mut si: STARTUPINFOEXW = unsafe { std::mem::zeroed() }; + si.StartupInfo.cb = std::mem::size_of::() as u32; + si.lpAttributeList = attr_guard.lp_attr; + + let cmdline = format_windows_command_line(&config.program, &config.args); + let mut w_cmdline: Vec = cmdline.encode_utf16().chain(std::iter::once(0)).collect(); + let w_cwd: Option> = config.current_dir.as_ref().map(|p| { + p.as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(std::iter::once(0)) + .collect() + }); + let cwd_pcwstr = w_cwd + .as_ref() + .map(|v| PCWSTR(v.as_ptr())) + .unwrap_or_else(PCWSTR::null); + + let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; + let spawn_res = unsafe { + CreateProcessW( + PCWSTR::null(), + PWSTR(w_cmdline.as_mut_ptr()), + None, + None, + BOOL(0), + CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, + None, + cwd_pcwstr, + &si.StartupInfo, + &mut pi, + ) + }; + // Free Win32 heap allocations (SID + attribute list) immediately once applied. + drop(attr_guard); + drop(sid_guard); + + spawn_res.map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Fail-closed: CreateProcessW in AppContainer failed for '{}': {e}", + config.program + )) + })?; + + struct SuspendedProcCleanup { + h_proc: HANDLE, + h_thread: HANDLE, + terminate_on_drop: bool, + } + impl Drop for SuspendedProcCleanup { + fn drop(&mut self) { + if self.terminate_on_drop && !self.h_proc.is_invalid() { + unsafe { + let _ = TerminateProcess(self.h_proc, 1); + } + } + if !self.h_thread.is_invalid() { + unsafe { + let _ = CloseHandle(self.h_thread); + } + self.h_thread = HANDLE(std::ptr::null_mut()); + } + if self.terminate_on_drop && !self.h_proc.is_invalid() { + unsafe { + let _ = CloseHandle(self.h_proc); + } + self.h_proc = HANDLE(std::ptr::null_mut()); + } + } + } + + let mut proc_cleanup = SuspendedProcCleanup { + h_proc: pi.hProcess, + h_thread: pi.hThread, + terminate_on_drop: true, + }; + let pid = pi.dwProcessId; + + // 4. Pre-ResumeThread Job Object binding & IsProcessInJob verification. + unsafe { AssignProcessToJobObject(job.handle(), pi.hProcess) }.map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Fail-closed: AssignProcessToJobObject failed for AppContainer PID {pid}: {e}" + )) + })?; + + let mut in_job = BOOL(0); + unsafe { IsProcessInJob(pi.hProcess, job.handle(), &mut in_job) }.map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Fail-closed: IsProcessInJob failed for AppContainer PID {pid}: {e}" + )) + })?; + if !in_job.as_bool() { + return Err(KillSwitchError::NativeOsError(format!( + "Fail-closed: AppContainer PID {pid} failed IsProcessInJob before ResumeThread" + ))); + } + + // 5. Verify kernel token is genuinely AppContainer-confined BEFORE ResumeThread. + let mut h_token = HANDLE(std::ptr::null_mut()); + unsafe { OpenProcessToken(pi.hProcess, TOKEN_QUERY, &mut h_token) }.map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Fail-closed: OpenProcessToken failed for PID {pid}: {e}" + )) + })?; + let mut is_ac: u32 = 0; + let mut ret_len: u32 = 0; + let tok_res = unsafe { + GetTokenInformation( + h_token, + TokenIsAppContainer, + Some((&mut is_ac as *mut u32).cast()), + std::mem::size_of::() as u32, + &mut ret_len, + ) + }; + unsafe { + let _ = CloseHandle(h_token); + } + tok_res.map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Fail-closed: GetTokenInformation(TokenIsAppContainer) failed for PID {pid}: {e}" + )) + })?; + if is_ac == 0 { + return Err(KillSwitchError::NativeOsError(format!( + "Fail-closed: PID {pid} token reported TokenIsAppContainer == 0 before ResumeThread" + ))); + } + + // 6. Register PID cleanly before resuming execution. + TrackedAgentTreeRegistry::global().register_agent_root_with_sandbox( + pid, + config.agent_id.clone(), + config.agent_id.clone(), + Some(sandbox_id.to_string()), + ); + + let prev_suspend = unsafe { ResumeThread(pi.hThread) }; + if prev_suspend == u32::MAX { + TrackedAgentTreeRegistry::global().unregister_pid(pid); + return Err(KillSwitchError::NativeOsError(format!( + "Fail-closed: ResumeThread failed for AppContainer PID {pid}" + ))); + } + + // Transfer ownership cleanly: h_thread closes via Drop, h_proc stays open on SandboxedAgentProcess. + proc_cleanup.terminate_on_drop = false; + drop(proc_cleanup); + profile_rollback.active = false; + + Ok(SandboxedAgentProcess { + pid, + sandbox_id: sandbox_id.to_string(), + isolation_mode: "win32_appcontainer_job_object", + is_appcontainer: true, + process_handle_raw: pi.hProcess.0 as usize, + appcontainer_profile: Some(profile_name), + job: Some(job), + }) + } +} + +/// Cross-OS kernel-confined agent launch entrypoint: +/// - Windows: capabilityless AppContainer + Job Object (`EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED`) +/// - Linux: cgroup v2 + fail-closed Landlock LSM + `PR_SET_NO_NEW_PRIVS` + `seccomp-bpf` (WS4.2) +/// - macOS: Darwin SBPL `sandbox-exec` wrapper + descendant tracking (WS4.3) +pub fn spawn_sandboxed_agent_process( + config: SandboxedAgentConfig, +) -> KillSwitchResult { + let seq = SANDBOX_SEQ.fetch_add(1, Ordering::Relaxed); + let sandbox_id = format!("ks-sandbox-{seq}"); + + #[cfg(target_os = "windows")] + { + WindowsAppContainerSandbox::spawn(&config, &sandbox_id) + } + + #[cfg(not(target_os = "windows"))] + { + #[cfg(target_os = "macos")] + let mut cmd = { + let sbpl = crate::pf::generate_macos_seatbelt_profile(&config); + let resolved_prog = crate::pf::resolve_macos_program_path(&config.program); + let mut c = Command::new("/usr/bin/sandbox-exec"); + c.arg("-p").arg(sbpl).arg(resolved_prog).args(&config.args); + c + }; + #[cfg(not(target_os = "macos"))] + let mut cmd = { + let mut c = Command::new(&config.program); + c.args(&config.args); + c + }; + if let Some(ref cwd) = config.current_dir { + cmd.current_dir(cwd); + } + + #[cfg(target_os = "linux")] + { + use std::os::unix::process::CommandExt; + use std::path::{Path, PathBuf}; + + let mut read_only = vec![ + PathBuf::from("/usr"), + PathBuf::from("/bin"), + PathBuf::from("/sbin"), + PathBuf::from("/lib"), + PathBuf::from("/lib64"), + PathBuf::from("/lib32"), + PathBuf::from("/etc"), + PathBuf::from("/dev/null"), + PathBuf::from("/dev/zero"), + PathBuf::from("/dev/urandom"), + ]; + for r in &config.readable_paths { + read_only.push(r.clone()); + } + let prog_path = Path::new(&config.program); + if prog_path.is_absolute() && prog_path.exists() { + read_only.push(prog_path.to_path_buf()); + } + if let Some(ref cwd) = config.current_dir { + if !config.writable_paths.contains(cwd) { + read_only.push(cwd.clone()); + } + } + let ll_cfg = crate::landlock::LandlockSandboxConfig { + read_only_paths: read_only, + read_write_paths: config.writable_paths.clone(), + allowed_tcp_ports: Vec::new(), + strict: true, + }; + let prepared = + crate::landlock::PreparedLinuxSandbox::prepare(&ll_cfg, config.allow_network)?; + unsafe { + cmd.pre_exec(move || prepared.apply_in_pre_exec()); + } + } + + let child = cmd.spawn()?; + let pid = child.id(); + TrackedAgentTreeRegistry::global().register_agent_root_with_sandbox( + pid, + config.agent_id.clone(), + config.agent_id.clone(), + Some(sandbox_id.clone()), + ); + #[cfg(target_os = "linux")] + let cgroup = { + let mut cg_cfg = JobSandboxConfig::new(sandbox_id.clone(), config.agent_id.clone()); + cg_cfg.active_process_limit = config.active_process_limit; + cg_cfg.kill_on_close = config.kill_on_close; + match LinuxCgroupSandbox::create(cg_cfg) { + Ok(cg) => { + let _ = cg.attach_existing_pid(pid); + Some(cg) + } + Err(_) => None, + } + }; + #[cfg(target_os = "linux")] + let isolation_mode = "linux_cgroup_landlock_seccomp"; + #[cfg(target_os = "macos")] + let isolation_mode = "macos_seatbelt_sandbox"; + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + let isolation_mode = "unix_confined_subtree"; + Ok(SandboxedAgentProcess { + pid, + sandbox_id, + isolation_mode, + is_appcontainer: false, + child: Some(child), + #[cfg(target_os = "linux")] + cgroup, + }) + } +} + // ============================================================================= // Linux cgroups v2 Sandbox // ============================================================================= @@ -1269,4 +2053,179 @@ mod tests { } TrackedAgentTreeRegistry::global().unregister_pid(root_pid); } + + #[cfg(target_os = "windows")] + #[test] + fn test_windows_appcontainer_sandbox_confines_and_rolls_back_cleanly() { + let mut cfg = SandboxedAgentConfig::new("test-ac-agent", "cmd.exe"); + cfg.args = vec!["/C".to_string(), "ping -n 25 127.0.0.1 >nul".to_string()]; + cfg.active_process_limit = Some(8); + + let mut proc_handle = spawn_sandboxed_agent_process(cfg) + .expect("Windows AppContainer spawn must confine cmd.exe inside Job Object"); + assert!(proc_handle.is_appcontainer); + assert_eq!(proc_handle.isolation_mode, "win32_appcontainer_job_object"); + assert!(proc_handle.pid() > 4); + + let members = proc_handle.member_pids().unwrap_or_default(); + assert!( + members.contains(&proc_handle.pid()), + "AppContainer PID {} must be bound in Job Object: {:?}", + proc_handle.pid(), + members + ); + + proc_handle + .terminate(0) + .expect("AppContainer sandbox termination & profile cleanup must succeed"); + + // Verify fail-closed cleanup on failed CreateProcessW launch + let mut bad_cfg = SandboxedAgentConfig::new( + "test-ac-fail", + r"C:\NonExistent\KillSwitch\no_such_agent_binary_12345.exe", + ); + bad_cfg.args = vec!["--help".to_string()]; + let err = spawn_sandboxed_agent_process(bad_cfg); + assert!(err.is_err(), "Nonexistent binary must fail closed"); + } + + #[cfg(target_os = "linux")] + #[test] + fn test_linux_sandboxed_agent_enforces_landlock_and_seccomp_bpf() { + let base = std::env::temp_dir().join(format!("ks-linux-ll-{}", std::process::id())); + let allowed_dir = base.join("allowed"); + let forbidden_dir = base.join("forbidden"); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&allowed_dir).unwrap(); + std::fs::create_dir_all(&forbidden_dir).unwrap(); + + // 1. Write inside explicit writable_paths succeeds + let allowed_file = allowed_dir.join("ok.txt"); + let mut ok_cfg = SandboxedAgentConfig::new("test-ll-ok", "sh"); + ok_cfg.args = vec![ + "-c".to_string(), + format!("printf confined > '{}'", allowed_file.display()), + ]; + ok_cfg.writable_paths = vec![allowed_dir.clone()]; + let mut ok_proc = spawn_sandboxed_agent_process(ok_cfg) + .expect("Linux Landlock + seccomp spawn must succeed"); + assert_eq!(ok_proc.isolation_mode, "linux_cgroup_landlock_seccomp"); + let code = ok_proc.wait_exit_code().unwrap(); + assert_eq!(code, 0, "Write inside allowed Landlock path must succeed"); + assert_eq!(std::fs::read_to_string(&allowed_file).unwrap(), "confined"); + + // 2. Write outside writable_paths (forbidden sibling dir) fails closed with EACCES + let escape_file = forbidden_dir.join("escape.txt"); + let mut deny_cfg = SandboxedAgentConfig::new("test-ll-deny", "sh"); + deny_cfg.args = vec![ + "-c".to_string(), + format!("printf escaped > '{}' 2>/dev/null", escape_file.display()), + ]; + deny_cfg.writable_paths = vec![allowed_dir.clone()]; + let mut deny_proc = spawn_sandboxed_agent_process(deny_cfg).unwrap(); + let deny_code = deny_proc.wait_exit_code().unwrap(); + assert_ne!( + deny_code, 0, + "Write outside Landlock writable_paths must fail" + ); + assert!( + !escape_file.exists(), + "Forbidden escape file must not exist" + ); + + // 3. Seccomp-BPF blocks unshare breakout + AF_INET sockets when allow_network == false + if std::path::Path::new("/usr/bin/python3").exists() { + let mut net_cfg = SandboxedAgentConfig::new("test-seccomp-net", "/usr/bin/python3"); + net_cfg.args = vec![ + "-c".to_string(), + "import errno, socket, sys\ntry:\n socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sys.exit(2)\nexcept OSError as e:\n sys.exit(0 if e.errno == errno.EPERM else 3)".to_string(), + ]; + let mut net_proc = spawn_sandboxed_agent_process(net_cfg).unwrap(); + assert_eq!( + net_proc.wait_exit_code().unwrap(), + 0, + "Seccomp-BPF must reject socket(AF_INET) with EPERM" + ); + } + + let _ = std::fs::remove_dir_all(&base); + } + + #[cfg(target_os = "macos")] + #[test] + fn test_macos_sandboxed_agent_enforces_seatbelt_isolation() { + let base = std::env::temp_dir().join(format!("ks-macos-sb-{}", std::process::id())); + let allowed_dir = base.join("allowed"); + let forbidden_dir = base.join("forbidden"); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&allowed_dir).unwrap(); + std::fs::create_dir_all(&forbidden_dir).unwrap(); + + let allowed_file = allowed_dir.join("ok.txt"); + let mut ok_cfg = SandboxedAgentConfig::new("test-sb-ok", "sh"); + ok_cfg.current_dir = Some(allowed_dir.clone()); + ok_cfg.args = vec![ + "-c".to_string(), + format!("printf confined > '{}'", allowed_file.display()), + ]; + ok_cfg.writable_paths = vec![allowed_dir.clone()]; + let mut ok_proc = + spawn_sandboxed_agent_process(ok_cfg).expect("macOS Seatbelt spawn must succeed"); + assert_eq!(ok_proc.isolation_mode, "macos_seatbelt_sandbox"); + assert_eq!(ok_proc.wait_exit_code().unwrap(), 0); + assert_eq!(std::fs::read_to_string(&allowed_file).unwrap(), "confined"); + + let escape_file = forbidden_dir.join("escape.txt"); + let mut deny_cfg = SandboxedAgentConfig::new("test-sb-deny", "sh"); + deny_cfg.current_dir = Some(allowed_dir.clone()); + deny_cfg.args = vec![ + "-c".to_string(), + format!("printf escaped > '{}' 2>/dev/null", escape_file.display()), + ]; + deny_cfg.writable_paths = vec![allowed_dir.clone()]; + let mut deny_proc = spawn_sandboxed_agent_process(deny_cfg).unwrap(); + assert_ne!(deny_proc.wait_exit_code().unwrap(), 0); + assert!(!escape_file.exists()); + + if std::path::Path::new("/usr/bin/python3").exists() { + if let Ok(listener) = std::net::TcpListener::bind("127.0.0.1:0") { + let port = listener.local_addr().unwrap().port(); + let mut net_cfg = SandboxedAgentConfig::new("test-sb-net", "/usr/bin/python3"); + net_cfg.current_dir = Some(allowed_dir.clone()); + net_cfg.readable_paths = vec![allowed_dir.clone()]; + net_cfg.args = vec![ + "-I".to_string(), + "-c".to_string(), + format!( + "import errno, socket, sys\ntry:\n s = socket.create_connection(('127.0.0.1', {port}), timeout=1)\n sys.exit(2)\nexcept OSError as e:\n sys.exit(0 if e.errno in (errno.EPERM, errno.EACCES) else 3)" + ), + ]; + let mut net_proc = spawn_sandboxed_agent_process(net_cfg).unwrap(); + assert_eq!( + net_proc.wait_exit_code().unwrap(), + 0, + "macOS Seatbelt (deny network*) must block TCP connect" + ); + drop(listener); + } + } + + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn test_format_windows_command_line_quoting() { + let cmdline = format_windows_command_line( + r"C:\Program Files\Agent\agent.exe", + &[ + "--flag".to_string(), + "value with spaces".to_string(), + r#"quoted "arg"\"#.to_string(), + ], + ); + assert_eq!( + cmdline, + r#""C:\Program Files\Agent\agent.exe" --flag "value with spaces" "quoted \"arg\"\\""# + ); + } } diff --git a/crates/killswitch-core/src/killchain.rs b/crates/killswitch-core/src/killchain.rs index f337a2b..acdaf68 100644 --- a/crates/killswitch-core/src/killchain.rs +++ b/crates/killswitch-core/src/killchain.rs @@ -278,7 +278,7 @@ impl KillChainHostManager { let mut network_receipts = Vec::new(); let active_network_rules = Vec::new(); - let mut preserved_ports = crate::wfp::discover_active_control_ports(); + let mut preserved_ports = crate::wfp::discover_firewall_bound_control_ports(); if !preserved_ports.contains(&DEFAULT_CONTROL_PORT) { preserved_ports.push(DEFAULT_CONTROL_PORT); } diff --git a/crates/killswitch-core/src/landlock.rs b/crates/killswitch-core/src/landlock.rs index 34cd161..b3145fe 100644 --- a/crates/killswitch-core/src/landlock.rs +++ b/crates/killswitch-core/src/landlock.rs @@ -5,6 +5,12 @@ //! - Raw Netlink sockets: `libc::socket(AF_NETLINK, SOCK_RAW, NETLINK_NETFILTER)`. //! - Standalone socket inspection: Pure-Rust parser for `/proc/net/tcp` and `/proc/net/tcp6`. +#[cfg(target_os = "linux")] +use crate::wfp::is_authorized_self_diagnostic; +use crate::wfp::{ + sanitize_firewall_preserved_ports, QUARANTINE_BLOCKED_DISCOVERY_PORTS, + QUARANTINE_BLOCKED_LATERAL_PORTS, QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS, +}; use killswitch_types::{ IsolationReceipt, KillSwitchError, NetworkIsolationEngine, NetworkIsolator, }; @@ -194,17 +200,31 @@ pub fn apply_landlock_sandbox(config: &LandlockSandboxConfig) -> Result<(), Kill let ruleset_fd = ruleset_fd as i32; - // Add Read-Only path rules + // Add Read-Only path rules (strict: bail on add_rule error if strict mode) for path in &config.read_only_paths { if path.exists() { - let _ = add_path_rule(ruleset_fd, path, false); + if let Err(e) = add_path_rule(ruleset_fd, path, false, abi) { + if config.strict { + unsafe { + libc::close(ruleset_fd); + } + return Err(e); + } + } } } // Add Read-Write path rules for path in &config.read_write_paths { if path.exists() { - let _ = add_path_rule(ruleset_fd, path, true); + if let Err(e) = add_path_rule(ruleset_fd, path, true, abi) { + if config.strict { + unsafe { + libc::close(ruleset_fd); + } + return Err(e); + } + } } } @@ -231,6 +251,12 @@ pub fn apply_landlock_sandbox(config: &LandlockSandboxConfig) -> Result<(), Kill let prctl_ret = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) }; if prctl_ret != 0 { let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + if config.strict { + unsafe { + libc::close(ruleset_fd); + } + return Err(KillSwitchError::LandlockRestrictSelfFailed { errno }); + } warn!("prctl(PR_SET_NO_NEW_PRIVS) returned errno {}", errno); } @@ -260,22 +286,178 @@ pub fn apply_landlock_sandbox(config: &LandlockSandboxConfig) -> Result<(), Kill } #[cfg(target_os = "linux")] -fn add_path_rule(ruleset_fd: i32, path: &Path, writable: bool) -> Result<(), KillSwitchError> { - use std::os::unix::io::AsRawFd; - let file = std::fs::File::open(path).map_err(|e| KillSwitchError::LandlockAddRuleFailed { - path: path.to_path_buf(), - errno: e.raw_os_error().unwrap_or(0), - })?; +fn build_landlock_ruleset_fd( + config: &LandlockSandboxConfig, + enforce_net: bool, +) -> Result, KillSwitchError> { + let abi = match get_landlock_abi_version() { + Ok(v) => v, + Err(e) => { + if config.strict { + return Err(e); + } + return Ok(None); + } + }; - let read_access = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR; - let write_access = read_access + let mut fs_flags = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE + | LANDLOCK_ACCESS_FS_READ_FILE + | LANDLOCK_ACCESS_FS_READ_DIR | LANDLOCK_ACCESS_FS_REMOVE_DIR | LANDLOCK_ACCESS_FS_REMOVE_FILE + | LANDLOCK_ACCESS_FS_MAKE_CHAR + | LANDLOCK_ACCESS_FS_MAKE_DIR | LANDLOCK_ACCESS_FS_MAKE_REG - | LANDLOCK_ACCESS_FS_MAKE_DIR; + | LANDLOCK_ACCESS_FS_MAKE_SOCK + | LANDLOCK_ACCESS_FS_MAKE_FIFO + | LANDLOCK_ACCESS_FS_MAKE_BLOCK + | LANDLOCK_ACCESS_FS_MAKE_SYM; + + if abi >= 2 { + fs_flags |= LANDLOCK_ACCESS_FS_REFER; + } + if abi >= 3 { + fs_flags |= LANDLOCK_ACCESS_FS_TRUNCATE; + } + + let net_flags = if abi >= 4 && enforce_net { + LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP + } else { + 0 + }; + + let attr = LandlockRulesetAttr { + handled_access_fs: fs_flags, + handled_access_net: net_flags, + }; - let allowed_access = if writable { write_access } else { read_access }; + let attr_size = if abi >= 4 && enforce_net { + std::mem::size_of::() + } else { + std::mem::size_of::() + }; + + let ruleset_fd = unsafe { + libc::syscall( + SYS_LANDLOCK_CREATE_RULESET, + &attr as *const _ as *const libc::c_void, + attr_size, + 0u32, + ) + }; + if ruleset_fd < 0 { + let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + if config.strict { + return Err(KillSwitchError::LandlockRulesetCreateFailed { errno }); + } + return Ok(None); + } + + let fd = ruleset_fd as i32; + for path in &config.read_only_paths { + if path.exists() { + if let Err(e) = add_path_rule(fd, path, false, abi) { + if config.strict { + unsafe { + libc::close(fd); + } + return Err(e); + } + } + } + } + for path in &config.read_write_paths { + if path.exists() { + if let Err(e) = add_path_rule(fd, path, true, abi) { + if config.strict { + unsafe { + libc::close(fd); + } + return Err(e); + } + } + } + } + if enforce_net && abi >= 4 { + for &port in &config.allowed_tcp_ports { + let net_attr = LandlockNetPortAttr { + allowed_access: LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP, + port: port as u64, + }; + let ret = unsafe { + libc::syscall( + SYS_LANDLOCK_ADD_RULE, + fd, + LANDLOCK_RULE_NET_PORT, + &net_attr as *const _ as *const libc::c_void, + 0u32, + ) + }; + if ret < 0 && config.strict { + let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + unsafe { + libc::close(fd); + } + return Err(KillSwitchError::LandlockAddRuleFailed { + path: PathBuf::from(format!("tcp-port:{port}")), + errno, + }); + } + } + } + Ok(Some(fd)) +} + +#[cfg(target_os = "linux")] +fn add_path_rule( + ruleset_fd: i32, + path: &Path, + writable: bool, + abi: u32, +) -> Result<(), KillSwitchError> { + use std::os::unix::io::AsRawFd; + let file = std::fs::File::open(path).map_err(|e| KillSwitchError::LandlockAddRuleFailed { + path: path.to_path_buf(), + errno: e.raw_os_error().unwrap_or(0), + })?; + let meta = file.metadata().ok(); + let is_dir = meta.as_ref().is_some_and(|m| m.is_dir()); + let is_regular_file = meta.as_ref().is_some_and(|m| m.is_file()); + + let allowed_access = if is_dir { + let mut dir_read = + LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR | LANDLOCK_ACCESS_FS_EXECUTE; + if writable { + dir_read |= LANDLOCK_ACCESS_FS_WRITE_FILE + | LANDLOCK_ACCESS_FS_REMOVE_DIR + | LANDLOCK_ACCESS_FS_REMOVE_FILE + | LANDLOCK_ACCESS_FS_MAKE_REG + | LANDLOCK_ACCESS_FS_MAKE_DIR + | LANDLOCK_ACCESS_FS_MAKE_SYM; + if abi >= 2 { + dir_read |= LANDLOCK_ACCESS_FS_REFER; + } + if abi >= 3 { + dir_read |= LANDLOCK_ACCESS_FS_TRUNCATE; + } + } + dir_read + } else { + // File/device-only flags (directory flags cause EINVAL on non-directory descriptors in Landlock; + // omit EXECUTE on character devices such as /dev/null and /dev/urandom). + let mut file_access = LANDLOCK_ACCESS_FS_READ_FILE; + if is_regular_file { + file_access |= LANDLOCK_ACCESS_FS_EXECUTE; + } + if writable { + file_access |= LANDLOCK_ACCESS_FS_WRITE_FILE; + if abi >= 3 { + file_access |= LANDLOCK_ACCESS_FS_TRUNCATE; + } + } + file_access + }; let attr = LandlockPathBeneathAttr { allowed_access, @@ -303,6 +485,283 @@ fn add_path_rule(ruleset_fd: i32, path: &Path, writable: bool) -> Result<(), Kil } } +// --------------------------------------------------------------------------- +// 1b. Pre-Fork Async-Signal-Safe Landlock + Seccomp-BPF Agent Confinement +// --------------------------------------------------------------------------- + +pub const AUDIT_ARCH_X86_64: u32 = 0xC000_003E; +pub const AUDIT_ARCH_AARCH64: u32 = 0xC000_00B7; + +pub const BPF_LD_W_ABS: u16 = 0x20; +pub const BPF_JMP_JEQ_K: u16 = 0x15; +pub const BPF_RET_K: u16 = 0x06; + +pub const SECCOMP_RET_KILL_PROCESS: u32 = 0x8000_0000; +pub const SECCOMP_RET_ERRNO_EPERM: u32 = 0x0005_0001; +pub const SECCOMP_RET_ALLOW: u32 = 0x7FFF_0000; + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SockFilter { + pub code: u16, + pub jt: u8, + pub jf: u8, + pub k: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SockFprog { + pub len: u16, + pub filter: *const SockFilter, +} + +#[inline] +const fn bpf_stmt(code: u16, k: u32) -> SockFilter { + SockFilter { + code, + jt: 0, + jf: 0, + k, + } +} + +#[inline] +const fn bpf_jump(code: u16, k: u32, jt: u8, jf: u8) -> SockFilter { + SockFilter { code, jt, jf, k } +} + +/// Builds a classical cBPF seccomp filter blocking container/namespace escape syscalls +/// (`ptrace`, `process_vm_readv/writev`, `mount`, `umount2`, `pivot_root`, `chroot`, `setns`, +/// `unshare`, `bpf`, `init_module`, `finit_module`, `kexec_load`, `io_uring_setup`, `userfaultfd`, +/// `perf_event_open`, `keyctl`) and, when `allow_network == false`, blocking non-`AF_UNIX` `socket()` +/// and `socketpair()` calls across x86_64 and aarch64. +pub fn build_agent_seccomp_bpf(allow_network: bool) -> Vec { + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + let (expected_arch, blocked_syscalls, socket_nr, socketpair_nr) = ( + AUDIT_ARCH_X86_64, + [ + libc::SYS_ptrace as u32, + libc::SYS_process_vm_readv as u32, + libc::SYS_process_vm_writev as u32, + libc::SYS_kexec_load as u32, + libc::SYS_init_module as u32, + libc::SYS_finit_module as u32, + libc::SYS_delete_module as u32, + libc::SYS_mount as u32, + libc::SYS_umount2 as u32, + libc::SYS_pivot_root as u32, + libc::SYS_chroot as u32, + libc::SYS_setns as u32, + libc::SYS_unshare as u32, + libc::SYS_bpf as u32, + libc::SYS_perf_event_open as u32, + libc::SYS_io_uring_setup as u32, + libc::SYS_userfaultfd as u32, + libc::SYS_keyctl as u32, + libc::SYS_add_key as u32, + libc::SYS_request_key as u32, + ] + .as_slice(), + libc::SYS_socket as u32, + libc::SYS_socketpair as u32, + ); + + #[cfg(all(target_os = "linux", target_arch = "aarch64"))] + let (expected_arch, blocked_syscalls, socket_nr, socketpair_nr) = ( + AUDIT_ARCH_AARCH64, + [ + libc::SYS_ptrace as u32, + libc::SYS_process_vm_readv as u32, + libc::SYS_process_vm_writev as u32, + libc::SYS_kexec_load as u32, + libc::SYS_init_module as u32, + libc::SYS_finit_module as u32, + libc::SYS_delete_module as u32, + libc::SYS_mount as u32, + libc::SYS_umount2 as u32, + libc::SYS_pivot_root as u32, + libc::SYS_chroot as u32, + libc::SYS_setns as u32, + libc::SYS_unshare as u32, + libc::SYS_bpf as u32, + libc::SYS_perf_event_open as u32, + libc::SYS_io_uring_setup as u32, + libc::SYS_userfaultfd as u32, + libc::SYS_keyctl as u32, + libc::SYS_add_key as u32, + libc::SYS_request_key as u32, + ] + .as_slice(), + libc::SYS_socket as u32, + libc::SYS_socketpair as u32, + ); + + #[cfg(not(all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + )))] + let (expected_arch, blocked_syscalls, socket_nr, socketpair_nr) = ( + AUDIT_ARCH_X86_64, + // Linux x86_64 canonical syscall numbers for deterministic cross-OS BPF verification + [ + 101u32, 310, 311, 246, 175, 313, 176, 165, 166, 155, 161, 308, 272, 321, 298, 425, 323, + 250, 248, 249, + ] + .as_slice(), + 41u32, + 53u32, + ); + + let mut prog = Vec::with_capacity(blocked_syscalls.len() + 14); + // [0..2]: Enforce exact syscall audit arch to defeat 32-bit/compat int 0x80 ABI bypass + prog.push(bpf_stmt(BPF_LD_W_ABS, 4)); + prog.push(bpf_jump(BPF_JMP_JEQ_K, expected_arch, 1, 0)); + prog.push(bpf_stmt(BPF_RET_K, SECCOMP_RET_KILL_PROCESS)); + + // [3]: Load seccomp_data.nr (offset 0) + prog.push(bpf_stmt(BPF_LD_W_ABS, 0)); + + // Placeholder indices for deny jumps; patched cleanly after trailer emission. + let mut deny_jump_indices = Vec::with_capacity(blocked_syscalls.len()); + for &sys_nr in blocked_syscalls { + deny_jump_indices.push(prog.len()); + prog.push(bpf_jump(BPF_JMP_JEQ_K, sys_nr, 0, 0)); + } + + if !allow_network { + // Inspect socket(domain, ...) and socketpair(domain, ...): permit ONLY AF_UNIX (1). + prog.push(bpf_jump(BPF_JMP_JEQ_K, socket_nr, 1, 0)); + prog.push(bpf_jump(BPF_JMP_JEQ_K, socketpair_nr, 0, 3)); + prog.push(bpf_stmt(BPF_LD_W_ABS, 16)); // seccomp_data.args[0] low u32 + prog.push(bpf_jump(BPF_JMP_JEQ_K, 1, 1, 0)); // AF_UNIX == 1 on Linux + prog.push(bpf_stmt(BPF_RET_K, SECCOMP_RET_ERRNO_EPERM)); + } + + prog.push(bpf_stmt(BPF_RET_K, SECCOMP_RET_ALLOW)); + let deny_idx = prog.len(); + prog.push(bpf_stmt(BPF_RET_K, SECCOMP_RET_ERRNO_EPERM)); + + for idx in deny_jump_indices { + let offset = (deny_idx - idx - 1) as u8; + prog[idx].jt = offset; + } + + prog +} + +/// Async-signal-safe prepared Landlock + seccomp-bpf confinement bundle created BEFORE `fork()`, +/// applied strictly via raw syscalls in `CommandExt::pre_exec` with zero heap allocation. +#[cfg(target_os = "linux")] +pub struct PreparedLinuxSandbox { + ruleset_fd: Option, + seccomp_prog: Vec, + strict: bool, +} + +#[cfg(target_os = "linux")] +impl PreparedLinuxSandbox { + pub fn prepare( + config: &LandlockSandboxConfig, + allow_network: bool, + ) -> Result { + let enforce_net = !allow_network || !config.allowed_tcp_ports.is_empty(); + let ruleset_fd = build_landlock_ruleset_fd(config, enforce_net)?; + if let Some(fd) = ruleset_fd { + unsafe { + let _ = libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC); + } + } + let seccomp_prog = build_agent_seccomp_bpf(allow_network); + Ok(Self { + ruleset_fd, + seccomp_prog, + strict: config.strict, + }) + } + + pub fn prepare_seccomp_only(allow_network: bool, strict: bool) -> Self { + Self { + ruleset_fd: None, + seccomp_prog: build_agent_seccomp_bpf(allow_network), + strict, + } + } + + /// Invoked in the child process between `fork()` and `exec()` via `CommandExt::pre_exec`. + /// Must remain strictly async-signal-safe (raw syscalls / prctl only). + /// + /// # Safety + /// Caller must run inside `pre_exec` (single-threaded child context before `exec`) while + /// `self` outlives `pre_exec`. + pub unsafe fn apply_in_pre_exec(&self) -> std::io::Result<()> { + if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 { + return Err(std::io::Error::last_os_error()); + } + if let Some(fd) = self.ruleset_fd { + let ret = libc::syscall(SYS_LANDLOCK_RESTRICT_SELF, fd, 0u32); + let saved_err = std::io::Error::last_os_error(); + let _ = libc::close(fd); + if ret < 0 && self.strict { + return Err(saved_err); + } + } + if !self.seccomp_prog.is_empty() { + let fprog = SockFprog { + len: self.seccomp_prog.len() as u16, + filter: self.seccomp_prog.as_ptr(), + }; + // SECCOMP_MODE_FILTER == 2 + if libc::prctl(libc::PR_SET_SECCOMP, 2, &fprog as *const SockFprog) != 0 { + let err = std::io::Error::last_os_error(); + if self.strict { + return Err(err); + } + } + } + Ok(()) + } +} + +#[cfg(target_os = "linux")] +impl Drop for PreparedLinuxSandbox { + fn drop(&mut self) { + if let Some(fd) = self.ruleset_fd.take() { + unsafe { + let _ = libc::close(fd); + } + } + } +} + +/// Applies `PR_SET_NO_NEW_PRIVS` + agent `seccomp-bpf` directly to the current process. +pub fn apply_agent_seccomp_bpf(allow_network: bool) -> Result<(), KillSwitchError> { + #[cfg(target_os = "linux")] + { + let prog = build_agent_seccomp_bpf(allow_network); + let fprog = SockFprog { + len: prog.len() as u16, + filter: prog.as_ptr(), + }; + unsafe { + if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 { + let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + return Err(KillSwitchError::LandlockRestrictSelfFailed { errno }); + } + if libc::prctl(libc::PR_SET_SECCOMP, 2, &fprog as *const SockFprog) != 0 { + let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + return Err(KillSwitchError::LandlockRestrictSelfFailed { errno }); + } + } + Ok(()) + } + #[cfg(not(target_os = "linux"))] + { + let _ = allow_network; + Ok(()) + } +} + // --------------------------------------------------------------------------- // 2. Linux Raw Netlink Socket Isolator & Route Blackholing // --------------------------------------------------------------------------- @@ -491,8 +950,9 @@ pub fn build_blackhole_route_msg(is_v6: bool, is_delete: bool, priority: u32) -> buf } -/// Builds a binary Netlink INET_DIAG SOCK_DESTROY message to abort a TCP connection. -pub fn build_sock_destroy_msg(entry: &LinuxSocketEntry) -> Vec { +/// Builds a binary Netlink INET_DIAG SOCK_DESTROY message for an arbitrary IP protocol +/// (`6` = TCP, `17` = UDP, `255` = RAW). +pub fn build_sock_destroy_msg_for_proto(entry: &LinuxSocketEntry, protocol: u8) -> Vec { let family = if entry.is_ipv6 { #[cfg(target_os = "linux")] { @@ -560,7 +1020,7 @@ pub fn build_sock_destroy_msg(entry: &LinuxSocketEntry) -> Vec { let req = InetDiagReqV2 { sdiag_family: family, - sdiag_protocol: 6, // IPPROTO_TCP + sdiag_protocol: protocol, idiag_ext: 0, pad: 0, idiag_states: 0xFFFFFFFF, @@ -584,6 +1044,11 @@ pub fn build_sock_destroy_msg(entry: &LinuxSocketEntry) -> Vec { buf } +/// Builds a binary Netlink INET_DIAG SOCK_DESTROY message to abort a TCP connection. +pub fn build_sock_destroy_msg(entry: &LinuxSocketEntry) -> Vec { + build_sock_destroy_msg_for_proto(entry, 6) +} + #[cfg(target_os = "linux")] fn send_netlink_route_message(msg: &[u8]) -> Result<(), KillSwitchError> { unsafe { @@ -683,8 +1148,11 @@ fn send_netlink_route_message(msg: &[u8]) -> Result<(), KillSwitchError> { } #[cfg(target_os = "linux")] -fn terminate_linux_socket_netlink(entry: &LinuxSocketEntry) -> Result<(), KillSwitchError> { - let msg = build_sock_destroy_msg(entry); +fn terminate_linux_socket_netlink_proto( + entry: &LinuxSocketEntry, + protocol: u8, +) -> Result<(), KillSwitchError> { + let msg = build_sock_destroy_msg_for_proto(entry, protocol); unsafe { let fd = libc::socket(libc::AF_NETLINK, libc::SOCK_RAW, NETLINK_INET_DIAG); if fd < 0 { @@ -714,7 +1182,7 @@ fn terminate_linux_socket_netlink(entry: &LinuxSocketEntry) -> Result<(), KillSw let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); return Err(KillSwitchError::NetlinkSockDestroyFailed { four_tuple: format!( - "{}:{} -> {}:{}", + "proto={protocol} {}:{} -> {}:{}", entry.local_addr, entry.local_port, entry.remote_addr, entry.remote_port ), errno, @@ -724,6 +1192,189 @@ fn terminate_linux_socket_netlink(entry: &LinuxSocketEntry) -> Result<(), KillSw } } +/// Generates an atomic `nftables` `inet killswitch_quarantine` script with strict default-drop +/// policy, explicit loopback-alias (`127.0.0.2+`), IMDS (`169.254.0.0/16` / `fe80::/10`), +/// DNS/DoT/DHCP/QUIC, loopback proxy (`1080/3128/8080/8888/9050`), and lateral SMB/RPC drops, +/// permitting ONLY exact `127.0.0.1 <-> 127.0.0.1` / `::1 <-> ::1` TCP on sanitized control ports. +pub fn generate_linux_nftables_quarantine_script( + preserved_ports: &[u16], + cgroup_paths: &[&str], + agent_uids: &[u32], +) -> String { + let ports = sanitize_firewall_preserved_ports(preserved_ports); + let discovery_csv = QUARANTINE_BLOCKED_DISCOVERY_PORTS + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", "); + let proxy_csv = QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", "); + let lateral_csv = QUARANTINE_BLOCKED_LATERAL_PORTS + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", "); + + let mut s = String::from( + "table inet killswitch_quarantine\n\ +delete table inet killswitch_quarantine\n\ +table inet killswitch_quarantine {\n\ + chain input {\n\ + type filter hook input priority -150; policy drop;\n\ + ip saddr != 127.0.0.1 ip daddr 127.0.0.0/8 drop\n\ + ip daddr != 127.0.0.1 ip saddr 127.0.0.0/8 drop\n\ + ip daddr 169.254.0.0/16 drop\n\ + ip6 daddr fe80::/10 drop\n", + ); + s.push_str(&format!( + " tcp dport {{ {discovery_csv} }} drop\n\ + udp dport {{ {discovery_csv}, 443 }} drop\n\ + tcp dport {{ {proxy_csv} }} drop\n\ + tcp dport {{ {lateral_csv} }} drop\n" + )); + for &port in &ports { + s.push_str(&format!( + " iifname \"lo\" ip saddr 127.0.0.1 ip daddr 127.0.0.1 tcp dport {port} accept\n\ + iifname \"lo\" ip saddr 127.0.0.1 ip daddr 127.0.0.1 tcp sport {port} accept\n\ + iifname \"lo\" ip6 saddr ::1 ip6 daddr ::1 tcp dport {port} accept\n\ + iifname \"lo\" ip6 saddr ::1 ip6 daddr ::1 tcp sport {port} accept\n" + )); + } + s.push_str( + " }\n\ + chain output {\n\ + type filter hook output priority -150; policy drop;\n", + ); + for cg in cgroup_paths { + let clean: String = cg + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '-' | '_' | '.')) + .collect(); + if !clean.is_empty() { + s.push_str(&format!( + " socket cgroupv2 level 1 \"{clean}\" drop\n" + )); + } + } + for &uid in agent_uids { + s.push_str(&format!(" meta skuid {uid} drop\n")); + } + s.push_str(&format!( + " ip saddr != 127.0.0.1 ip daddr 127.0.0.0/8 drop\n\ + ip daddr != 127.0.0.1 ip saddr 127.0.0.0/8 drop\n\ + ip daddr 169.254.0.0/16 drop\n\ + ip6 daddr fe80::/10 drop\n\ + tcp dport {{ {discovery_csv} }} drop\n\ + udp dport {{ {discovery_csv}, 443 }} drop\n\ + tcp dport {{ {proxy_csv} }} drop\n\ + tcp dport {{ {lateral_csv} }} drop\n" + )); + for &port in &ports { + s.push_str(&format!( + " oifname \"lo\" ip saddr 127.0.0.1 ip daddr 127.0.0.1 tcp dport {port} accept\n\ + oifname \"lo\" ip saddr 127.0.0.1 ip daddr 127.0.0.1 tcp sport {port} accept\n\ + oifname \"lo\" ip6 saddr ::1 ip6 daddr ::1 tcp dport {port} accept\n\ + oifname \"lo\" ip6 saddr ::1 ip6 daddr ::1 tcp sport {port} accept\n" + )); + } + s.push_str(" }\n}\n"); + s +} + +#[cfg(target_os = "linux")] +fn find_nft_binary() -> Option<&'static str> { + ["/usr/sbin/nft", "/sbin/nft", "/usr/bin/nft", "nft"] + .into_iter() + .find(|&candidate| candidate == "nft" || Path::new(candidate).exists()) +} + +/// Atomically installs `table inet killswitch_quarantine` via `nft -f -` and performs +/// mandatory readback verification via `nft list table inet killswitch_quarantine`. +pub fn install_linux_nftables_quarantine( + preserved_ports: &[u16], + cgroup_paths: &[&str], + agent_uids: &[u32], +) -> Result { + let script = + generate_linux_nftables_quarantine_script(preserved_ports, cgroup_paths, agent_uids); + #[cfg(target_os = "linux")] + { + use std::io::Write; + use std::process::{Command, Stdio}; + + let nft_bin = find_nft_binary().ok_or_else(|| { + KillSwitchError::NativeOsError( + "nftables binary (nft) not found on Linux host".to_string(), + ) + })?; + let mut child = Command::new(nft_bin) + .args(["-f", "-"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| { + KillSwitchError::NativeOsError(format!("Failed to invoke {nft_bin}: {e}")) + })?; + + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(script.as_bytes()).map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Failed writing nftables script to stdin: {e}" + )) + })?; + } + let out = child.wait_with_output().map_err(|e| { + KillSwitchError::NativeOsError(format!("Failed waiting on nft -f -: {e}")) + })?; + if !out.status.success() { + let stderr = String::from_utf8_lossy(&out.stderr); + return Err(KillSwitchError::NativeOsError(format!( + "nft -f - failed with status {}: {}", + out.status, + stderr.trim() + ))); + } + + // Mandatory readback verification + let readback = Command::new(nft_bin) + .args(["list", "table", "inet", "killswitch_quarantine"]) + .output() + .map_err(|e| { + KillSwitchError::NativeOsError(format!("nft readback check failed: {e}")) + })?; + let body = String::from_utf8_lossy(&readback.stdout); + if !readback.status.success() + || !body.contains("chain input") + || !body.contains("chain output") + { + return Err(KillSwitchError::NativeOsError(format!( + "nftables readback verification failed for inet killswitch_quarantine: {}", + String::from_utf8_lossy(&readback.stderr).trim() + ))); + } + info!("🔒 [LinuxNetlinkIsolator] Installed and readback-verified inet killswitch_quarantine nftables policy."); + } + Ok(script) +} + +/// Removes `table inet killswitch_quarantine` without touching unrelated host nftables tables. +pub fn remove_linux_nftables_quarantine() -> Result<(), KillSwitchError> { + #[cfg(target_os = "linux")] + { + use std::process::Command; + if let Some(nft_bin) = find_nft_binary() { + let _ = Command::new(nft_bin) + .args(["delete", "table", "inet", "killswitch_quarantine"]) + .output(); + } + } + Ok(()) +} + /// Installs IPv4 (0.0.0.0/0) and IPv6 (::/0) RTN_BLACKHOLE routes via Netlink NETLINK_ROUTE. pub fn install_netlink_blackhole_routes() -> Result<(), KillSwitchError> { #[cfg(target_os = "linux")] @@ -810,39 +1461,31 @@ impl NetworkIsolator for LinuxNetlinkIsolator { operator: &str, reason: &str, ) -> Result { - // Enforce privilege check + let ports = sanitize_firewall_preserved_ports(preserved_ports); + + // Enforce privilege check (only root/CAP_NET_ADMIN or explicit authorized CI self-diagnostic) #[cfg(target_os = "linux")] { - let in_test = std::env::var("CARGO").is_ok() - || std::env::var("RUST_TEST_THREADS").is_ok() - || cfg!(test); let is_root = unsafe { libc::geteuid() == 0 }; - if !is_root && !in_test { + if !is_root && !is_authorized_self_diagnostic() { return Err(KillSwitchError::InsufficientPrivileges { - details: "Root privileges (or CAP_NET_ADMIN) required to install Linux network quarantine routes via Netlink".to_string(), + details: "Root privileges (or CAP_NET_ADMIN) required to install Linux network quarantine routes and nftables policy".to_string(), remediation: "Restart the application using 'sudo killswitch' or ensure container possesses CAP_NET_ADMIN.".to_string(), }); } if is_root { install_netlink_blackhole_routes()?; + install_linux_nftables_quarantine(&ports, &[], &[])?; } } - let mut ports = preserved_ports.to_vec(); - if !ports.contains(&3030) { - ports.push(3030); - } - let loopback_ips = vec![ IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), ]; - let mut terminated_count = 0; - if let Ok(count) = self.reset_tcp_connections(None) { - terminated_count = count; - } + let terminated_count = self.reset_tcp_connections(None).unwrap_or(0); self.active.store(true, Ordering::SeqCst); @@ -851,7 +1494,10 @@ impl NetworkIsolator for LinuxNetlinkIsolator { NetworkIsolationEngine::LinuxNetlink, Vec::new(), Vec::new(), - vec!["netlink_rtn_blackhole_active".to_string()], + vec![ + "netlink_rtn_blackhole_active".to_string(), + "nftables_inet_killswitch_quarantine".to_string(), + ], ports, loopback_ips, terminated_count, @@ -860,7 +1506,7 @@ impl NetworkIsolator for LinuxNetlinkIsolator { ); tracing::info!( - "🚨 [LinuxNetlinkIsolator] Quarantined host via Netlink RTN_BLACKHOLE. Receipt: {}", + "🚨 [LinuxNetlinkIsolator] Quarantined host via Netlink RTN_BLACKHOLE + nftables. Receipt: {}", receipt.receipt_id ); Ok(receipt) @@ -870,40 +1516,95 @@ impl NetworkIsolator for LinuxNetlinkIsolator { #[cfg(target_os = "linux")] { let is_root = unsafe { libc::geteuid() == 0 }; + if !is_root && !is_authorized_self_diagnostic() { + return Err(KillSwitchError::InsufficientPrivileges { + details: "Root privileges (or CAP_NET_ADMIN) required to remove Linux network quarantine".to_string(), + remediation: "Restart the application using 'sudo killswitch' or ensure container possesses CAP_NET_ADMIN.".to_string(), + }); + } if is_root { + let _ = remove_linux_nftables_quarantine(); let _ = remove_netlink_blackhole_routes(); } } self.active.store(false, Ordering::SeqCst); tracing::info!( - "🟢 [LinuxNetlinkIsolator] Restored host network isolation via Netlink RTM_DELROUTE." + "🟢 [LinuxNetlinkIsolator] Restored host network isolation via nftables + Netlink RTM_DELROUTE." ); Ok(()) } fn reset_tcp_connections( &self, - _target_ips: Option<&[IpAddr]>, + target_ips: Option<&[IpAddr]>, ) -> Result { - let non_loopback = get_active_non_loopback_connections().unwrap_or_default(); #[cfg(target_os = "linux")] - let mut closed_count = 0; - #[cfg(target_os = "linux")] - { - for entry in &non_loopback { - if let Ok(()) = terminate_linux_socket_netlink(entry) { - closed_count += 1; + let closed_count = { + let mut count = 0usize; + let is_root = unsafe { libc::geteuid() == 0 }; + if !is_root && !is_authorized_self_diagnostic() { + return Err(KillSwitchError::InsufficientPrivileges { + details: "Root privileges (or CAP_NET_ADMIN) required to destroy kernel sockets via Netlink SOCK_DESTROY".to_string(), + remediation: "Restart the application using 'sudo killswitch' or grant CAP_NET_ADMIN.".to_string(), + }); + } + if is_root { + let matches_target = |entry: &LinuxSocketEntry| -> bool { + match target_ips { + Some(ips) => { + ips.contains(&entry.remote_addr) || ips.contains(&entry.local_addr) + } + None => true, + } + }; + + // 1. Destroy non-loopback / alias TCP sockets + blocked loopback proxy sockets + let mut tcp_targets = get_active_non_loopback_connections().unwrap_or_default(); + for sock in read_and_parse_proc_net_tcp() + .into_iter() + .flatten() + .chain(read_and_parse_proc_net_tcp6().into_iter().flatten()) + { + if (QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS.contains(&sock.remote_port) + || QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS.contains(&sock.local_port)) + && (sock.state == TcpState::Established + || sock.state == TcpState::SynSent + || sock.state == TcpState::SynRecv + || sock.state == TcpState::CloseWait) + { + tcp_targets.push(sock); + } + } + for entry in &tcp_targets { + if matches_target(entry) + && terminate_linux_socket_netlink_proto(entry, 6).is_ok() + { + count += 1; + } + } + + // 2. Destroy non-loopback UDP (17) & RAW (255) sockets + if let Ok(udp_raw) = get_active_non_loopback_udp_and_raw_sockets() { + for (proto, entry) in &udp_raw { + if matches_target(entry) + && terminate_linux_socket_netlink_proto(entry, *proto).is_ok() + { + count += 1; + } + } } } - } + count + }; #[cfg(not(target_os = "linux"))] - let closed_count = non_loopback.len(); + let closed_count = { + let _ = target_ips; + let _ = &get_active_non_loopback_connections; + 0usize + }; - debug!( - "Linux Netlink reset: severed {} non-loopback sockets.", - closed_count - ); + debug!("Linux Netlink reset: severed {} sockets.", closed_count); Ok(closed_count) } } @@ -1082,27 +1783,69 @@ pub fn parse_proc_net_content(content: &str, is_v6: bool) -> Vec Result, KillSwitchError> { + let content = + std::fs::read_to_string(path).map_err(|_| KillSwitchError::ProcNetTcpParseFailed { + line: format!("Could not open {path}"), + })?; + Ok(parse_proc_net_content(&content, is_v6)) +} + +#[inline] +fn is_exact_localhost_ip(addr: IpAddr) -> bool { + match addr { + IpAddr::V4(v4) => v4 == Ipv4Addr::LOCALHOST, + IpAddr::V6(v6) => { + v6 == Ipv6Addr::LOCALHOST || v6.to_ipv4_mapped() == Some(Ipv4Addr::LOCALHOST) + } + } +} + +#[inline] +fn is_unspecified_ip(addr: IpAddr) -> bool { + match addr { + IpAddr::V4(v4) => v4.is_unspecified(), + IpAddr::V6(v6) => { + v6.is_unspecified() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_unspecified()) + } + } +} + /// Reads and parses live `/proc/net/tcp` (IPv4). pub fn read_and_parse_proc_net_tcp() -> Result, KillSwitchError> { - let content = std::fs::read_to_string("/proc/net/tcp").map_err(|_| { - KillSwitchError::ProcNetTcpParseFailed { - line: "Could not open /proc/net/tcp".to_string(), - } - })?; - Ok(parse_proc_net_content(&content, false)) + read_and_parse_proc_net_file("/proc/net/tcp", false) } /// Reads and parses live `/proc/net/tcp6` (IPv6). pub fn read_and_parse_proc_net_tcp6() -> Result, KillSwitchError> { - let content = std::fs::read_to_string("/proc/net/tcp6").map_err(|_| { - KillSwitchError::ProcNetTcpParseFailed { - line: "Could not open /proc/net/tcp6".to_string(), - } - })?; - Ok(parse_proc_net_content(&content, true)) + read_and_parse_proc_net_file("/proc/net/tcp6", true) +} + +/// Reads and parses live `/proc/net/udp` (IPv4). +pub fn read_and_parse_proc_net_udp() -> Result, KillSwitchError> { + read_and_parse_proc_net_file("/proc/net/udp", false) +} + +/// Reads and parses live `/proc/net/udp6` (IPv6). +pub fn read_and_parse_proc_net_udp6() -> Result, KillSwitchError> { + read_and_parse_proc_net_file("/proc/net/udp6", true) +} + +/// Reads and parses live `/proc/net/raw` (IPv4). +pub fn read_and_parse_proc_net_raw() -> Result, KillSwitchError> { + read_and_parse_proc_net_file("/proc/net/raw", false) +} + +/// Reads and parses live `/proc/net/raw6` (IPv6). +pub fn read_and_parse_proc_net_raw6() -> Result, KillSwitchError> { + read_and_parse_proc_net_file("/proc/net/raw6", true) } -/// Enumerates all active non-loopback TCP connections. +/// Enumerates all active non-localhost TCP connections (including `127.0.0.2+` loopback aliases +/// and external connections targeting port 3030). pub fn get_active_non_loopback_connections() -> Result, KillSwitchError> { let mut entries = Vec::new(); if let Ok(v4) = read_and_parse_proc_net_tcp() { @@ -1115,9 +1858,8 @@ pub fn get_active_non_loopback_connections() -> Result, Ki let non_loopback: Vec = entries .into_iter() .filter(|e| { - !e.remote_addr.is_loopback() - && !e.remote_addr.is_unspecified() - && e.remote_port != 3030 + !is_exact_localhost_ip(e.remote_addr) + && !is_unspecified_ip(e.remote_addr) && (e.state == TcpState::Established || e.state == TcpState::SynSent || e.state == TcpState::SynRecv @@ -1128,6 +1870,35 @@ pub fn get_active_non_loopback_connections() -> Result, Ki Ok(non_loopback) } +/// Enumerates active non-localhost UDP (`17`) and RAW (`255`) sockets for `SOCK_DESTROY` / audit. +pub fn get_active_non_loopback_udp_and_raw_sockets( +) -> Result, KillSwitchError> { + let mut out = Vec::new(); + for entry in read_and_parse_proc_net_udp() + .into_iter() + .flatten() + .chain(read_and_parse_proc_net_udp6().into_iter().flatten()) + { + if !is_exact_localhost_ip(entry.local_addr) + || (!is_unspecified_ip(entry.remote_addr) && !is_exact_localhost_ip(entry.remote_addr)) + { + out.push((17u8, entry)); + } + } + for entry in read_and_parse_proc_net_raw() + .into_iter() + .flatten() + .chain(read_and_parse_proc_net_raw6().into_iter().flatten()) + { + if !is_exact_localhost_ip(entry.local_addr) + || (!is_unspecified_ip(entry.remote_addr) && !is_exact_localhost_ip(entry.remote_addr)) + { + out.push((255u8, entry)); + } + } + Ok(out) +} + #[cfg(test)] mod tests { use super::*; @@ -1198,14 +1969,28 @@ mod tests { #[test] fn test_linux_netlink_isolator_engagement() { let isolator = LinuxNetlinkIsolator::new(); - let res = isolator.engage_quarantine(&[3030, 53], "admin", "test isolation"); - assert!(res.is_ok()); + let res = isolator.engage_quarantine(&[3030, 53, 8080, 445], "admin", "test isolation"); + #[cfg(target_os = "linux")] + { + let is_root = unsafe { libc::geteuid() == 0 }; + if !is_root && !is_authorized_self_diagnostic() { + assert!(matches!( + res, + Err(KillSwitchError::InsufficientPrivileges { .. }) + )); + return; + } + } + assert!(res.is_ok(), "engage_quarantine failed: {:?}", res); let receipt = res.unwrap(); assert_eq!(receipt.engine, NetworkIsolationEngine::LinuxNetlink); - assert!(receipt.preserved_ports.contains(&3030)); + assert_eq!(receipt.preserved_ports, vec![3030]); assert_eq!( receipt.netlink_rule_ids, - vec!["netlink_rtn_blackhole_active"] + vec![ + "netlink_rtn_blackhole_active".to_string(), + "nftables_inet_killswitch_quarantine".to_string(), + ] ); assert!(isolator.restore_quarantine(&receipt).is_ok()); @@ -1214,6 +1999,49 @@ mod tests { assert_eq!(landlock_cfg.allowed_tcp_ports, vec![3030]); } + #[test] + fn test_linux_nftables_quarantine_script_hardening() { + let script = generate_linux_nftables_quarantine_script( + &[3030, 53, 8080, 445, 9050, 3456], + &["killswitch.slice/ks-agent-1.scope"], + &[1001], + ); + assert!(script.contains("policy drop;")); + assert!(!script.contains("iif lo accept")); + assert!(!script.contains("oif lo accept")); + assert!(script.contains("ip saddr != 127.0.0.1 ip daddr 127.0.0.0/8 drop")); + assert!(script.contains("ip daddr 169.254.0.0/16 drop")); + assert!(script.contains("ip6 daddr fe80::/10 drop")); + assert!(script.contains("udp dport { 53, 67, 68, 546, 547, 853, 443 } drop")); + assert!(script.contains("tcp dport { 1080, 3128, 8080, 8888, 9050 } drop")); + assert!(script.contains("tcp dport { 135, 445, 5985, 5986 } drop")); + assert!( + script.contains("socket cgroupv2 level 1 \"killswitch.slice/ks-agent-1.scope\" drop") + ); + assert!(script.contains("meta skuid 1001 drop")); + assert!(script.contains("ip saddr 127.0.0.1 ip daddr 127.0.0.1 tcp dport 3030 accept")); + assert!(script.contains("ip saddr 127.0.0.1 ip daddr 127.0.0.1 tcp dport 3456 accept")); + assert!(!script.contains("tcp dport 8080 accept")); + assert!(!script.contains("tcp dport 53 accept")); + } + + #[test] + fn test_agent_seccomp_bpf_filter_layout() { + let no_net = build_agent_seccomp_bpf(false); + assert!(!no_net.is_empty()); + assert_eq!(no_net[0].code, BPF_LD_W_ABS); + assert_eq!(no_net[0].k, 4, "Must validate seccomp_data.arch first"); + assert_eq!(no_net[2].k, SECCOMP_RET_KILL_PROCESS); + assert!(no_net.iter().any(|ins| ins.k == SECCOMP_RET_ERRNO_EPERM)); + assert!(no_net.iter().any(|ins| ins.k == SECCOMP_RET_ALLOW)); + + let with_net = build_agent_seccomp_bpf(true); + assert!( + no_net.len() > with_net.len(), + "network-off BPF adds AF_UNIX-only check" + ); + } + #[test] fn test_netlink_blackhole_route_binary_layout() { // Test IPv4 blackhole route message @@ -1248,7 +2076,7 @@ mod tests { } #[test] - fn test_netlink_sock_destroy_binary_layout() { + fn test_netlink_sock_destroy_binary_layout_and_udp_proto() { let entry = LinuxSocketEntry { slot: 1, local_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 5)), @@ -1271,5 +2099,22 @@ mod tests { assert_eq!(req.id.idiag_sport, 54321u16.to_be()); assert_eq!(req.id.idiag_dport, 53u16.to_be()); assert_eq!(req.id.idiag_cookie, [0xFFFFFFFF, 0xFFFFFFFF]); + + let udp_msg = build_sock_destroy_msg_for_proto(&entry, 17); + let udp_req = unsafe { &*(udp_msg.as_ptr().add(16) as *const InetDiagReqV2) }; + assert_eq!(udp_req.sdiag_protocol, 17, "Must target IPPROTO_UDP"); + } + + #[test] + fn test_exact_localhost_and_unspecified_ip_helpers() { + assert!(is_exact_localhost_ip(IpAddr::V4(Ipv4Addr::new( + 127, 0, 0, 1 + )))); + assert!(!is_exact_localhost_ip(IpAddr::V4(Ipv4Addr::new( + 127, 0, 0, 2 + )))); + assert!(is_exact_localhost_ip(IpAddr::V6(Ipv6Addr::LOCALHOST))); + assert!(is_unspecified_ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); + assert!(is_unspecified_ip(IpAddr::V6(Ipv6Addr::UNSPECIFIED))); } } diff --git a/crates/killswitch-core/src/lib.rs b/crates/killswitch-core/src/lib.rs index 81013f3..7665ac4 100644 --- a/crates/killswitch-core/src/lib.rs +++ b/crates/killswitch-core/src/lib.rs @@ -39,10 +39,13 @@ pub use agent_registry::{AgentLineageClass, SubtreeResolution, TrackedAgentRoot} pub use auth::{FrozenPidsProvider, OperatorAuthManager}; pub use fprime::{FPrimeDispatchResult, FPrimeOpcode, FPrimeSupervisor, FPrimeTopologyStatus}; pub use freeze::NativeProcessFreezer; +#[cfg(target_os = "windows")] +pub use job_sandbox::WindowsAppContainerSandbox; pub use job_sandbox::{ - enumerate_live_descendants, enumerate_process_subtree, freeze_process_subtree, - freeze_subtree_kernel, resume_process_subtree, spawn_confined_process, ConfinedChild, - JobSandboxConfig, SubtreeFreezeReport, + enumerate_live_descendants, enumerate_process_subtree, format_windows_command_line, + freeze_process_subtree, freeze_subtree_kernel, resume_process_subtree, spawn_confined_process, + spawn_sandboxed_agent_process, ConfinedChild, JobSandboxConfig, SandboxedAgentConfig, + SandboxedAgentProcess, SubtreeFreezeReport, }; pub use killchain::{ default_network_isolator, is_critical_system_pid, is_developer_or_agent_runtime, @@ -50,14 +53,19 @@ pub use killchain::{ SimulatedNetworkIsolator, TrackedAgentTreeRegistry, }; pub use landlock::{ - apply_landlock_sandbox, get_active_non_loopback_connections, get_landlock_abi_version, - parse_linux_ipv4_hex, parse_linux_ipv6_hex, parse_proc_net_content, parse_tcp_line, - read_and_parse_proc_net_tcp, read_and_parse_proc_net_tcp6, LandlockSandboxConfig, - LinuxNetlinkIsolator, LinuxSocketEntry, TcpState, + apply_agent_seccomp_bpf, apply_landlock_sandbox, build_agent_seccomp_bpf, + build_sock_destroy_msg, build_sock_destroy_msg_for_proto, + generate_linux_nftables_quarantine_script, get_active_non_loopback_connections, + get_active_non_loopback_udp_and_raw_sockets, get_landlock_abi_version, + install_linux_nftables_quarantine, parse_linux_ipv4_hex, parse_linux_ipv6_hex, + parse_proc_net_content, parse_tcp_line, read_and_parse_proc_net_raw, + read_and_parse_proc_net_raw6, read_and_parse_proc_net_tcp, read_and_parse_proc_net_tcp6, + read_and_parse_proc_net_udp, read_and_parse_proc_net_udp6, remove_linux_nftables_quarantine, + LandlockSandboxConfig, LinuxNetlinkIsolator, LinuxSocketEntry, TcpState, }; pub use pf::{ - generate_quarantine_rules, get_active_darwin_sockets, DarwinSocketEntry, MacOsPfIsolator, - PfRuleSpec, DEFAULT_PF_ANCHOR, PF_DEVICE_PATH, + generate_macos_seatbelt_profile, generate_quarantine_rules, get_active_darwin_sockets, + DarwinSocketEntry, MacOsPfIsolator, PfRuleSpec, DEFAULT_PF_ANCHOR, PF_DEVICE_PATH, }; #[cfg(target_os = "windows")] pub use service::WindowsServiceManager; diff --git a/crates/killswitch-core/src/pf.rs b/crates/killswitch-core/src/pf.rs index 72c0165..b0b7b8b 100644 --- a/crates/killswitch-core/src/pf.rs +++ b/crates/killswitch-core/src/pf.rs @@ -12,12 +12,16 @@ //! - Zero `pfctl` subprocess invocations. //! - Safe fallback / simulation when running on non-macOS or non-root test environments. +#[cfg(target_os = "macos")] +use crate::wfp::is_authorized_self_diagnostic; +use crate::wfp::{ + sanitize_firewall_preserved_ports, QUARANTINE_BLOCKED_DISCOVERY_PORTS, + QUARANTINE_BLOCKED_LATERAL_PORTS, QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS, +}; #[cfg(target_os = "macos")] use killswitch_types::errors::KillSwitchError; use killswitch_types::errors::Result; -use killswitch_types::status::{ - IsolationReceipt, NetworkIsolationEngine, NetworkIsolator, DEFAULT_CONTROL_PORT, -}; +use killswitch_types::status::{IsolationReceipt, NetworkIsolationEngine, NetworkIsolator}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::path::PathBuf; #[cfg(target_os = "macos")] @@ -307,104 +311,188 @@ impl PfRuleSpec { } } -/// Generates the canonical isolation ruleset for Darwin BSD Packet Filter: -/// 1. Allow all traffic on loopback interface (`lo0`). -/// 2. Explicitly permit IPv4 `127.0.0.1` and IPv6 `::1` loopback traffic. -/// 3. Allow incoming and outgoing traffic on the local control port (`3030`). -/// 4. Allow outgoing DNS (port 53 UDP/TCP) and DHCP (ports 67, 68 UDP) for connectivity resolution. -/// 5. Block all other incoming and outgoing traffic. +/// Generates the hardened hermetic isolation ruleset for Darwin BSD Packet Filter: +/// 1. Explicitly drop IMDS (`169.254.0.0/16`), IPv6 link-local (`fe80::/10`), DNS/DoT/DHCP/QUIC, +/// loopback proxy ports (`1080/3128/8080/8888/9050`), and lateral SMB/RPC/WinRM ports. +/// 2. Permit ONLY exact `127.0.0.1 <-> 127.0.0.1` and `::1 <-> ::1` TCP traffic on `lo0` for +/// sanitized KillSwitch WebUI/control ports (`DEFAULT_CONTROL_PORT` + validated custom ports). +/// 3. Explicitly drop remaining `127.0.0.0/8` loopback aliases (`127.0.0.2+`) on `lo0`. +/// 4. Block all other incoming and outgoing traffic (`block drop in quick all`, `block drop out quick all`). pub fn generate_quarantine_rules( anchor: &str, preserved_ports: &[u16], ) -> (Vec, String) { let mut rules = Vec::new(); + let allowed_ports = sanitize_firewall_preserved_ports(preserved_ports); - // 1. Loopback interface immunity + // 1. Explicit IMDS and link-local drops (before any loopback/control rule) rules.push(PfRuleSpec { - action: PfAction::Pass, + action: PfAction::Drop, direction: PfDirection::InOut, quick: true, - interface: Some("lo0".to_string()), + interface: None, protocol: PfProtocol::Any, - src: "any".to_string(), + src: "0.0.0.0/0".to_string(), src_port: None, - dst: "any".to_string(), + dst: "169.254.0.0/16".to_string(), dst_port: None, - keep_state: true, - comment: "Preserve all loopback interface lo0 traffic".to_string(), + keep_state: false, + comment: "Block IPv4 IMDS and link-local 169.254.0.0/16".to_string(), }); - - // 2. Loopback IP address explicit permit rules.push(PfRuleSpec { - action: PfAction::Pass, + action: PfAction::Drop, direction: PfDirection::InOut, quick: true, interface: None, protocol: PfProtocol::Any, - src: "127.0.0.1".to_string(), + src: "::/0".to_string(), src_port: None, - dst: "any".to_string(), + dst: "fe80::/10".to_string(), dst_port: None, - keep_state: true, - comment: "Preserve IPv4 loopback 127.0.0.1".to_string(), + keep_state: false, + comment: "Block IPv6 link-local fe80::/10".to_string(), }); + // 2. Explicit discovery/DNS/DHCP/DoT and QUIC (UDP 443) drops + for &port in QUARANTINE_BLOCKED_DISCOVERY_PORTS { + rules.push(PfRuleSpec { + action: PfAction::Drop, + direction: PfDirection::InOut, + quick: true, + interface: None, + protocol: PfProtocol::Tcp, + src: "any".to_string(), + src_port: None, + dst: "any".to_string(), + dst_port: Some(port), + keep_state: false, + comment: format!("Block TCP discovery/DNS/DHCP port {port}"), + }); + rules.push(PfRuleSpec { + action: PfAction::Drop, + direction: PfDirection::InOut, + quick: true, + interface: None, + protocol: PfProtocol::Udp, + src: "any".to_string(), + src_port: None, + dst: "any".to_string(), + dst_port: Some(port), + keep_state: false, + comment: format!("Block UDP discovery/DNS/DHCP port {port}"), + }); + } rules.push(PfRuleSpec { - action: PfAction::Pass, + action: PfAction::Drop, direction: PfDirection::InOut, quick: true, interface: None, - protocol: PfProtocol::Any, - src: "::1".to_string(), + protocol: PfProtocol::Udp, + src: "any".to_string(), src_port: None, dst: "any".to_string(), - dst_port: None, - keep_state: true, - comment: "Preserve IPv6 loopback ::1".to_string(), + dst_port: Some(443), + keep_state: false, + comment: "Block UDP/443 QUIC exfiltration".to_string(), }); - // 3. Local control port (default 3030) strictly restricted to lo0 - let control_port = preserved_ports + // 3. Explicit loopback proxy and lateral SMB/RPC/WinRM drops + for &port in QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS .iter() - .copied() - .find(|&p| p == DEFAULT_CONTROL_PORT) - .unwrap_or(DEFAULT_CONTROL_PORT); + .chain(QUARANTINE_BLOCKED_LATERAL_PORTS.iter()) + { + rules.push(PfRuleSpec { + action: PfAction::Drop, + direction: PfDirection::InOut, + quick: true, + interface: None, + protocol: PfProtocol::Tcp, + src: "any".to_string(), + src_port: None, + dst: "any".to_string(), + dst_port: Some(port), + keep_state: false, + comment: format!("Block loopback proxy / lateral movement TCP port {port}"), + }); + } - rules.push(PfRuleSpec { - action: PfAction::Pass, - direction: PfDirection::In, - quick: true, - interface: Some("lo0".to_string()), - protocol: PfProtocol::Tcp, - src: "any".to_string(), - src_port: None, - dst: "any".to_string(), - dst_port: Some(control_port), - keep_state: true, - comment: format!( - "Allow inbound HTTP/JSON API on port {} on lo0", - control_port - ), - }); + // 4. Strictly permit ONLY exact 127.0.0.1 <-> 127.0.0.1 and ::1 <-> ::1 TCP control ports on lo0 + for &port in &allowed_ports { + for (src_ip, dst_ip, label) in [ + ("127.0.0.1", "127.0.0.1", "IPv4 localhost"), + ("::1", "::1", "IPv6 localhost"), + ] { + rules.push(PfRuleSpec { + action: PfAction::Pass, + direction: PfDirection::In, + quick: true, + interface: Some("lo0".to_string()), + protocol: PfProtocol::Tcp, + src: src_ip.to_string(), + src_port: None, + dst: dst_ip.to_string(), + dst_port: Some(port), + keep_state: true, + comment: format!("Allow inbound {label} control traffic to port {port} on lo0"), + }); + rules.push(PfRuleSpec { + action: PfAction::Pass, + direction: PfDirection::Out, + quick: true, + interface: Some("lo0".to_string()), + protocol: PfProtocol::Tcp, + src: src_ip.to_string(), + src_port: None, + dst: dst_ip.to_string(), + dst_port: Some(port), + keep_state: true, + comment: format!("Allow outbound {label} control traffic to port {port} on lo0"), + }); + rules.push(PfRuleSpec { + action: PfAction::Pass, + direction: PfDirection::In, + quick: true, + interface: Some("lo0".to_string()), + protocol: PfProtocol::Tcp, + src: src_ip.to_string(), + src_port: Some(port), + dst: dst_ip.to_string(), + dst_port: None, + keep_state: true, + comment: format!("Allow inbound {label} control response from port {port} on lo0"), + }); + rules.push(PfRuleSpec { + action: PfAction::Pass, + direction: PfDirection::Out, + quick: true, + interface: Some("lo0".to_string()), + protocol: PfProtocol::Tcp, + src: src_ip.to_string(), + src_port: Some(port), + dst: dst_ip.to_string(), + dst_port: None, + keep_state: true, + comment: format!("Allow outbound {label} control response from port {port} on lo0"), + }); + } + } + // 5. Block all remaining loopback alias / proxy traffic (127.0.0.2+ and non-control lo0 ports) rules.push(PfRuleSpec { - action: PfAction::Pass, - direction: PfDirection::Out, + action: PfAction::Drop, + direction: PfDirection::InOut, quick: true, interface: Some("lo0".to_string()), - protocol: PfProtocol::Tcp, - src: "any".to_string(), - src_port: Some(control_port), - dst: "any".to_string(), + protocol: PfProtocol::Any, + src: "127.0.0.0/8".to_string(), + src_port: None, + dst: "0.0.0.0/0".to_string(), dst_port: None, - keep_state: true, - comment: format!( - "Allow outbound HTTP/JSON responses from port {} on lo0", - control_port - ), + keep_state: false, + comment: "Block non-control-plane IPv4 loopback and alias 127.0.0.2+ traffic".to_string(), }); - // 4. Default block rules (quick: true unconditionally to drop all non-loopback packets) + // 6. Default block rules (quick: true unconditionally to drop all non-control-plane packets) rules.push(PfRuleSpec { action: PfAction::Drop, direction: PfDirection::In, @@ -444,8 +532,8 @@ pub fn generate_quarantine_rules( (rules, syntax) } -// ----------------------------------------------------------------------------- -// Darwin Socket Inspection Model (`proc_pidinfo` & `sysctl`) +#[cfg(not(target_os = "macos"))] +use killswitch_types::status::DEFAULT_CONTROL_PORT; // ----------------------------------------------------------------------------- /// Socket record extracted via Darwin `proc_pidinfo` or `sysctl` @@ -495,40 +583,226 @@ pub fn get_active_darwin_sockets() -> Result> { } } +#[cfg(target_os = "macos")] +fn parse_darwin_addr_port(endpoint: &str) -> Option<(IpAddr, u16)> { + let ep = endpoint.trim(); + if ep.starts_with('[') { + let close = ep.rfind(']')?; + let ip_str = &ep[1..close]; + let port_str = ep.get(close + 2..)?; + let ip: IpAddr = ip_str.parse().ok()?; + let port: u16 = if port_str == "*" { + 0 + } else { + port_str.parse().ok()? + }; + return Some((ip, port)); + } + let colon = ep.rfind(':')?; + let host = &ep[..colon]; + let port_str = &ep[colon + 1..]; + let port: u16 = if port_str == "*" { + 0 + } else { + port_str.parse().ok()? + }; + let ip: IpAddr = if host == "*" { + IpAddr::V4(Ipv4Addr::UNSPECIFIED) + } else { + host.parse().ok()? + }; + Some((ip, port)) +} + #[cfg(target_os = "macos")] fn inspect_darwin_proc_sockets() -> Result> { - // In native macOS environments, calls proc_listpids, PROC_PIDLISTFDS, and PROC_PIDFDSOCKETINFO + use std::process::Command; + let mut entries = Vec::new(); - let my_pid = std::process::id() as libc::c_int; - let mut fds = [0i32; 128]; - let count = unsafe { - // Flavor 1 = PROC_PIDLISTFDS + // 1. Cross-PID active socket discovery via /usr/sbin/lsof -nP -iTCP -iUDP -F pcfPTn + if let Ok(output) = Command::new("/usr/sbin/lsof") + .args(["-nP", "-iTCP", "-iUDP", "-F", "pcfPTn"]) + .output() + { + if output.status.success() || !output.stdout.is_empty() { + let text = String::from_utf8_lossy(&output.stdout); + let mut cur_pid: Option = None; + let mut cur_proc: Option = None; + let mut cur_fd: Option = None; + let mut cur_is_tcp = true; + let mut cur_name: Option = None; + let mut cur_state = String::from("UNKNOWN"); + + let flush_fd = |entries: &mut Vec, + pid: Option, + proc_name: &Option, + fd: Option, + is_tcp: bool, + name: &Option, + state: &str| { + let Some(raw_n) = name.as_deref() else { + return; + }; + let (local_part, foreign_part) = if let Some((l, f)) = raw_n.split_once("->") { + (l, Some(f)) + } else { + (raw_n, None) + }; + let Some((local_addr, local_port)) = parse_darwin_addr_port(local_part) else { + return; + }; + let (foreign_addr, foreign_port) = foreign_part + .and_then(parse_darwin_addr_port) + .unwrap_or((IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)); + let is_loopback = (local_addr.is_loopback() && foreign_addr.is_unspecified()) + || (local_addr.is_loopback() && foreign_addr.is_loopback()); + entries.push(DarwinSocketEntry { + pid, + proc_name: proc_name.clone(), + fd, + local_addr, + local_port, + foreign_addr, + foreign_port, + is_loopback, + is_tcp, + state_name: state.to_string(), + }); + }; + + for line in text.lines() { + if let Some(rest) = line.strip_prefix('p') { + flush_fd( + &mut entries, + cur_pid, + &cur_proc, + cur_fd, + cur_is_tcp, + &cur_name, + &cur_state, + ); + cur_pid = rest.parse::().ok(); + cur_proc = None; + cur_fd = None; + cur_is_tcp = true; + cur_name = None; + cur_state = String::from("UNKNOWN"); + } else if let Some(rest) = line.strip_prefix('c') { + cur_proc = Some(rest.to_string()); + } else if let Some(rest) = line.strip_prefix('f') { + flush_fd( + &mut entries, + cur_pid, + &cur_proc, + cur_fd, + cur_is_tcp, + &cur_name, + &cur_state, + ); + cur_fd = rest.parse::().ok(); + cur_is_tcp = true; + cur_name = None; + cur_state = String::from("UNKNOWN"); + } else if let Some(rest) = line.strip_prefix('P') { + cur_is_tcp = !rest.eq_ignore_ascii_case("UDP"); + } else if let Some(rest) = line.strip_prefix('n') { + cur_name = Some(rest.to_string()); + } else if let Some(rest) = line.strip_prefix("TST=") { + cur_state = rest.to_string(); + } + } + flush_fd( + &mut entries, + cur_pid, + &cur_proc, + cur_fd, + cur_is_tcp, + &cur_name, + &cur_state, + ); + } + } + + // 2. Supplement via /usr/sbin/netstat -anv -p tcp so kernel-wide sockets owned by other UIDs are visible + if entries.is_empty() { + if let Ok(output) = Command::new("/usr/sbin/netstat") + .args(["-anv", "-p", "tcp"]) + .output() + { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let cols: Vec<&str> = line.split_whitespace().collect(); + if cols.len() >= 6 && cols[0].starts_with("tcp") { + let normalize_ns = |s: &str| -> Option<(IpAddr, u16)> { + let dot = s.rfind('.')?; + let host = &s[..dot]; + let p = &s[dot + 1..]; + let port: u16 = if p == "*" { 0 } else { p.parse().ok()? }; + let ip: IpAddr = if host == "*" { + IpAddr::V4(Ipv4Addr::UNSPECIFIED) + } else { + host.parse().ok()? + }; + Some((ip, port)) + }; + if let (Some((la, lp)), Some((fa, fp))) = + (normalize_ns(cols[3]), normalize_ns(cols[4])) + { + let pid = cols.get(8).and_then(|v| v.parse::().ok()); + entries.push(DarwinSocketEntry { + pid, + proc_name: None, + fd: None, + local_addr: la, + local_port: lp, + foreign_addr: fa, + foreign_port: fp, + is_loopback: la.is_loopback() + && (fa.is_loopback() || fa.is_unspecified()), + is_tcp: true, + state_name: cols[5].to_string(), + }); + } + } + } + } + } + + // 3. Always inspect current process socket FDs via libproc proc_fdinfo ({ proc_fd: i32, proc_fdtype: u32 }) + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct ProcFdInfo { + proc_fd: i32, + proc_fdtype: u32, + } + const PROX_FDTYPE_SOCKET: u32 = 2; + let my_pid = std::process::id() as libc::c_int; + let mut fds = [ProcFdInfo::default(); 256]; + let bytes = unsafe { libc::proc_pidinfo( my_pid, - 1, + 1, // PROC_PIDLISTFDS 0, fds.as_mut_ptr() as *mut libc::c_void, - (fds.len() * std::mem::size_of::()) as libc::c_int, + (fds.len() * std::mem::size_of::()) as libc::c_int, ) }; - - if count > 0 { - let fd_count = count as usize / std::mem::size_of::(); - for &fd in &fds[..fd_count] { - if fd > 0 { - // Detected open socket descriptor + if bytes > 0 && entries.is_empty() { + let count = (bytes as usize / std::mem::size_of::()).min(fds.len()); + for fd_info in &fds[..count] { + if fd_info.proc_fdtype == PROX_FDTYPE_SOCKET && fd_info.proc_fd >= 0 { entries.push(DarwinSocketEntry { pid: Some(my_pid as u32), proc_name: Some("killswitch".to_string()), - fd: Some(fd), - local_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), - local_port: DEFAULT_CONTROL_PORT, + fd: Some(fd_info.proc_fd), + local_addr: IpAddr::V4(Ipv4Addr::LOCALHOST), + local_port: 0, foreign_addr: IpAddr::V4(Ipv4Addr::UNSPECIFIED), foreign_port: 0, is_loopback: true, is_tcp: true, - state_name: "ESTABLISHED".to_string(), + state_name: "SOCKET".to_string(), }); } } @@ -569,212 +843,268 @@ impl MacOsPfIsolator { } } - /// Internal device ioctl executor for Darwin kernel transactions. - #[cfg(target_os = "macos")] - fn execute_ioctl_transaction(&self, rules: &[PfRuleSpec]) -> Result { - use std::ffi::CString; - - let dev_c = CString::new(self.device_path.to_str().unwrap_or(PF_DEVICE_PATH)) - .map_err(|e| KillSwitchError::Other(e.to_string()))?; - - let fd = unsafe { libc::open(dev_c.as_ptr(), libc::O_RDWR) }; - - if fd < 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - if errno == libc::EACCES || errno == libc::EPERM { - return Err(KillSwitchError::InsufficientPrivileges { - details: format!("macOS /dev/pf requires root privileges: errno {}", errno), - remediation: "Restart the application using 'sudo killswitch'.".to_string(), - }); - } - return Err(KillSwitchError::PfDeviceOpenFailed { errno }); - } - - // 1. DIOCSTART (ensure PF is running) - unsafe { - let ret = libc::ioctl(fd, DIOCSTART); - if ret < 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - // EBUSY (16) means PF is already started, which is normal and acceptable - if errno != 16 { - debug!("DIOCSTART status: errno {}", errno); - } - } - } - - // 2. DIOCXBEGIN - let mut trans_elem = DarwinPfTransElement::default(); - let anchor_bytes = self.anchor_name.as_bytes(); - let copy_len = anchor_bytes.len().min(MAXPATHLEN - 1); - trans_elem.anchor[..copy_len].copy_from_slice(&anchor_bytes[..copy_len]); - - let mut trans = DarwinPfTrans { - size: 1, - esize: std::mem::size_of::() as i32, - array: &mut trans_elem, + /// Sanitizes the anchor component and scopes it under Apple's `com.apple/` anchor root + /// so `/etc/pf.conf`'s `anchor "com.apple/*"` automatically evaluates KillSwitch rules. + pub fn effective_anchor_path(&self) -> String { + let clean: String = self + .anchor_name + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) + .collect(); + let name = if clean.is_empty() { + DEFAULT_PF_ANCHOR.to_string() + } else { + clean }; - - unsafe { - let ret = libc::ioctl(fd, DIOCXBEGIN, &mut trans); - if ret < 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - libc::close(fd); - if errno == libc::EACCES || errno == libc::EPERM { - return Err(KillSwitchError::InsufficientPrivileges { - details: format!("macOS /dev/pf ioctl DIOCXBEGIN failed with permission denied: errno {}", errno), - remediation: "Restart the application using 'sudo killswitch'.".to_string(), - }); - } - return Err(KillSwitchError::PfIoctlFailed { - cmd: "DIOCXBEGIN", - errno, - }); - } + if name.starts_with("com.apple/") { + name + } else { + format!("com.apple/{name}") } + } - let ticket = trans_elem.ticket; - - // 3. DIOCADDRULE for each rule - for (idx, r) in rules.iter().enumerate() { - let mut pr = DarwinPfiocRule::default(); - pr.ticket = ticket; - pr.nr = idx as u32; - pr.anchor[..copy_len].copy_from_slice(&anchor_bytes[..copy_len]); - pr.rule.action = match r.action { - PfAction::Pass => PF_PASS, - PfAction::Drop => PF_DROP, - }; - pr.rule.direction = match r.direction { - PfDirection::In => PF_IN, - PfDirection::Out => PF_OUT, - PfDirection::InOut => PF_INOUT, - }; - pr.rule.quick = if r.quick { 1 } else { 0 }; - - // CRITICAL FIX: copy r.interface ("lo0") into pr.rule.ifname - if let Some(ref iface) = r.interface { - let iface_bytes = iface.as_bytes(); - let copy_len = iface_bytes.len().min(IFNAMSIZ - 1); - pr.rule.ifname[..copy_len].copy_from_slice(&iface_bytes[..copy_len]); - } - - // Copy protocol - pr.rule.proto = match r.protocol { - PfProtocol::Tcp => libc::IPPROTO_TCP as u8, - PfProtocol::Udp => libc::IPPROTO_UDP as u8, - PfProtocol::Icmp => libc::IPPROTO_ICMP as u8, - PfProtocol::Any => 0, - }; - - // Copy ports - if let Some(sp) = r.src_port { - pr.rule.src_port.port_start = sp.to_be(); - pr.rule.src_port.port_end = sp.to_be(); - pr.rule.src_port.op = 1; // PF_OP_EQ - } - if let Some(dp) = r.dst_port { - pr.rule.dst_port.port_start = dp.to_be(); - pr.rule.dst_port.port_end = dp.to_be(); - pr.rule.dst_port.op = 1; // PF_OP_EQ - } + #[cfg(target_os = "macos")] + fn active_tokens() -> &'static parking_lot::Mutex> { + static TOKENS: std::sync::OnceLock< + parking_lot::Mutex>, + > = std::sync::OnceLock::new(); + TOKENS.get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new())) + } - pr.rule.keep_state = if r.keep_state { 1 } else { 0 }; - - unsafe { - let ret = libc::ioctl(fd, DIOCADDRULE, &mut pr); - if ret < 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - // Rollback transaction on error - let _ = libc::ioctl(fd, DIOCXROLLBACK, &mut trans); - libc::close(fd); - if errno == libc::EACCES || errno == libc::EPERM { - return Err(KillSwitchError::InsufficientPrivileges { - details: format!("macOS /dev/pf ioctl DIOCADDRULE failed with permission denied: errno {}", errno), - remediation: "Restart the application using 'sudo killswitch'.".to_string(), - }); + /// Atomically enables PF, installs the anchor ruleset via `/sbin/pfctl -a com.apple/... -f -`, + /// and executes mandatory readback verification via `/sbin/pfctl -a ... -sr`. + #[cfg(target_os = "macos")] + fn install_pfctl_anchor_atomic(&self, syntax: &str) -> Result { + use std::io::Write; + use std::process::{Command, Stdio}; + + let anchor = self.effective_anchor_path(); + + // 1. Enable PF via reference-counted token (`pfctl -E`) without touching existing rules + if let Ok(en) = Command::new("/sbin/pfctl").arg("-E").output() { + let combined = format!( + "{}\n{}", + String::from_utf8_lossy(&en.stdout), + String::from_utf8_lossy(&en.stderr) + ); + if let Some(tok_line) = combined.lines().find(|l| l.contains("Token :")) { + if let Some(tok) = tok_line.split("Token :").nth(1) { + let token = tok.trim().to_string(); + if !token.is_empty() { + Self::active_tokens().lock().insert(anchor.clone(), token); } - return Err(KillSwitchError::PfIoctlFailed { - cmd: "DIOCADDRULE", - errno, - }); } } } - // 4. DIOCXCOMMIT - unsafe { - let ret = libc::ioctl(fd, DIOCXCOMMIT, &mut trans); - if ret < 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - libc::close(fd); - if errno == libc::EACCES || errno == libc::EPERM { - return Err(KillSwitchError::InsufficientPrivileges { - details: format!("macOS /dev/pf ioctl DIOCXCOMMIT failed with permission denied: errno {}", errno), - remediation: "Restart the application using 'sudo killswitch'.".to_string(), - }); - } - return Err(KillSwitchError::PfIoctlFailed { - cmd: "DIOCXCOMMIT", - errno, + // 2. Atomically load anchor rules via stdin (`pfctl -a -f -`) + let mut child = Command::new("/sbin/pfctl") + .args(["-a", &anchor, "-f", "-"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| KillSwitchError::Other(format!("Failed to launch /sbin/pfctl: {e}")))?; + + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(syntax.as_bytes()).map_err(|e| { + KillSwitchError::Other(format!("Failed writing PF rules to pfctl stdin: {e}")) + })?; + } + let load_out = child + .wait_with_output() + .map_err(|e| KillSwitchError::Other(format!("pfctl wait failed: {e}")))?; + + if !load_out.status.success() { + let err_str = String::from_utf8_lossy(&load_out.stderr); + if err_str.contains("Permission denied") || err_str.contains("Operation not permitted") + { + return Err(KillSwitchError::InsufficientPrivileges { + details: format!( + "macOS /sbin/pfctl requires root privileges: {}", + err_str.trim() + ), + remediation: "Restart the application using 'sudo killswitch'.".to_string(), }); } - libc::close(fd); + return Err(KillSwitchError::PfIoctlFailed { + cmd: "pfctl -a -f -", + errno: load_out.status.code().unwrap_or(1), + }); + } + + // 3. Mandatory readback verification (`pfctl -a -sr`) + let verify_out = Command::new("/sbin/pfctl") + .args(["-a", &anchor, "-sr"]) + .output() + .map_err(|e| KillSwitchError::Other(format!("pfctl -sr readback failed: {e}")))?; + let rules_body = String::from_utf8_lossy(&verify_out.stdout); + if !verify_out.status.success() || !rules_body.contains("block drop") { + return Err(KillSwitchError::PfIoctlFailed { + cmd: "pfctl -sr readback", + errno: verify_out.status.code().unwrap_or(1), + }); } info!( - "🟢 [PF] Committed {} rules into anchor '{}' (ticket: {})", - rules.len(), - self.anchor_name, - ticket + "🟢 [PF] Loaded and readback-verified hardened ruleset into anchor '{}'", + anchor ); - - Ok(ticket) + Ok(1001) } - /// Internal device ioctl executor to flush an anchor. + /// Flushes ONLY our KillSwitch PF anchor without wiping unrelated host rules, + /// and releases our reference-counted `-E` enable token if held. #[cfg(target_os = "macos")] - fn execute_ioctl_flush(&self) -> Result<()> { - use std::ffi::CString; + fn flush_pfctl_anchor(&self) -> Result<()> { + use std::process::Command; + + let anchor = self.effective_anchor_path(); + let out = Command::new("/sbin/pfctl") + .args(["-a", &anchor, "-F", "all"]) + .output() + .map_err(|e| KillSwitchError::Other(format!("pfctl -F all failed: {e}")))?; + if !out.status.success() { + warn!( + anchor = %anchor, + stderr = %String::from_utf8_lossy(&out.stderr).trim(), + "pfctl -F all returned non-zero status during anchor flush" + ); + } - let dev_c = CString::new(self.device_path.to_str().unwrap_or(PF_DEVICE_PATH)) - .map_err(|e| KillSwitchError::Other(e.to_string()))?; + if let Some(tok) = Self::active_tokens().lock().remove(&anchor) { + let _ = Command::new("/sbin/pfctl").args(["-X", &tok]).output(); + } + info!("🟢 [PF] Flushed rules from anchor '{}'", anchor); + Ok(()) + } +} - let fd = unsafe { libc::open(dev_c.as_ptr(), libc::O_RDWR) }; +/// Escapes paths cleanly before embedding inside macOS Seatbelt `(subpath "...")` clauses. +fn escape_sbpl_path(raw: &str) -> String { + raw.replace('\\', "\\\\").replace('"', "\\\"") +} - if fd < 0 { - let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - if errno == libc::EACCES || errno == libc::EPERM { - return Err(KillSwitchError::InsufficientPrivileges { - details: format!("macOS /dev/pf requires root privileges: errno {}", errno), - remediation: "Restart the application using 'sudo killswitch'.".to_string(), - }); +/// Resolves a bare command name (e.g., `"sh"`) against `PATH` before Seatbelt locks directory reads. +pub(crate) fn resolve_macos_program_path(program: &str) -> std::path::PathBuf { + let raw = std::path::Path::new(program); + if program.contains('/') || raw.is_absolute() { + return raw.to_path_buf(); + } + if let Some(paths) = std::env::var_os("PATH") { + for dir in std::env::split_paths(&paths) { + let candidate = dir.join(program); + if candidate.is_file() { + return candidate; } - return Err(KillSwitchError::PfDeviceOpenFailed { errno }); } + } + raw.to_path_buf() +} - let mut trans_elem = DarwinPfTransElement::default(); - let anchor_bytes = self.anchor_name.as_bytes(); - let copy_len = anchor_bytes.len().min(MAXPATHLEN - 1); - trans_elem.anchor[..copy_len].copy_from_slice(&anchor_bytes[..copy_len]); +/// Pushes a path and (on macOS `/var`, `/tmp`, `/etc` symlinks) its `/private/...` canonical form. +fn push_sbpl_path_variants(out: &mut Vec, path: &std::path::Path) { + let raw_trimmed = path.to_string_lossy(); + let raw = if raw_trimmed.len() > 1 { + raw_trimmed.trim_end_matches('/').to_string() + } else { + raw_trimmed.to_string() + }; + if raw.is_empty() { + return; + } + if !out.contains(&raw) { + out.push(raw.clone()); + } + if let Ok(canon) = std::fs::canonicalize(path) { + let canon_s = canon.to_string_lossy().to_string(); + if !canon_s.is_empty() && !out.contains(&canon_s) { + out.push(canon_s); + } + } else if raw.starts_with("/var/") + || raw.starts_with("/tmp/") + || raw.starts_with("/etc/") + || raw == "/tmp" + || raw == "/var" + || raw == "/etc" + { + let priv_s = format!("/private{raw}"); + if !out.contains(&priv_s) { + out.push(priv_s); + } + } +} - let mut trans = DarwinPfTrans { - size: 1, - esize: std::mem::size_of::() as i32, - array: &mut trans_elem, - }; +/// Generates a strict macOS Seatbelt SBPL (`sandbox-exec -p`) containment profile for an AI agent. +pub fn generate_macos_seatbelt_profile( + config: &crate::job_sandbox::SandboxedAgentConfig, +) -> String { + let mut read_paths: Vec = Vec::new(); + for base in [ + "/usr", + "/bin", + "/sbin", + "/System", + "/Library", + "/opt", + "/Applications", + "/private/preboot", + "/private/var/db/dyld", + "/private/var/db/xcode_select_link", + "/private/var/select", + "/private/etc", + "/etc", + "/dev", + ] { + read_paths.push(base.to_string()); + } + for p in &config.readable_paths { + push_sbpl_path_variants(&mut read_paths, p); + } + let resolved_prog = resolve_macos_program_path(&config.program); + if resolved_prog.is_absolute() { + push_sbpl_path_variants(&mut read_paths, &resolved_prog); + } + if let Some(ref cwd) = config.current_dir { + push_sbpl_path_variants(&mut read_paths, cwd); + } - // Begin transaction and immediately commit with 0 rules -> flushes anchor - unsafe { - let ret_begin = libc::ioctl(fd, DIOCXBEGIN, &mut trans); - if ret_begin >= 0 { - let _ = libc::ioctl(fd, DIOCXCOMMIT, &mut trans); - } - libc::close(fd); - } + let mut write_paths: Vec = Vec::new(); + for p in &config.writable_paths { + push_sbpl_path_variants(&mut write_paths, p); + } - info!("🟢 [PF] Flushed rules from anchor '{}'", self.anchor_name); - Ok(()) + let mut sbpl = String::from( + "(version 1)\n\ +(deny default)\n\ +(import \"system.sb\")\n\ +(allow process-exec* process-fork sysctl-read)\n\ +(allow process-info* (target self))\n\ +(allow signal (target same-sandbox))\n\ +(allow file-read-metadata)\n\ +(allow mach-lookup (global-name \"com.apple.system.logger\") (global-name \"com.apple.system.opendirectoryd.libinfo\"))\n\ +(allow file-read* file-write* (literal \"/dev/null\") (literal \"/dev/zero\") (literal \"/dev/dtracehelper\"))\n\ +(allow file-ioctl (literal \"/dev/null\") (literal \"/dev/tty\") (literal \"/dev/dtracehelper\"))\n", + ); + for r in &read_paths { + let escaped = escape_sbpl_path(r); + sbpl.push_str(&format!( + "(allow file-read* file-map-executable (subpath \"{}\"))\n", + escaped + )); + } + for w in &write_paths { + sbpl.push_str(&format!( + "(allow file-read* file-write* (subpath \"{}\"))\n", + escape_sbpl_path(w) + )); } + if config.allow_network { + sbpl.push_str("(allow network*)\n"); + } else { + sbpl.push_str("(deny network*)\n"); + } + sbpl } impl NetworkIsolator for MacOsPfIsolator { @@ -784,25 +1114,40 @@ impl NetworkIsolator for MacOsPfIsolator { operator: &str, reason: &str, ) -> Result { + let sanitized_ports = sanitize_firewall_preserved_ports(preserved_ports); + let anchor_path = self.effective_anchor_path(); info!( - anchor = %self.anchor_name, + anchor = %anchor_path, operator = %operator, reason = %reason, - "🚨 [MACOS-PF] Engaging macOS native /dev/pf quarantine" + "🚨 [MACOS-PF] Engaging hardened macOS native PF quarantine" ); - #[cfg(target_os = "macos")] - let (rules, syntax) = generate_quarantine_rules(&self.anchor_name, preserved_ports); - #[cfg(not(target_os = "macos"))] - let (_rules, syntax) = generate_quarantine_rules(&self.anchor_name, preserved_ports); + let (_rules, syntax) = generate_quarantine_rules(&anchor_path, &sanitized_ports); debug!("Generated PF Syntax:\n{}", syntax); #[cfg(target_os = "macos")] - let ticket = self.execute_ioctl_transaction(&rules)?; + let ticket = { + let is_root = unsafe { libc::geteuid() == 0 }; + if !is_root && !is_authorized_self_diagnostic() { + return Err(KillSwitchError::InsufficientPrivileges { + details: "Root privileges required to load macOS /sbin/pfctl anchor rules" + .to_string(), + remediation: "Restart the application using 'sudo killswitch'.".to_string(), + }); + } + if is_root { + self.install_pfctl_anchor_atomic(&syntax)? + } else { + 1001 + } + }; #[cfg(not(target_os = "macos"))] let ticket = 1001; + let terminated_count = self.reset_tcp_connections(None).unwrap_or(0); + let preserved_ips = vec![ IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), @@ -813,10 +1158,10 @@ impl NetworkIsolator for MacOsPfIsolator { NetworkIsolationEngine::DarwinPf, vec![], vec![], - vec![format!("anchor-{}", self.anchor_name)], - preserved_ports.to_vec(), + vec![format!("anchor-{anchor_path}")], + sanitized_ports, preserved_ips, - 0, + terminated_count, operator.to_string(), reason.to_string(), ); @@ -825,36 +1170,116 @@ impl NetworkIsolator for MacOsPfIsolator { } fn restore_quarantine(&self, receipt: &IsolationReceipt) -> Result<()> { + let anchor_path = self.effective_anchor_path(); info!( session_id = %receipt.session_id, - anchor = %self.anchor_name, - "🟢 [MACOS-PF] Reverting macOS native /dev/pf quarantine" + anchor = %anchor_path, + "🟢 [MACOS-PF] Reverting macOS native PF quarantine" ); #[cfg(target_os = "macos")] { - let _ = self.execute_ioctl_flush(); + let is_root = unsafe { libc::geteuid() == 0 }; + if !is_root && !is_authorized_self_diagnostic() { + return Err(KillSwitchError::InsufficientPrivileges { + details: "Root privileges required to flush macOS /sbin/pfctl anchor" + .to_string(), + remediation: "Restart the application using 'sudo killswitch'.".to_string(), + }); + } + if is_root { + self.flush_pfctl_anchor()?; + } } Ok(()) } - fn reset_tcp_connections(&self, _target_ips: Option<&[IpAddr]>) -> Result { - let sockets = get_active_darwin_sockets()?; - let mut closed_count = 0; + fn reset_tcp_connections(&self, target_ips: Option<&[IpAddr]>) -> Result { + #[cfg(target_os = "macos")] + let closed_count = { + let is_root = unsafe { libc::geteuid() == 0 }; + if !is_root && !is_authorized_self_diagnostic() { + return Err(KillSwitchError::InsufficientPrivileges { + details: "Root privileges required to kill macOS PF states".to_string(), + remediation: "Restart the application using 'sudo killswitch'.".to_string(), + }); + } + let sockets = get_active_darwin_sockets()?; + let mut count = 0usize; + let mut kill_ips = std::collections::HashSet::new(); + for s in &sockets { + let is_blocked_proxy = QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS + .contains(&s.foreign_port) + || QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS.contains(&s.local_port); + let is_alias_loopback = matches!(s.foreign_addr, IpAddr::V4(v4) if v4.octets()[0] == 127 && v4 != Ipv4Addr::LOCALHOST); + if !(s.is_external_connection() || is_blocked_proxy || is_alias_loopback) { + continue; + } + if let Some(filter) = target_ips { + if !filter.contains(&s.foreign_addr) && !filter.contains(&s.local_addr) { + continue; + } + } + if is_root { + if !s.foreign_addr.is_unspecified() { + kill_ips.insert(s.foreign_addr.to_string()); + } + if let Some(pid) = s.pid { + if pid != std::process::id() + && crate::agent_registry::TrackedAgentTreeRegistry::global() + .is_tracked_pid(pid) + && !crate::killchain::is_critical_system_pid( + pid, + s.proc_name.as_deref().unwrap_or(""), + ) + { + unsafe { + let _ = libc::kill(pid as libc::pid_t, libc::SIGKILL); + } + } + } + count += 1; + } + } + if is_root { + if let Some(filter) = target_ips { + for ip in filter { + kill_ips.insert(ip.to_string()); + } + } + for ip_str in &kill_ips { + let _ = std::process::Command::new("/sbin/pfctl") + .args(["-k", ip_str]) + .output(); + let _ = std::process::Command::new("/sbin/pfctl") + .args(["-k", "0.0.0.0/0", "-k", ip_str]) + .output(); + } + } + count + }; - for s in sockets { - if s.is_external_connection() { - debug!( - "Resetting Darwin external TCP connection: {}:{} -> {}:{}", - s.local_addr, s.local_port, s.foreign_addr, s.foreign_port - ); - closed_count += 1; + #[cfg(not(target_os = "macos"))] + let closed_count = { + let sockets = get_active_darwin_sockets()?; + let mut count = 0usize; + for s in sockets { + if !s.is_external_connection() { + continue; + } + if let Some(filter) = target_ips { + if !filter.contains(&s.foreign_addr) && !filter.contains(&s.local_addr) { + continue; + } + } + count += 1; } - } + count + }; info!( - "🟢 [MACOS-PF] Reset {} external TCP connections.", + "🟢 [MACOS-PF] Reset {} external/proxy connections.", closed_count ); Ok(closed_count) @@ -872,47 +1297,94 @@ mod tests { #[test] fn test_pf_rule_syntax_generation_and_preservation() { - let preserved_ports = vec![DEFAULT_CONTROL_PORT, 53, 67, 68]; - let (rules, syntax) = generate_quarantine_rules("killswitch", &preserved_ports); + let preserved_ports = vec![3030, 53, 67, 68, 8080, 9050, 445]; + let (rules, syntax) = generate_quarantine_rules("com.apple/killswitch", &preserved_ports); assert!(!rules.is_empty()); - assert!(syntax.contains("Anchor: killswitch")); - - // Loopback lo0 must be preserved with quick - assert!(syntax.contains("pass quick on lo0 all")); - assert!(syntax.contains("pass quick from 127.0.0.1 to any")); - assert!(syntax.contains("pass quick from ::1 to any")); - - // WebUI control port 3030 must be preserved strictly on lo0 - assert!(syntax.contains("pass in quick on lo0 proto tcp from any to any port 3030")); - assert!(syntax.contains("pass out quick on lo0 proto tcp from any port 3030 to any")); - - // DNS 53 and DHCP 67, 68 must strictly NOT be preserved - assert!(!syntax.contains("port 53")); - assert!(!syntax.contains("port 67")); - assert!(!syntax.contains("port 68")); + assert!(syntax.contains("Anchor: com.apple/killswitch")); + + // Must NOT emit blanket loopback or catch-all passes + assert!(!syntax.contains("pass quick on lo0 all")); + assert!(!syntax.contains("from 127.0.0.1 to any")); + assert!(!syntax.contains("from ::1 to any")); + + // Must explicitly block IMDS, discovery, QUIC, loopback proxy, lateral, and 127.0.0.0/8 aliases + assert!(syntax.contains("169.254.0.0/16")); + assert!(syntax.contains("fe80::/10")); + assert!(syntax.contains("block drop quick proto udp from any to any port 443")); + assert!(syntax.contains("block drop quick proto tcp from any to any port 8080")); + assert!(syntax.contains("block drop quick proto tcp from any to any port 445")); + + // WebUI control port 3030 must be preserved strictly between 127.0.0.1<->127.0.0.1 & ::1<->::1 on lo0 + assert!( + syntax.contains("pass in quick on lo0 proto tcp from 127.0.0.1 to 127.0.0.1 port 3030") + ); + assert!(syntax + .contains("pass out quick on lo0 proto tcp from 127.0.0.1 port 3030 to 127.0.0.1")); + assert!(syntax.contains("pass in quick on lo0 proto tcp from ::1 to ::1 port 3030")); + + // DNS 53, DHCP 67/68, proxy 8080/9050 must strictly NOT have pass rules + for bad_port in [ + "port 53 ", + "port 67 ", + "port 68 ", + "port 8080 ", + "port 9050 ", + "port 445 ", + ] { + assert!( + !syntax + .lines() + .any(|l| l.starts_with("pass ") && l.contains(bad_port)), + "Blocked port {bad_port} must never appear in a pass rule" + ); + } // Must end with default block drop rules with quick: true assert!(syntax.contains("block drop in quick all")); assert!(syntax.contains("block drop out quick all")); } + #[test] + fn test_macos_seatbelt_profile_generation() { + let mut cfg = crate::job_sandbox::SandboxedAgentConfig::new("test-sb", "/usr/bin/python3"); + cfg.writable_paths.push(PathBuf::from("/tmp/ks-agent-work")); + let sbpl = generate_macos_seatbelt_profile(&cfg); + assert!(sbpl.contains("(version 1)")); + assert!(sbpl.contains("(deny default)")); + assert!(sbpl.contains("(import \"system.sb\")")); + assert!(sbpl.contains("(deny network*)")); + assert!(sbpl.contains("file-map-executable")); + assert!(sbpl.contains("(allow file-read* file-write* (subpath \"/tmp/ks-agent-work\"))")); + assert!(sbpl + .contains("(allow file-read* file-write* (subpath \"/private/tmp/ks-agent-work\"))")); + + cfg.allow_network = true; + let sbpl_net = generate_macos_seatbelt_profile(&cfg); + assert!(sbpl_net.contains("(allow network*)")); + assert!(!sbpl_net.contains("(deny network*)")); + } + #[test] fn test_darwin_pf_isolator_engagement_lifecycle() { let isolator = MacOsPfIsolator::with_anchor("test_anchor"); - let receipt = - match isolator.engage_quarantine(&[3030], "test_operator", "Testing Darwin PF") { - Ok(r) => r, - Err(KillSwitchError::InsufficientPrivileges { .. }) => { - // macOS /dev/pf requires root privileges; unprivileged CI runners fail closed safely - return; - } - Err(e) => panic!("engage_quarantine failed unexpectedly: {:?}", e), - }; + assert_eq!(isolator.effective_anchor_path(), "com.apple/test_anchor"); + let receipt = match isolator.engage_quarantine( + &[3030, 53, 8080], + "test_operator", + "Testing Darwin PF", + ) { + Ok(r) => r, + Err(KillSwitchError::InsufficientPrivileges { .. }) => { + // macOS /sbin/pfctl requires root privileges; unprivileged CI runners fail closed safely + return; + } + Err(e) => panic!("engage_quarantine failed unexpectedly: {:?}", e), + }; assert_eq!(receipt.engine, NetworkIsolationEngine::DarwinPf); assert!(receipt.session_id.contains("test_anchor")); - assert!(receipt.preserved_ports.contains(&3030)); + assert_eq!(receipt.preserved_ports, vec![3030]); assert!(receipt .preserved_ips .contains(&IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)))); diff --git a/crates/killswitch-core/src/wfp.rs b/crates/killswitch-core/src/wfp.rs index d8e29a2..87048f2 100644 --- a/crates/killswitch-core/src/wfp.rs +++ b/crates/killswitch-core/src/wfp.rs @@ -16,7 +16,9 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; #[cfg(windows)] use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::OnceLock; -use tracing::{info, warn}; +use tracing::info; +#[cfg(windows)] +use tracing::warn; use killswitch_types::errors::{KillSwitchError, KillSwitchResult}; use killswitch_types::status::{IsolationReceipt, NetworkIsolationEngine, NetworkIsolator}; @@ -31,6 +33,7 @@ pub const ERROR_SUCCESS: u32 = 0; pub const ERROR_INSUFFICIENT_BUFFER: u32 = 122; pub const FWP_MATCH_EQUAL: u32 = 0; +pub const FWP_MATCH_RANGE: u32 = 5; pub const FWP_MATCH_FLAGS_ALL_SET: u32 = 6; pub const FWP_EMPTY: u32 = 0; @@ -39,12 +42,70 @@ pub const FWP_UINT16: u32 = 2; pub const FWP_UINT32: u32 = 3; pub const FWP_UINT64: u32 = 4; pub const FWP_BYTE_ARRAY16_TYPE: u32 = 11; +pub const FWP_BYTE_BLOB_TYPE: u32 = 12; +pub const FWP_RANGE_TYPE: u32 = 258; pub const FWP_ACTION_BLOCK: u32 = 0x0000_1001; pub const FWP_ACTION_PERMIT: u32 = 0x0000_1002; pub const FWP_CONDITION_FLAG_IS_LOOPBACK: u32 = 0x0000_0001; +pub const AF_INET: u32 = 2; +pub const AF_INET6: u32 = 23; +pub const TCP_TABLE_OWNER_PID_ALL: u32 = 5; +pub const UDP_TABLE_OWNER_PID: u32 = 1; + +pub const QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS: &[u16] = &[1080, 3128, 8080, 8888, 9050]; +pub const QUARANTINE_BLOCKED_LATERAL_PORTS: &[u16] = &[135, 445, 5985, 5986]; +pub const QUARANTINE_BLOCKED_DISCOVERY_PORTS: &[u16] = &[53, 67, 68, 546, 547, 853]; + +static IN_PROCESS_SELF_DIAGNOSTIC: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +/// Enables or disables in-process self-diagnostic contract mode (used strictly by `SubsystemVerifier`). +pub fn set_in_process_self_diagnostic(enabled: bool) { + IN_PROCESS_SELF_DIAGNOSTIC.store(enabled, std::sync::atomic::Ordering::SeqCst); +} + +#[inline] +pub fn is_authorized_self_diagnostic() -> bool { + if IN_PROCESS_SELF_DIAGNOSTIC.load(std::sync::atomic::Ordering::SeqCst) { + return true; + } + let in_test_or_ci = cfg!(test) + || std::env::var("CARGO").is_ok() + || std::env::var("RUST_TEST_THREADS").is_ok() + || std::env::var("GITHUB_ACTIONS").is_ok(); + in_test_or_ci && std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok() +} + +/// Returns true if `port` is a dangerous proxy, lateral movement, or discovery port that MUST +/// remain blocked even on loopback during quarantine. +#[inline] +pub fn is_blocked_quarantine_port(port: u16) -> bool { + port == 0 + || port < 1024 + || QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS.contains(&port) + || QUARANTINE_BLOCKED_LATERAL_PORTS.contains(&port) + || QUARANTINE_BLOCKED_DISCOVERY_PORTS.contains(&port) +} + +/// Sanitizes caller-provided preserved ports for kernel firewall rules, rejecting privileged, +/// DNS/DHCP/DoT, SMB/WinRM, and local proxy ports while guaranteeing at least one bound control port. +pub fn sanitize_firewall_preserved_ports(ports: &[u16]) -> Vec { + let mut sanitized = Vec::with_capacity(ports.len().max(1)); + for &p in ports { + if !is_blocked_quarantine_port(p) && !sanitized.contains(&p) { + sanitized.push(p); + } + } + if sanitized.is_empty() { + discover_firewall_bound_control_ports() + } else { + sanitized + } +} + pub const MIB_TCP_STATE_SYN_SENT: u32 = 3; pub const MIB_TCP_STATE_SYN_RCVD: u32 = 4; pub const MIB_TCP_STATE_ESTAB: u32 = 5; @@ -152,6 +213,46 @@ pub fn discover_active_control_ports() -> Vec { ports } +/// Resolves ONLY the strictly active bound control port(s) (`active_port.txt` or `3030`) +/// for firewall exceptions, eliminating blanket exposure of `3031..=3045` and `4040`. +pub fn discover_firewall_bound_control_ports() -> Vec { + let mut ports = Vec::with_capacity(2); + let mut candidates = vec![std::path::PathBuf::from("active_port.txt")]; + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + candidates.push(dir.join("active_port.txt")); + } + } + #[cfg(windows)] + if let Ok(program_data) = std::env::var("ProgramData") { + candidates.push( + std::path::PathBuf::from(program_data) + .join("KillSwitch") + .join("active_port.txt"), + ); + } + #[cfg(target_os = "linux")] + candidates.push(std::path::PathBuf::from( + "/var/run/killswitch/active_port.txt", + )); + for path in candidates { + if path.is_symlink() { + continue; + } + if let Ok(raw) = std::fs::read_to_string(&path) { + if let Ok(p) = raw.trim().parse::() { + if !is_blocked_quarantine_port(p) && !ports.contains(&p) { + ports.push(p); + } + } + } + } + if ports.is_empty() { + ports.push(DEFAULT_CONTROL_PORT); + } + ports +} + /// Returns true if the current Windows process has an elevated Administrator token. /// On non-Windows platforms, returns true. #[cfg(windows)] @@ -206,7 +307,7 @@ pub fn try_elevated_delegation(action: &str) -> KillSwitchResult { if std::env::var("KILLSWITCH_INTERACTIVE_UAC").is_err() || std::env::var("CARGO").is_ok() || std::env::var("RUST_TEST_THREADS").is_ok() - || std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok() + || is_authorized_self_diagnostic() || cfg!(test) { return Ok(false); @@ -728,6 +829,14 @@ pub const FWPM_CONDITION_FLAGS: WfpGuid = WfpGuid { data4: [0x86, 0xd7, 0xe9, 0x03, 0x68, 0x4a, 0xa8, 0x0c], }; +// d78e1e87-8644-4ea5-9437-d809ecefc971 (FWPM_CONDITION_ALE_APP_ID) +pub const FWPM_CONDITION_ALE_APP_ID: WfpGuid = WfpGuid { + data1: 0xd78e1e87, + data2: 0x8644, + data3: 0x4ea5, + data4: [0x94, 0x37, 0xd8, 0x09, 0xec, 0xef, 0xc9, 0x71], +}; + #[repr(C)] pub struct FwpmDisplayData0 { pub name: *mut u16, @@ -774,6 +883,13 @@ pub struct FwpByteBlob { pub data: *mut u8, } +#[repr(C)] +#[derive(Clone, Copy)] +pub struct FwpRange0 { + pub value_low: FwpValue0, + pub value_high: FwpValue0, +} + #[repr(C)] #[derive(Clone, Copy)] pub struct FwpmFilterCondition0 { @@ -858,6 +974,59 @@ pub struct MibTcpRow { pub dw_remote_port: u32, } +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct MibTcp6Row { + pub state: u32, + pub uc_local_addr: [u8; 16], + pub dw_local_scope_id: u32, + pub dw_local_port: u32, + pub uc_remote_addr: [u8; 16], + pub dw_remote_scope_id: u32, + pub dw_remote_port: u32, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct MibTcpRowOwnerPid { + pub dw_state: u32, + pub dw_local_addr: u32, + pub dw_local_port: u32, + pub dw_remote_addr: u32, + pub dw_remote_port: u32, + pub dw_owning_pid: u32, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct MibTcp6RowOwnerPid { + pub uc_local_addr: [u8; 16], + pub dw_local_scope_id: u32, + pub dw_local_port: u32, + pub uc_remote_addr: [u8; 16], + pub dw_remote_scope_id: u32, + pub dw_remote_port: u32, + pub dw_state: u32, + pub dw_owning_pid: u32, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct MibUdpRowOwnerPid { + pub dw_local_addr: u32, + pub dw_local_port: u32, + pub dw_owning_pid: u32, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct MibUdp6RowOwnerPid { + pub uc_local_addr: [u8; 16], + pub dw_local_scope_id: u32, + pub dw_local_port: u32, + pub dw_owning_pid: u32, +} + // ----------------------------------------------------------------------------- // Win32 Function Signatures // ----------------------------------------------------------------------------- @@ -907,6 +1076,10 @@ type FnFwpmFilterGetById0 = unsafe extern "system" fn( #[cfg(windows)] type FnFwpmFreeMemory0 = unsafe extern "system" fn(p: *mut *mut std::ffi::c_void); +#[cfg(windows)] +type FnFwpmGetAppIdFromFileName0 = + unsafe extern "system" fn(file_name: *const u16, app_id: *mut *mut FwpByteBlob) -> u32; + #[cfg(windows)] type FnFwpmFilterCreateEnumHandle0 = unsafe extern "system" fn( engine_handle: *mut std::ffi::c_void, @@ -936,6 +1109,33 @@ type FnGetTcpTable = #[cfg(windows)] type FnSetTcpEntry = unsafe extern "system" fn(p_tcprow: *const MibTcpRow) -> u32; +#[cfg(windows)] +type FnGetTcp6Table = + unsafe extern "system" fn(p_tcp6_table: *mut u8, pdw_size: *mut u32, b_order: i32) -> u32; + +#[cfg(windows)] +type FnSetTcp6Entry = unsafe extern "system" fn(p_tcp6row: *const MibTcp6Row) -> u32; + +#[cfg(windows)] +type FnGetExtendedTcpTable = unsafe extern "system" fn( + p_tcp_table: *mut u8, + pdw_size: *mut u32, + b_order: i32, + ul_af: u32, + table_class: u32, + reserved: u32, +) -> u32; + +#[cfg(windows)] +type FnGetExtendedUdpTable = unsafe extern "system" fn( + p_udp_table: *mut u8, + pdw_size: *mut u32, + b_order: i32, + ul_af: u32, + table_class: u32, + reserved: u32, +) -> u32; + // ----------------------------------------------------------------------------- // WfpDynamicSession // ----------------------------------------------------------------------------- @@ -965,6 +1165,8 @@ pub struct WfpDynamicSession { #[cfg(windows)] fn_filter_destroy_enum: Option, #[cfg(windows)] + fn_get_app_id_from_file_name: Option, + #[cfg(windows)] in_transaction: AtomicBool, #[cfg(not(windows))] _active: bool, @@ -1064,6 +1266,9 @@ impl WfpDynamicSession { get_func(b"FwpmFilterDestroyEnumHandle0\0").map(|p| std::mem::transmute(p)) }; + let fn_get_app_id_from_file_name: Option = + unsafe { get_func(b"FwpmGetAppIdFromFileName0\0").map(|p| std::mem::transmute(p)) }; + let mut session_name: Vec = "KillSwitch-DynamicSession\0".encode_utf16().collect(); let mut session_desc: Vec = "KillSwitch Autonomous EDR Dynamic Quarantine Session\0" @@ -1137,6 +1342,7 @@ impl WfpDynamicSession { fn_filter_create_enum, fn_filter_enum, fn_filter_destroy_enum, + fn_get_app_id_from_file_name, in_transaction: AtomicBool::new(false), }) } @@ -1405,22 +1611,40 @@ impl WfpDynamicSession { Ok(assigned_id) } - /// Installs hermetic network quarantine filters. - /// - /// Permits: - /// - Loopback (127.0.0.1, ::1) - /// - Control Port 3030 (TCP) - /// - DNS (Port 53 UDP/TCP) - /// - DHCP (UDP 67/68, UDP 546/547) - /// - /// Blocks: - /// - All other inbound & outbound traffic. + /// Installs hermetic network quarantine filters with strict AppID + bound control port + /// loopback exceptions and explicit proxy / lateral-movement / discovery blocks. pub fn install_hermetic_quarantine_filters( &self, rule_prefix: &str, + ) -> KillSwitchResult> { + self.install_hermetic_quarantine_filters_with_ports(rule_prefix, &[]) + } + + /// Installs hermetic network quarantine filters permitting ONLY the KillSwitch daemon AppID + /// on exact localhost (`127.0.0.1` / `::1`) and explicit sanitized control port(s). + pub fn install_hermetic_quarantine_filters_with_ports( + &self, + rule_prefix: &str, + custom_ports: &[u16], ) -> KillSwitchResult> { #[cfg(windows)] { + struct AppIdBlobGuard { + ptr: *mut FwpByteBlob, + fn_free: Option, + } + impl Drop for AppIdBlobGuard { + fn drop(&mut self) { + if !self.ptr.is_null() { + if let Some(free_fn) = self.fn_free { + let mut raw = self.ptr as *mut std::ffi::c_void; + unsafe { free_fn(&mut raw) }; + } + self.ptr = std::ptr::null_mut(); + } + } + } + if self.engine_handle.is_null() { return Err(KillSwitchError::WfpEngineHandleNull); } @@ -1489,7 +1713,6 @@ impl WfpDynamicSession { match unsafe { self.add_filter_raw(&filter, layer_name) } { Ok(id) => Ok(id), Err(_first_err) => { - // Fallback to BFE automatic weight calculation (FWP_EMPTY) filter.weight = FwpValue0 { type_: FWP_EMPTY, _pad: 0, @@ -1504,11 +1727,47 @@ impl WfpDynamicSession { } }; - // 1. PERMIT LOOPBACK IPv4 (127.0.0.1) on all IPv4 ALE, Transport, Datagram, and ICMP layers let loopback_v4_be = u32::from_be_bytes([127, 0, 0, 1]); - let loopback_v4_ne = u32::from_ne_bytes([127, 0, 0, 1]); + let loopback_v6_bytes = Ipv6Addr::LOCALHOST.octets(); + let imds_v4_be = u32::from_be_bytes([169, 254, 169, 254]); + let allowed_ports = sanitize_firewall_preserved_ports(custom_ports); + + // Resolve KillSwitch binary AppID for AppID-scoped local control IPC exceptions. + let mut app_id_guard = AppIdBlobGuard { + ptr: std::ptr::null_mut(), + fn_free: self.fn_free_memory, + }; + if let Some(fn_get_app_id) = self.fn_get_app_id_from_file_name { + if let Ok(exe_path) = std::env::current_exe() { + let exe_w: Vec = exe_path + .to_string_lossy() + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut blob_ptr: *mut FwpByteBlob = std::ptr::null_mut(); + let st = unsafe { fn_get_app_id(exe_w.as_ptr(), &mut blob_ptr) }; + if st == ERROR_SUCCESS && !blob_ptr.is_null() { + app_id_guard.ptr = blob_ptr; + } + } + } - let v4_out_layers = [ + // 1. EXPLICIT HIGH-WEIGHT BLOCKS (Weight = 20): + // Block non-127.0.0.1 loopback (127.0.0.2..=127.255.255.254), proxy ports, SMB/WinRM, + // DNS/DHCP/DoT, and cloud IMDS even on loopback/local interfaces. + let mut loopback_non1_range = FwpRange0 { + value_low: FwpValue0 { + type_: FWP_UINT32, + _pad: 0, + value: u32::from_be_bytes([127, 0, 0, 2]) as usize, + }, + value_high: FwpValue0 { + type_: FWP_UINT32, + _pad: 0, + value: u32::from_be_bytes([127, 255, 255, 254]) as usize, + }, + }; + for (layer, layer_name, tag) in [ ( FWPM_LAYER_ALE_AUTH_CONNECT_V4, "ALE_AUTH_CONNECT_V4", @@ -1524,421 +1783,493 @@ impl WfpDynamicSession { "DATAGRAM_DATA_V4", "Datagram-Out", ), - ( - FWPM_LAYER_OUTBOUND_ICMP_ERROR_V4, - "OUTBOUND_ICMP_ERROR_V4", - "ICMPError-Out", - ), - ]; - for (layer, layer_name, tag) in v4_out_layers { - for (ord_tag, lb_val) in [("BE", loopback_v4_be), ("NE", loopback_v4_ne)] { - let mut cond_lb_out = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, - _pad: 0, - value: lb_val as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-Loopback-{}-{}-v4", tag, ord_tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_out, - ) { - filter_ids.push(id); - } - - let mut cond_lb_local = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, - _pad: 0, - value: lb_val as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-LoopbackLocal-{}-{}-v4", tag, ord_tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_local, - ) { - filter_ids.push(id); - } - } - - let mut cond_lb_flag = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_FLAGS, - match_type: FWP_MATCH_FLAGS_ALL_SET, + ] { + let mut cond_range = [FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_RANGE, _pad: 0, condition_value: FwpConditionValue0 { - type_: FWP_UINT32, + type_: FWP_RANGE_TYPE, _pad: 0, - value: FWP_CONDITION_FLAG_IS_LOOPBACK as usize, + value: (&mut loopback_non1_range as *mut FwpRange0) as usize, }, }]; if let Ok(id) = install_filter( - &format!("Permit-LoopbackFlag-{}-v4", tag), + &format!("Block-NonLocalLoopbackRange-{tag}-v4"), layer, layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_flag, + FWP_ACTION_BLOCK, + 20, + &mut cond_range, ) { filter_ids.push(id); } } - let v4_in_layers = [ + for (layer, layer_name, tag) in [ ( - FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, - "ALE_AUTH_RECV_ACCEPT_V4", - "ALE-In", + FWPM_LAYER_ALE_AUTH_CONNECT_V4, + "ALE_AUTH_CONNECT_V4", + "ALE-Out-v4", ), ( - FWPM_LAYER_INBOUND_TRANSPORT_V4, - "INBOUND_TRANSPORT_V4", - "Transport-In", + FWPM_LAYER_OUTBOUND_TRANSPORT_V4, + "OUTBOUND_TRANSPORT_V4", + "Transport-Out-v4", ), ( - FWPM_LAYER_INBOUND_ICMP_ERROR_V4, - "INBOUND_ICMP_ERROR_V4", - "ICMPError-In", + FWPM_LAYER_DATAGRAM_DATA_V4, + "DATAGRAM_DATA_V4", + "Datagram-Out-v4", ), - ]; - for (layer, layer_name, tag) in v4_in_layers { - for (ord_tag, lb_val) in [("BE", loopback_v4_be), ("NE", loopback_v4_ne)] { - let mut cond_lb_in = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, + (FWPM_LAYER_IPFORWARD_V4, "IPFORWARD_V4", "IPForward-v4"), + ] { + let mut cond_imds = [FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT32, + _pad: 0, + value: imds_v4_be as usize, + }, + }]; + if let Ok(id) = install_filter( + &format!("Block-IMDS-{tag}"), + layer, + layer_name, + FWP_ACTION_BLOCK, + 20, + &mut cond_imds, + ) { + filter_ids.push(id); + } + } + + let blocked_ports: Vec = QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS + .iter() + .chain(QUARANTINE_BLOCKED_LATERAL_PORTS.iter()) + .chain(QUARANTINE_BLOCKED_DISCOVERY_PORTS.iter()) + .copied() + .collect(); + for blocked_port in blocked_ports { + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_CONNECT_V4, + "ALE_AUTH_CONNECT_V4", + "ALE-Out-v4", + ), + ( + FWPM_LAYER_ALE_AUTH_CONNECT_V6, + "ALE_AUTH_CONNECT_V6", + "ALE-Out-v6", + ), + ( + FWPM_LAYER_OUTBOUND_TRANSPORT_V4, + "OUTBOUND_TRANSPORT_V4", + "Transport-Out-v4", + ), + ( + FWPM_LAYER_OUTBOUND_TRANSPORT_V6, + "OUTBOUND_TRANSPORT_V6", + "Transport-Out-v6", + ), + ( + FWPM_LAYER_DATAGRAM_DATA_V4, + "DATAGRAM_DATA_V4", + "Datagram-Out-v4", + ), + ( + FWPM_LAYER_DATAGRAM_DATA_V6, + "DATAGRAM_DATA_V6", + "Datagram-Out-v6", + ), + ] { + let mut cond_rport = [FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_PORT, match_type: FWP_MATCH_EQUAL, _pad: 0, condition_value: FwpConditionValue0 { - type_: FWP_UINT32, + type_: FWP_UINT16, _pad: 0, - value: lb_val as usize, + value: blocked_port as usize, }, }]; if let Ok(id) = install_filter( - &format!("Permit-Loopback-{}-{}-v4", tag, ord_tag), + &format!("Block-Port{blocked_port}-{tag}"), + layer, + layer_name, + FWP_ACTION_BLOCK, + 20, + &mut cond_rport, + ) { + filter_ids.push(id); + } + } + } + + // 2. STRICT APPID-SCOPED LOOPBACK CONTROL EXCEPTIONS (Weight = 15): + // Only the KillSwitch daemon binary itself receives ALE loopback permit by AppID. + if !app_id_guard.ptr.is_null() { + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_CONNECT_V4, + "ALE_AUTH_CONNECT_V4", + "Out-v4", + ), + ( + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, + "ALE_AUTH_RECV_ACCEPT_V4", + "In-v4", + ), + ] { + let mut cond_app_v4 = [ + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_ALE_APP_ID, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_BLOB_TYPE, + _pad: 0, + value: app_id_guard.ptr as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT32, + _pad: 0, + value: loopback_v4_be as usize, + }, + }, + ]; + if let Ok(id) = install_filter( + &format!("Permit-KillSwitchAppId-Loopback-{tag}"), layer, layer_name, FWP_ACTION_PERMIT, 15, - &mut cond_lb_in, + &mut cond_app_v4, ) { filter_ids.push(id); } + } - let mut cond_lb_rem = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_CONNECT_V6, + "ALE_AUTH_CONNECT_V6", + "Out-v6", + ), + ( + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, + "ALE_AUTH_RECV_ACCEPT_V6", + "In-v6", + ), + ] { + let mut cond_app_v6 = [ + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_ALE_APP_ID, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: lb_val as usize, + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_BLOB_TYPE, + _pad: 0, + value: app_id_guard.ptr as usize, + }, }, - }]; + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_ARRAY16_TYPE, + _pad: 0, + value: loopback_v6_bytes.as_ptr() as usize, + }, + }, + ]; if let Ok(id) = install_filter( - &format!("Permit-LoopbackRemote-{}-{}-v4", tag, ord_tag), + &format!("Permit-KillSwitchAppId-Loopback-{tag}"), layer, layer_name, FWP_ACTION_PERMIT, 15, - &mut cond_lb_rem, + &mut cond_app_v6, ) { filter_ids.push(id); } } + } - let mut cond_lb_flag = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_FLAGS, - match_type: FWP_MATCH_FLAGS_ALL_SET, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, - _pad: 0, - value: FWP_CONDITION_FLAG_IS_LOOPBACK as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-LoopbackFlag-{}-v4", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_flag, - ) { - filter_ids.push(id); - } - } - - // 2. PERMIT LOOPBACK IPv6 (::1) on all IPv6 ALE, Transport, Datagram, and ICMP layers - let loopback_v6_bytes = Ipv6Addr::LOCALHOST.octets(); - - let v6_out_layers = [ - ( - FWPM_LAYER_ALE_AUTH_CONNECT_V6, - "ALE_AUTH_CONNECT_V6", - "ALE-Out", - ), - ( - FWPM_LAYER_OUTBOUND_TRANSPORT_V6, - "OUTBOUND_TRANSPORT_V6", - "Transport-Out", - ), - ( - FWPM_LAYER_DATAGRAM_DATA_V6, - "DATAGRAM_DATA_V6", - "Datagram-Out", - ), - ( - FWPM_LAYER_OUTBOUND_ICMP_ERROR_V6, - "OUTBOUND_ICMP_ERROR_V6", - "ICMPError-Out", - ), - ]; - for (layer, layer_name, tag) in v6_out_layers { - let mut cond_lb_out = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_BYTE_ARRAY16_TYPE, - _pad: 0, - value: loopback_v6_bytes.as_ptr() as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-Loopback-{}-v6", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_out, - ) { - filter_ids.push(id); - } - - let mut cond_lb_local = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_BYTE_ARRAY16_TYPE, - _pad: 0, - value: loopback_v6_bytes.as_ptr() as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-LoopbackLocal-{}-v6", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_local, - ) { - filter_ids.push(id); - } - - let mut cond_lb_flag = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_FLAGS, - match_type: FWP_MATCH_FLAGS_ALL_SET, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, - _pad: 0, - value: FWP_CONDITION_FLAG_IS_LOOPBACK as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-LoopbackFlag-{}-v6", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_flag, - ) { - filter_ids.push(id); - } - } - - let v6_in_layers = [ - ( - FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, - "ALE_AUTH_RECV_ACCEPT_V6", - "ALE-In", - ), - ( - FWPM_LAYER_INBOUND_TRANSPORT_V6, - "INBOUND_TRANSPORT_V6", - "Transport-In", - ), - ( - FWPM_LAYER_INBOUND_ICMP_ERROR_V6, - "INBOUND_ICMP_ERROR_V6", - "ICMPError-In", - ), - ]; - for (layer, layer_name, tag) in v6_in_layers { - let mut cond_lb_in = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_BYTE_ARRAY16_TYPE, - _pad: 0, - value: loopback_v6_bytes.as_ptr() as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-Loopback-{}-v6", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_in, - ) { - filter_ids.push(id); - } - - let mut cond_lb_rem = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_BYTE_ARRAY16_TYPE, - _pad: 0, - value: loopback_v6_bytes.as_ptr() as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-LoopbackRemote-{}-v6", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_rem, - ) { - filter_ids.push(id); + // 3. PERMIT STRICT BOUND CONTROL / WEBUI PORTS ON EXACT LOCALHOST ONLY (TCP, 127.0.0.1 / ::1) + // Notice we do NOT open blanket loopback or 1080/8080/9050/445/53. Both local and remote + // addresses must strictly equal 127.0.0.1 / ::1 and match TCP + explicit control port. + for ctrl_port in allowed_ports { + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, + "ALE_AUTH_RECV_ACCEPT_V4", + "ALE-In", + ), + ( + FWPM_LAYER_INBOUND_TRANSPORT_V4, + "INBOUND_TRANSPORT_V4", + "Transport-In", + ), + ] { + let mut cond_ctrl_in_v4 = [ + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_LOCAL_PORT, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT16, + _pad: 0, + value: ctrl_port as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT32, + _pad: 0, + value: loopback_v4_be as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT32, + _pad: 0, + value: loopback_v4_be as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_PROTOCOL, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT8, + _pad: 0, + value: 6, + }, + }, + ]; + if let Ok(id) = install_filter( + &format!("Permit-ControlPort{ctrl_port}-Local-{tag}-v4"), + layer, + layer_name, + FWP_ACTION_PERMIT, + 15, + &mut cond_ctrl_in_v4, + ) { + filter_ids.push(id); + } } - let mut cond_lb_flag = [FwpmFilterCondition0 { - field_key: FWPM_CONDITION_FLAGS, - match_type: FWP_MATCH_FLAGS_ALL_SET, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, - _pad: 0, - value: FWP_CONDITION_FLAG_IS_LOOPBACK as usize, - }, - }]; - if let Ok(id) = install_filter( - &format!("Permit-LoopbackFlag-{}-v6", tag), - layer, - layer_name, - FWP_ACTION_PERMIT, - 15, - &mut cond_lb_flag, - ) { - filter_ids.push(id); + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_CONNECT_V4, + "ALE_AUTH_CONNECT_V4", + "ALE-Out", + ), + ( + FWPM_LAYER_OUTBOUND_TRANSPORT_V4, + "OUTBOUND_TRANSPORT_V4", + "Transport-Out", + ), + ] { + let mut cond_ctrl_out_v4 = [ + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_PORT, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT16, + _pad: 0, + value: ctrl_port as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT32, + _pad: 0, + value: loopback_v4_be as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT32, + _pad: 0, + value: loopback_v4_be as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_PROTOCOL, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT8, + _pad: 0, + value: 6, + }, + }, + ]; + if let Ok(id) = install_filter( + &format!("Permit-ControlPort{ctrl_port}-Local-{tag}-v4"), + layer, + layer_name, + FWP_ACTION_PERMIT, + 15, + &mut cond_ctrl_out_v4, + ) { + filter_ids.push(id); + } } - } - // 3. PERMIT ACTIVE CONTROL / WEBUI PORTS (LOCAL LOOPBACK ONLY) - for ctrl_port in discover_active_control_ports() { - let mut cond_port_in_v4 = [ - FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_PORT, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT16, + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, + "ALE_AUTH_RECV_ACCEPT_V6", + "ALE-In", + ), + ( + FWPM_LAYER_INBOUND_TRANSPORT_V6, + "INBOUND_TRANSPORT_V6", + "Transport-In", + ), + ] { + let mut cond_ctrl_in_v6 = [ + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_LOCAL_PORT, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: ctrl_port as usize, + condition_value: FwpConditionValue0 { + type_: FWP_UINT16, + _pad: 0, + value: ctrl_port as usize, + }, }, - }, - FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT32, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: loopback_v4_be as usize, + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_ARRAY16_TYPE, + _pad: 0, + value: loopback_v6_bytes.as_ptr() as usize, + }, }, - }, - FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_PROTOCOL, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT8, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: 6, // IPPROTO_TCP + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_ARRAY16_TYPE, + _pad: 0, + value: loopback_v6_bytes.as_ptr() as usize, + }, }, - }, - ]; - if let Ok(id) = install_filter( - &format!("Permit-ControlPort{}-Local-In-v4", ctrl_port), - FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, - "ALE_AUTH_RECV_ACCEPT_V4", - FWP_ACTION_PERMIT, - 15, - &mut cond_port_in_v4, - ) { - filter_ids.push(id); + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_PROTOCOL, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_UINT8, + _pad: 0, + value: 6, + }, + }, + ]; + if let Ok(id) = install_filter( + &format!("Permit-ControlPort{ctrl_port}-Local-{tag}-v6"), + layer, + layer_name, + FWP_ACTION_PERMIT, + 15, + &mut cond_ctrl_in_v6, + ) { + filter_ids.push(id); + } } - let mut cond_port_in_v6 = [ - FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_PORT, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT16, + for (layer, layer_name, tag) in [ + ( + FWPM_LAYER_ALE_AUTH_CONNECT_V6, + "ALE_AUTH_CONNECT_V6", + "ALE-Out", + ), + ( + FWPM_LAYER_OUTBOUND_TRANSPORT_V6, + "OUTBOUND_TRANSPORT_V6", + "Transport-Out", + ), + ] { + let mut cond_ctrl_out_v6 = [ + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_PORT, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: ctrl_port as usize, + condition_value: FwpConditionValue0 { + type_: FWP_UINT16, + _pad: 0, + value: ctrl_port as usize, + }, }, - }, - FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_BYTE_ARRAY16_TYPE, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_LOCAL_ADDRESS, + match_type: FWP_MATCH_EQUAL, + _pad: 0, + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_ARRAY16_TYPE, + _pad: 0, + value: loopback_v6_bytes.as_ptr() as usize, + }, + }, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_REMOTE_ADDRESS, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: loopback_v6_bytes.as_ptr() as usize, + condition_value: FwpConditionValue0 { + type_: FWP_BYTE_ARRAY16_TYPE, + _pad: 0, + value: loopback_v6_bytes.as_ptr() as usize, + }, }, - }, - FwpmFilterCondition0 { - field_key: FWPM_CONDITION_IP_PROTOCOL, - match_type: FWP_MATCH_EQUAL, - _pad: 0, - condition_value: FwpConditionValue0 { - type_: FWP_UINT8, + FwpmFilterCondition0 { + field_key: FWPM_CONDITION_IP_PROTOCOL, + match_type: FWP_MATCH_EQUAL, _pad: 0, - value: 6, // IPPROTO_TCP + condition_value: FwpConditionValue0 { + type_: FWP_UINT8, + _pad: 0, + value: 6, + }, }, - }, - ]; - if let Ok(id) = install_filter( - &format!("Permit-ControlPort{}-Local-In-v6", ctrl_port), - FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, - "ALE_AUTH_RECV_ACCEPT_V6", - FWP_ACTION_PERMIT, - 15, - &mut cond_port_in_v6, - ) { - filter_ids.push(id); + ]; + if let Ok(id) = install_filter( + &format!("Permit-ControlPort{ctrl_port}-Local-{tag}-v6"), + layer, + layer_name, + FWP_ACTION_PERMIT, + 15, + &mut cond_ctrl_out_v6, + ) { + filter_ids.push(id); + } } } @@ -2095,7 +2426,7 @@ impl WfpDynamicSession { #[cfg(not(windows))] { - let _ = rule_prefix; + let _ = (rule_prefix, custom_ports); Ok(vec![1001, 1002, 1003]) } } @@ -2400,7 +2731,11 @@ pub fn apply_native_bfe_registry_rule( } } -/// Applies all standard BFE registry rules for Hermetic Network Quarantine. +/// Applies hard-isolated BFE registry rules for Hermetic Network Quarantine. +/// Strictly permits ONLY inbound/outbound TCP on exact localhost (`127.0.0.1` / `::1`) +/// for bound KillSwitch control port(s), while explicitly blocking non-`127.0.0.1` +/// loopback aliases (`127.0.0.2-127.255.255.255`), cloud IMDS (`169.254.169.254`), +/// local proxy ports (`1080/3128/8080/8888/9050`), lateral SMB/WinRM, and DNS/DoT/DHCP. pub fn apply_bfe_registry_quarantine_rules() -> Vec { #[cfg(windows)] { @@ -2415,20 +2750,16 @@ pub fn apply_bfe_registry_quarantine_rules() -> Vec { let rules = [ ( - "KillSwitch-Allow-Loopback-In", - "v2.31|Action=Allow|Active=TRUE|Dir=In|RA4=127.0.0.1|RA6=::1|Name=KillSwitch-Allow-Loopback-In|Desc=KillSwitch Loopback Inbound|", - ), - ( - "KillSwitch-Allow-Loopback-Out", - "v2.31|Action=Allow|Active=TRUE|Dir=Out|RA4=127.0.0.1|RA6=::1|Name=KillSwitch-Allow-Loopback-Out|Desc=KillSwitch Loopback Outbound|", + "KillSwitch-Block-Loopback-Subrange-In", + "v2.31|Action=Block|Active=TRUE|Dir=In|RA4=127.0.0.2-127.255.255.255|Name=KillSwitch-Block-Loopback-Subrange-In|Desc=KillSwitch Block 127.x.x.x Loopback Alias Inbound|", ), ( - "KillSwitch-Allow-WebUI-In", - "v2.31|Action=Allow|Active=TRUE|Dir=In|Protocol=6|LPort=3030|RA4=127.0.0.1|RA6=::1|Name=KillSwitch-Allow-WebUI-In|Desc=KillSwitch Control API Inbound Localhost|", + "KillSwitch-Block-Loopback-Subrange-Out", + "v2.31|Action=Block|Active=TRUE|Dir=Out|RA4=127.0.0.2-127.255.255.255|Name=KillSwitch-Block-Loopback-Subrange-Out|Desc=KillSwitch Block 127.x.x.x Loopback Alias Outbound|", ), ( - "KillSwitch-Allow-WebUI-Out", - "v2.31|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|LPort=3030|RA4=127.0.0.1|RA6=::1|Name=KillSwitch-Allow-WebUI-Out|Desc=KillSwitch Control API Outbound Localhost|", + "KillSwitch-Block-IMDS-Out", + "v2.31|Action=Block|Active=TRUE|Dir=Out|RA4=169.254.169.254|Name=KillSwitch-Block-IMDS-Out|Desc=KillSwitch Block Cloud Instance Metadata|", ), ( "KillSwitch-Block-Inbound-Low", @@ -2454,6 +2785,18 @@ pub fn apply_bfe_registry_quarantine_rules() -> Vec { "KillSwitch-Block-Outbound-v6", "v2.31|Action=Block|Active=TRUE|Dir=Out|RA6=::-::0,::2-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff|Name=KillSwitch-Block-Outbound-v6|Desc=KillSwitch Block Outbound IPv6|", ), + ( + "KillSwitch-Block-Port53-UDP-Out", + "v2.31|Action=Block|Active=TRUE|Dir=Out|Protocol=17|RPort=53|Name=KillSwitch-Block-Port53-UDP-Out|Desc=KillSwitch Block UDP Port 53 Exfil|", + ), + ( + "KillSwitch-Block-Port53-TCP-Out", + "v2.31|Action=Block|Active=TRUE|Dir=Out|Protocol=6|RPort=53|Name=KillSwitch-Block-Port53-TCP-Out|Desc=KillSwitch Block TCP Port 53 Exfil|", + ), + ( + "KillSwitch-Block-Port853-DoT-Out", + "v2.31|Action=Block|Active=TRUE|Dir=Out|Protocol=6|RPort=853|Name=KillSwitch-Block-Port853-DoT-Out|Desc=KillSwitch Block DoT Port 853|", + ), ]; let mut applied = Vec::new(); @@ -2462,22 +2805,39 @@ pub fn apply_bfe_registry_quarantine_rules() -> Vec { applied.push(name.to_string()); } } - for ctrl_port in discover_active_control_ports() { - if ctrl_port == 3030 { - continue; + for blocked_port in QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS + .iter() + .chain(QUARANTINE_BLOCKED_LATERAL_PORTS.iter()) + { + for dir in ["In", "Out"] { + let r_name = format!("KillSwitch-Block-Port{}-{}", blocked_port, dir); + let r_val = format!( + "v2.31|Action=Block|Active=TRUE|Dir={dir}|Protocol=6|RPort={blocked_port}|Name={r_name}|Desc=KillSwitch Block Proxy or Lateral Port {blocked_port}|", + ); + if fw_key.set_value(&r_name, &r_val).is_ok() { + applied.push(r_name); + } } - let r_in_name = format!("KillSwitch-Allow-WebUI-{}-In", ctrl_port); + } + for ctrl_port in discover_firewall_bound_control_ports() { + let r_in_name = if ctrl_port == DEFAULT_CONTROL_PORT { + "KillSwitch-Allow-WebUI-In".to_string() + } else { + format!("KillSwitch-Allow-WebUI-{}-In", ctrl_port) + }; let r_in_val = format!( - "v2.31|Action=Allow|Active=TRUE|Dir=In|Protocol=6|LPort={}|RA4=127.0.0.1|RA6=::1|Name={}|Desc=KillSwitch Control API Inbound Localhost|", - ctrl_port, r_in_name + "v2.31|Action=Allow|Active=TRUE|Dir=In|Protocol=6|LPort={ctrl_port}|RA4=127.0.0.1|RA6=::1|Name={r_in_name}|Desc=KillSwitch Control API Inbound Exact Localhost|", ); if fw_key.set_value(&r_in_name, &r_in_val).is_ok() { applied.push(r_in_name); } - let r_out_name = format!("KillSwitch-Allow-WebUI-{}-Out", ctrl_port); + let r_out_name = if ctrl_port == DEFAULT_CONTROL_PORT { + "KillSwitch-Allow-WebUI-Out".to_string() + } else { + format!("KillSwitch-Allow-WebUI-{}-Out", ctrl_port) + }; let r_out_val = format!( - "v2.31|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|LPort={}|RA4=127.0.0.1|RA6=::1|Name={}|Desc=KillSwitch Control API Outbound Localhost|", - ctrl_port, r_out_name + "v2.31|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|LPort={ctrl_port}|RA4=127.0.0.1|RA6=::1|Name={r_out_name}|Desc=KillSwitch Control API Outbound Exact Localhost|", ); if fw_key.set_value(&r_out_name, &r_out_val).is_ok() { applied.push(r_out_name); @@ -2491,7 +2851,10 @@ pub fn apply_bfe_registry_quarantine_rules() -> Vec { } #[cfg(not(windows))] { - vec!["KillSwitch-Allow-Loopback-In".to_string()] + vec![ + "KillSwitch-Allow-WebUI-In".to_string(), + "KillSwitch-Allow-WebUI-Out".to_string(), + ] } } @@ -2544,81 +2907,272 @@ pub fn remove_all_killswitch_bfe_registry_rules() -> usize { } // ----------------------------------------------------------------------------- -// Direct TCP Socket Termination (`iphlpapi.dll`) +// Direct TCP / UDP Socket Inspection & Termination (`iphlpapi.dll`) // ----------------------------------------------------------------------------- -/// Terminates all active non-loopback TCP connections in states `3 | 4 | 5 | 8` -/// via `iphlpapi.dll` (`GetTcpTable` + `SetTcpEntry` with `MIB_TCP_STATE_DELETE_TCB = 12`). -/// Preserves loopback (`127.0.0.0/8`) and local control port `3030`. -pub fn terminate_all_non_loopback_tcp_sockets() -> usize { - #[cfg(windows)] - { +#[cfg(any(windows, test))] +#[inline] +fn is_exact_localhost_v4(octets: [u8; 4]) -> bool { + octets == [127, 0, 0, 1] +} + +#[cfg(any(windows, test))] +#[inline] +fn is_exact_localhost_v6(octets: [u8; 16]) -> bool { + let addr = Ipv6Addr::from(octets); + addr == Ipv6Addr::LOCALHOST || addr.to_ipv4_mapped() == Some(Ipv4Addr::LOCALHOST) +} + +#[cfg(windows)] +#[inline] +fn is_blocked_proxy_port(port: u16, preserved_ports: &[u16]) -> bool { + !preserved_ports.contains(&port) && QUARANTINE_BLOCKED_LOOPBACK_PROXY_PORTS.contains(&port) +} + +#[cfg(windows)] +struct IphlpApi { + fn_get_tcp: Option, + fn_set_tcp: Option, + fn_get_tcp6: Option, + fn_set_tcp6: Option, + fn_get_ext_tcp: Option, + fn_get_ext_udp: Option, +} + +#[cfg(windows)] +impl IphlpApi { + fn load() -> Option { use windows::core::{PCSTR, PCWSTR}; use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; let dll_name: Vec = "iphlpapi.dll\0".encode_utf16().collect(); - let Ok(h_mod) = (unsafe { LoadLibraryW(PCWSTR(dll_name.as_ptr())) }) else { - return 0; + let h_mod = unsafe { LoadLibraryW(PCWSTR(dll_name.as_ptr())) }.ok()?; + + unsafe { + let fn_get_tcp = GetProcAddress(h_mod, PCSTR(c"GetTcpTable".as_ptr().cast())) + .map(|p| std::mem::transmute((p as usize) as *const ())); + let fn_set_tcp = GetProcAddress(h_mod, PCSTR(c"SetTcpEntry".as_ptr().cast())) + .map(|p| std::mem::transmute((p as usize) as *const ())); + let fn_get_tcp6 = GetProcAddress(h_mod, PCSTR(c"GetTcp6Table".as_ptr().cast())) + .map(|p| std::mem::transmute((p as usize) as *const ())); + let fn_set_tcp6 = GetProcAddress(h_mod, PCSTR(c"SetTcp6Entry".as_ptr().cast())) + .map(|p| std::mem::transmute((p as usize) as *const ())); + let fn_get_ext_tcp = + GetProcAddress(h_mod, PCSTR(c"GetExtendedTcpTable".as_ptr().cast())) + .map(|p| std::mem::transmute((p as usize) as *const ())); + let fn_get_ext_udp = + GetProcAddress(h_mod, PCSTR(c"GetExtendedUdpTable".as_ptr().cast())) + .map(|p| std::mem::transmute((p as usize) as *const ())); + + Some(Self { + fn_get_tcp, + fn_set_tcp, + fn_get_tcp6, + fn_set_tcp6, + fn_get_ext_tcp, + fn_get_ext_udp, + }) + } + } + + unsafe fn read_table_rows(mut fetch: impl FnMut(*mut u8, *mut u32) -> u32) -> Vec { + let mut size: u32 = 0; + if fetch(std::ptr::null_mut(), &mut size) != ERROR_INSUFFICIENT_BUFFER || size < 4 { + return Vec::new(); + } + let mut buf = vec![0u8; size as usize + 1024]; + let mut actual_size = buf.len() as u32; + if fetch(buf.as_mut_ptr(), &mut actual_size) != ERROR_SUCCESS || actual_size < 4 { + return Vec::new(); + } + let num_entries = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; + let row_size = std::mem::size_of::(); + let max_entries = (buf.len().saturating_sub(4)) / row_size; + let count = num_entries.min(max_entries); + let rows_ptr = buf.as_ptr().add(4) as *const T; + (0..count).map(|i| *rows_ptr.add(i)).collect() + } + + fn tcp4_rows(&self) -> Vec { + let Some(fn_get) = self.fn_get_tcp else { + return Vec::new(); }; + unsafe { Self::read_table_rows(|ptr, sz| fn_get(ptr, sz, 0)) } + } - let Some(p_get) = (unsafe { GetProcAddress(h_mod, PCSTR(c"GetTcpTable".as_ptr().cast())) }) - else { - return 0; + fn tcp6_rows(&self) -> Vec { + let Some(fn_get) = self.fn_get_tcp6 else { + return Vec::new(); }; - let Some(p_set) = (unsafe { GetProcAddress(h_mod, PCSTR(c"SetTcpEntry".as_ptr().cast())) }) - else { - return 0; + unsafe { Self::read_table_rows(|ptr, sz| fn_get(ptr, sz, 0)) } + } + + fn tcp6_owner_pids(&self) -> Vec { + let Some(fn_get) = self.fn_get_ext_tcp else { + return Vec::new(); }; + unsafe { + Self::read_table_rows(|ptr, sz| { + fn_get(ptr, sz, 0, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) + }) + } + } - let fn_get: FnGetTcpTable = unsafe { std::mem::transmute((p_get as usize) as *const ()) }; - let fn_set: FnSetTcpEntry = unsafe { std::mem::transmute((p_set as usize) as *const ()) }; + fn udp4_owner_pids(&self) -> Vec { + let Some(fn_get) = self.fn_get_ext_udp else { + return Vec::new(); + }; + unsafe { + Self::read_table_rows(|ptr, sz| fn_get(ptr, sz, 0, AF_INET, UDP_TABLE_OWNER_PID, 0)) + } + } - let mut size: u32 = 0; - let first_status = unsafe { fn_get(std::ptr::null_mut(), &mut size, 0) }; - if first_status != ERROR_INSUFFICIENT_BUFFER || size < 4 { - return 0; + fn udp6_owner_pids(&self) -> Vec { + let Some(fn_get) = self.fn_get_ext_udp else { + return Vec::new(); + }; + unsafe { + Self::read_table_rows(|ptr, sz| fn_get(ptr, sz, 0, AF_INET6, UDP_TABLE_OWNER_PID, 0)) } + } +} - // Pad buffer to handle connection churn between calls - let mut buf = vec![0u8; size as usize + 512]; - let mut actual_size = buf.len() as u32; - let status = unsafe { fn_get(buf.as_mut_ptr(), &mut actual_size, 0) }; - if status != ERROR_SUCCESS || actual_size < 4 { +#[cfg(windows)] +fn terminate_tracked_socket_owner_pid(pid: u32) -> bool { + if pid <= 4 || pid == std::process::id() { + return false; + } + if !crate::agent_registry::TrackedAgentTreeRegistry::global().is_tracked_pid(pid) { + return false; + } + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}; + + unsafe { + let Ok(handle) = OpenProcess(PROCESS_TERMINATE, false, pid) else { + return false; + }; + let ok = TerminateProcess(handle, 1).is_ok(); + let _ = CloseHandle(handle); + ok + } +} + +/// Terminates all active non-localhost TCP connections (`3 | 4 | 5 | 8`), `127.0.0.2+` +/// loopback aliases, local proxy-port tunnels (`1080/3128/8080/8888/9050`), IPv6 connections +/// (via `SetTcp6Entry` when exported + tracked agent owner PID teardown), and non-localhost +/// UDP sockets owned by tracked agent PIDs via `iphlpapi.dll`. +/// Preserves exact localhost (`127.0.0.1` / `::1`) non-proxy and sanitized control-port sockets. +pub fn terminate_all_non_loopback_tcp_sockets() -> usize { + #[cfg(windows)] + { + let Some(api) = IphlpApi::load() else { return 0; + }; + let preserved_ports = sanitize_firewall_preserved_ports(&[]); + let mut terminated = 0usize; + + if let Some(fn_set) = api.fn_set_tcp { + for row in api.tcp4_rows() { + if !matches!(row.dw_state, 3 | 4 | 5 | 8) { + continue; + } + let local_octets = row.dw_local_addr.to_ne_bytes(); + let remote_octets = row.dw_remote_addr.to_ne_bytes(); + let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); + let remote_port = u16::from_be((row.dw_remote_port & 0xFFFF) as u16); + + let both_exact_localhost = + is_exact_localhost_v4(local_octets) && is_exact_localhost_v4(remote_octets); + let is_control_port = + preserved_ports.contains(&local_port) || preserved_ports.contains(&remote_port); + let hits_proxy_port = is_blocked_proxy_port(local_port, &preserved_ports) + || is_blocked_proxy_port(remote_port, &preserved_ports); + + let should_terminate = + !both_exact_localhost || (!is_control_port && hits_proxy_port); + if should_terminate { + let mut reset_row = row; + reset_row.dw_state = MIB_TCP_STATE_DELETE_TCB; + if unsafe { fn_set(&reset_row) } == ERROR_SUCCESS { + terminated += 1; + } + } + } } - let num_entries = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; - let row_size = std::mem::size_of::(); - let max_entries = (buf.len().saturating_sub(4)) / row_size; - let count = num_entries.min(max_entries); - let rows_ptr = unsafe { buf.as_ptr().add(4) as *const MibTcpRow }; + if let Some(fn_set6) = api.fn_set_tcp6 { + for row in api.tcp6_rows() { + if !matches!(row.state, 3 | 4 | 5 | 8) { + continue; + } + let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); + let remote_port = u16::from_be((row.dw_remote_port & 0xFFFF) as u16); + let both_exact_localhost = is_exact_localhost_v6(row.uc_local_addr) + && is_exact_localhost_v6(row.uc_remote_addr); + let is_control_port = + preserved_ports.contains(&local_port) || preserved_ports.contains(&remote_port); + let hits_proxy_port = is_blocked_proxy_port(local_port, &preserved_ports) + || is_blocked_proxy_port(remote_port, &preserved_ports); + + if !both_exact_localhost || (!is_control_port && hits_proxy_port) { + let mut reset_row = row; + reset_row.state = MIB_TCP_STATE_DELETE_TCB; + if unsafe { fn_set6(&reset_row) } == ERROR_SUCCESS { + terminated += 1; + } + } + } + } - let active_ctrl_ports = discover_active_control_ports(); - let mut terminated = 0usize; - for i in 0..count { - let row = unsafe { *rows_ptr.add(i) }; - let local_octets = row.dw_local_addr.to_ne_bytes(); - let remote_octets = row.dw_remote_addr.to_ne_bytes(); + // Sever tracked agent PIDs holding non-localhost IPv6 TCP or UDP sockets that lack Set*Entry deletion. + let mut killed_pids = std::collections::HashSet::new(); + for row in api.tcp6_owner_pids() { + if !matches!(row.dw_state, 3 | 4 | 5 | 8) || killed_pids.contains(&row.dw_owning_pid) { + continue; + } + let both_exact_localhost = is_exact_localhost_v6(row.uc_local_addr) + && is_exact_localhost_v6(row.uc_remote_addr); let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); let remote_port = u16::from_be((row.dw_remote_port & 0xFFFF) as u16); - - // Invariant 1: Preserve loopback traffic (127.0.0.0/8) - let is_loopback = local_octets[0] == 127 || remote_octets[0] == 127; - // Invariant 2: Preserve all active control/WebUI ports (3030, 4040, active_port.txt) - let is_control_port = - active_ctrl_ports.contains(&local_port) || active_ctrl_ports.contains(&remote_port); - // Invariant 3: Target half-open and established states - let is_target_state = matches!(row.dw_state, 3 | 4 | 5 | 8); - - if is_target_state && !is_loopback && !is_control_port { - let mut reset_row = row; - reset_row.dw_state = MIB_TCP_STATE_DELETE_TCB; - if unsafe { fn_set(&reset_row) } == ERROR_SUCCESS { - terminated += 1; - } + let hits_proxy = is_blocked_proxy_port(local_port, &preserved_ports) + || is_blocked_proxy_port(remote_port, &preserved_ports); + if (!both_exact_localhost || hits_proxy) + && terminate_tracked_socket_owner_pid(row.dw_owning_pid) + { + killed_pids.insert(row.dw_owning_pid); + terminated += 1; + } + } + for row in api.udp4_owner_pids() { + if killed_pids.contains(&row.dw_owning_pid) { + continue; + } + let local_octets = row.dw_local_addr.to_ne_bytes(); + let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); + if (!is_exact_localhost_v4(local_octets) + || QUARANTINE_BLOCKED_DISCOVERY_PORTS.contains(&local_port)) + && terminate_tracked_socket_owner_pid(row.dw_owning_pid) + { + killed_pids.insert(row.dw_owning_pid); + terminated += 1; + } + } + for row in api.udp6_owner_pids() { + if killed_pids.contains(&row.dw_owning_pid) { + continue; + } + let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); + if (!is_exact_localhost_v6(row.uc_local_addr) + || QUARANTINE_BLOCKED_DISCOVERY_PORTS.contains(&local_port)) + && terminate_tracked_socket_owner_pid(row.dw_owning_pid) + { + killed_pids.insert(row.dw_owning_pid); + terminated += 1; } } + info!( - "⚡ [TCP-RESET] Terminated {} active non-loopback TCP connections", + "⚡ [TCP-RESET] Terminated {} active non-localhost TCP/UDP agent connections", terminated ); terminated @@ -2629,61 +3183,36 @@ pub fn terminate_all_non_loopback_tcp_sockets() -> usize { } } -/// Inspects the OS TCP connection table (`GetTcpTable` on Windows, `/proc/net/tcp` on Linux) -/// and returns `(active_non_loopback_peer_connections_count, remote_peer_endpoints_sample)`. +/// Inspects OS IPv4 + IPv6 TCP connection tables (`GetTcpTable`/`GetTcp6Table` on Windows, +/// `/proc/net/tcp` + `/proc/net/tcp6` on Linux) and returns +/// `(active_non_loopback_peer_connections_count, remote_peer_endpoints_sample)`. pub fn count_active_non_loopback_tcp_peers() -> (usize, Vec) { #[cfg(windows)] { - use windows::core::{PCSTR, PCWSTR}; - use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; - - let dll_name: Vec = "iphlpapi.dll\0".encode_utf16().collect(); - let Ok(h_mod) = (unsafe { LoadLibraryW(PCWSTR(dll_name.as_ptr())) }) else { + let Some(api) = IphlpApi::load() else { return (0, Vec::new()); }; - let Some(p_get) = (unsafe { GetProcAddress(h_mod, PCSTR(c"GetTcpTable".as_ptr().cast())) }) - else { - return (0, Vec::new()); - }; - let fn_get: FnGetTcpTable = unsafe { std::mem::transmute((p_get as usize) as *const ()) }; - - let mut size: u32 = 0; - let first_status = unsafe { fn_get(std::ptr::null_mut(), &mut size, 0) }; - if first_status != ERROR_INSUFFICIENT_BUFFER || size < 4 { - return (0, Vec::new()); - } - - let mut buf = vec![0u8; size as usize + 512]; - let mut actual_size = buf.len() as u32; - let status = unsafe { fn_get(buf.as_mut_ptr(), &mut actual_size, 0) }; - if status != ERROR_SUCCESS || actual_size < 4 { - return (0, Vec::new()); - } - - let num_entries = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; - let row_size = std::mem::size_of::(); - let max_entries = (buf.len().saturating_sub(4)) / row_size; - let count = num_entries.min(max_entries); - let rows_ptr = unsafe { buf.as_ptr().add(4) as *const MibTcpRow }; - - let active_ctrl_ports = discover_active_control_ports(); + let preserved_ports = sanitize_firewall_preserved_ports(&[]); let mut active_count = 0usize; let mut peers = Vec::new(); - for i in 0..count { - let row = unsafe { *rows_ptr.add(i) }; + for row in api.tcp4_rows() { + if !matches!(row.dw_state, 3 | 4 | 5 | 8) { + continue; + } let local_octets = row.dw_local_addr.to_ne_bytes(); let remote_octets = row.dw_remote_addr.to_ne_bytes(); let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); let remote_port = u16::from_be((row.dw_remote_port & 0xFFFF) as u16); - let is_loopback = - local_octets[0] == 127 || remote_octets[0] == 127 || remote_octets == [0, 0, 0, 0]; - let is_control_port = - active_ctrl_ports.contains(&local_port) || active_ctrl_ports.contains(&remote_port); - let is_active_state = matches!(row.dw_state, 3 | 4 | 5 | 8); + let is_localhost_or_unspecified = (is_exact_localhost_v4(local_octets) + && is_exact_localhost_v4(remote_octets)) + || remote_octets == [0, 0, 0, 0]; + let is_control_port = (preserved_ports.contains(&local_port) + || preserved_ports.contains(&remote_port)) + && is_exact_localhost_v4(remote_octets); - if is_active_state && !is_loopback && !is_control_port { + if !is_localhost_or_unspecified && !is_control_port { active_count += 1; if peers.len() < 20 { let ep = format!( @@ -2700,21 +3229,58 @@ pub fn count_active_non_loopback_tcp_peers() -> (usize, Vec) { } } } + + for row in api.tcp6_rows() { + if !matches!(row.state, 3 | 4 | 5 | 8) { + continue; + } + let remote_ip = Ipv6Addr::from(row.uc_remote_addr); + let local_port = u16::from_be((row.dw_local_port & 0xFFFF) as u16); + let remote_port = u16::from_be((row.dw_remote_port & 0xFFFF) as u16); + let is_localhost_or_unspecified = (is_exact_localhost_v6(row.uc_local_addr) + && is_exact_localhost_v6(row.uc_remote_addr)) + || remote_ip.is_unspecified(); + let is_control_port = (preserved_ports.contains(&local_port) + || preserved_ports.contains(&remote_port)) + && is_exact_localhost_v6(row.uc_remote_addr); + + if !is_localhost_or_unspecified && !is_control_port { + active_count += 1; + if peers.len() < 20 { + let ep = format!("[{}]:{}", remote_ip, remote_port); + if !peers.contains(&ep) { + peers.push(ep); + } + } + } + } (active_count, peers) } #[cfg(target_os = "linux")] { let mut active_count = 0usize; let mut peers = Vec::new(); - if let Ok(raw) = std::fs::read_to_string("/proc/net/tcp") { - for line in raw.lines().skip(1) { - let parts: Vec<&str> = line.split_whitespace().collect(); - if parts.len() >= 4 && parts[3] == "01" { - let rem = parts[2]; - if !rem.starts_with("0100007F:") && !rem.starts_with("00000000:") { - active_count += 1; - if peers.len() < 20 { - peers.push(rem.to_string()); + for (path, loopback_prefixes) in [ + ("/proc/net/tcp", &["0100007F:", "00000000:"][..]), + ( + "/proc/net/tcp6", + &[ + "00000000000000000000000001000000:", + "00000000000000000000000000000000:", + "0000000000000000FFFF00000100007F:", + ][..], + ), + ] { + if let Ok(raw) = std::fs::read_to_string(path) { + for line in raw.lines().skip(1) { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 4 && parts[3] == "01" { + let rem = parts[2]; + if !loopback_prefixes.iter().any(|pfx| rem.starts_with(pfx)) { + active_count += 1; + if peers.len() < 20 { + peers.push(rem.to_string()); + } } } } @@ -2728,13 +3294,11 @@ pub fn count_active_non_loopback_tcp_peers() -> (usize, Vec) { } } -/// Terminates active TCP connections destined for specific remote IP addresses. +/// Terminates active IPv4 & IPv6 TCP connections destined for specific remote IP addresses. pub fn terminate_active_tcp_sockets_for_ips(ips: &[IpAddr]) -> usize { #[cfg(windows)] { use std::collections::HashSet; - use windows::core::{PCSTR, PCWSTR}; - use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; let target_v4_addrs: HashSet = ips .iter() @@ -2743,58 +3307,63 @@ pub fn terminate_active_tcp_sockets_for_ips(ips: &[IpAddr]) -> usize { IpAddr::V6(_) => None, }) .collect(); - if target_v4_addrs.is_empty() { + let target_v6_addrs: HashSet<[u8; 16]> = ips + .iter() + .map(|ip| match ip { + IpAddr::V6(v6) => v6.octets(), + IpAddr::V4(v4) => v4.to_ipv6_mapped().octets(), + }) + .collect(); + if target_v4_addrs.is_empty() && target_v6_addrs.is_empty() { return 0; } - let dll_name: Vec = "iphlpapi.dll\0".encode_utf16().collect(); - let Ok(h_mod) = (unsafe { LoadLibraryW(PCWSTR(dll_name.as_ptr())) }) else { + let Some(api) = IphlpApi::load() else { return 0; }; + let mut terminated = 0usize; - let Some(p_get) = (unsafe { GetProcAddress(h_mod, PCSTR(c"GetTcpTable".as_ptr().cast())) }) - else { - return 0; - }; - let Some(p_set) = (unsafe { GetProcAddress(h_mod, PCSTR(c"SetTcpEntry".as_ptr().cast())) }) - else { - return 0; - }; - - let fn_get: FnGetTcpTable = unsafe { std::mem::transmute((p_get as usize) as *const ()) }; - let fn_set: FnSetTcpEntry = unsafe { std::mem::transmute((p_set as usize) as *const ()) }; - - let mut size: u32 = 0; - let first_status = unsafe { fn_get(std::ptr::null_mut(), &mut size, 0) }; - if first_status != ERROR_INSUFFICIENT_BUFFER || size < 4 { - return 0; - } - - let mut buf = vec![0u8; size as usize + 256]; - let mut actual_size = buf.len() as u32; - let status = unsafe { fn_get(buf.as_mut_ptr(), &mut actual_size, 0) }; - if status != ERROR_SUCCESS || actual_size < 4 { - return 0; + if !target_v4_addrs.is_empty() { + if let Some(fn_set) = api.fn_set_tcp { + for mut row in api.tcp4_rows() { + if matches!(row.dw_state, 3 | 4 | 5 | 8) + && target_v4_addrs.contains(&row.dw_remote_addr) + { + row.dw_state = MIB_TCP_STATE_DELETE_TCB; + if unsafe { fn_set(&row) } == ERROR_SUCCESS { + terminated += 1; + } + } + } + } } - let num_entries = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; - let row_size = std::mem::size_of::(); - let max_entries = (buf.len().saturating_sub(4)) / row_size; - let count = num_entries.min(max_entries); - let rows_ptr = unsafe { buf.as_ptr().add(4) as *const MibTcpRow }; - - let mut terminated = 0usize; - for i in 0..count { - let mut row = unsafe { *rows_ptr.add(i) }; - if matches!(row.dw_state, 3 | 4 | 5 | 8) - && target_v4_addrs.contains(&row.dw_remote_addr) - { - row.dw_state = MIB_TCP_STATE_DELETE_TCB; - if unsafe { fn_set(&row) } == ERROR_SUCCESS { + if !target_v6_addrs.is_empty() { + if let Some(fn_set6) = api.fn_set_tcp6 { + for mut row in api.tcp6_rows() { + if matches!(row.state, 3 | 4 | 5 | 8) + && target_v6_addrs.contains(&row.uc_remote_addr) + { + row.state = MIB_TCP_STATE_DELETE_TCB; + if unsafe { fn_set6(&row) } == ERROR_SUCCESS { + terminated += 1; + } + } + } + } + let mut killed_pids = HashSet::new(); + for row in api.tcp6_owner_pids() { + if matches!(row.dw_state, 3 | 4 | 5 | 8) + && target_v6_addrs.contains(&row.uc_remote_addr) + && !killed_pids.contains(&row.dw_owning_pid) + && terminate_tracked_socket_owner_pid(row.dw_owning_pid) + { + killed_pids.insert(row.dw_owning_pid); terminated += 1; } } } + terminated } #[cfg(not(windows))] @@ -2980,11 +3549,7 @@ pub fn engage_windows_network_quarantine_with_ports( "Elevated helper did not record any installed WFP filter IDs".to_string(), )); } - let preserved_ports = if !custom_ports.is_empty() { - custom_ports.to_vec() - } else { - discover_active_control_ports() - }; + let preserved_ports = sanitize_firewall_preserved_ports(custom_ports); let preserved_ips = vec![ IpAddr::V4(Ipv4Addr::LOCALHOST), IpAddr::V6(Ipv6Addr::LOCALHOST), @@ -3047,8 +3612,9 @@ pub fn engage_windows_network_quarantine_with_ports( clear_persisted_wfp_filter_ids(); } + let preserved_ports = sanitize_firewall_preserved_ports(custom_ports); let ids = session - .install_hermetic_quarantine_filters("KillSwitch") + .install_hermetic_quarantine_filters_with_ports("KillSwitch", &preserved_ports) .inspect_err(|_e| { let _ = session.abort_transaction(); })?; @@ -3071,11 +3637,7 @@ pub fn engage_windows_network_quarantine_with_ports( let registry_rules = apply_bfe_registry_quarantine_rules(); let terminated_tcp = terminate_all_non_loopback_tcp_sockets(); - let preserved_ports = if !custom_ports.is_empty() { - custom_ports.to_vec() - } else { - discover_active_control_ports() - }; + let preserved_ports = sanitize_firewall_preserved_ports(custom_ports); let preserved_ips = vec![ IpAddr::V4(Ipv4Addr::LOCALHOST), IpAddr::V6(Ipv6Addr::LOCALHOST), @@ -3189,12 +3751,8 @@ impl NetworkIsolator for WindowsWfpIsolator { operator: &str, reason: &str, ) -> Result { - if std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok() { - let preserved = if !preserved_ports.is_empty() { - preserved_ports.to_vec() - } else { - discover_active_control_ports() - }; + if is_authorized_self_diagnostic() { + let preserved = sanitize_firewall_preserved_ports(preserved_ports); let preserved_ips = vec![ IpAddr::V4(Ipv4Addr::LOCALHOST), IpAddr::V6(Ipv6Addr::LOCALHOST), @@ -3212,53 +3770,23 @@ impl NetworkIsolator for WindowsWfpIsolator { reason.to_string(), )); } - match engage_windows_network_quarantine_with_ports(operator, reason, preserved_ports) { - Ok(receipt) => Ok(receipt), - Err(KillSwitchError::InsufficientPrivileges { .. }) => { - warn!("⚠️ [WFP-USERMODE] Non-elevated session detected; executing user-space TCP socket termination and returning contract receipt."); - let terminated = terminate_all_non_loopback_tcp_sockets(); - let preserved = if !preserved_ports.is_empty() { - preserved_ports.to_vec() - } else { - discover_active_control_ports() - }; - let preserved_ips = vec![ - IpAddr::V4(Ipv4Addr::LOCALHOST), - IpAddr::V6(Ipv6Addr::LOCALHOST), - ]; - Ok(IsolationReceipt::new( - "usermode-session-contract".to_string(), - NetworkIsolationEngine::WindowsWfpDynamic, - vec![1001, 1002, 1003], - Vec::new(), - Vec::new(), - preserved, - preserved_ips, - terminated, - operator.to_string(), - reason.to_string(), - )) - } - Err(e) => Err(e), - } + // Fail closed unconditionally on InsufficientPrivileges or any WFP engine error; + // never fabricate a spoofed "usermode-session-contract" receipt. + engage_windows_network_quarantine_with_ports(operator, reason, preserved_ports) } fn restore_quarantine(&self, _receipt: &IsolationReceipt) -> Result<(), KillSwitchError> { - if std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok() { + if is_authorized_self_diagnostic() { return Ok(()); } - match disarm_windows_network_quarantine("disarm", "reverting quarantine") { - Ok(()) => Ok(()), - Err(KillSwitchError::InsufficientPrivileges { .. }) => Ok(()), - Err(e) => Err(e), - } + disarm_windows_network_quarantine("disarm", "reverting quarantine") } fn reset_tcp_connections( &self, target_ips: Option<&[IpAddr]>, ) -> Result { - if std::env::var("KILLSWITCH_SELF_DIAGNOSTIC").is_ok() { + if is_authorized_self_diagnostic() { return Ok(0); } if let Some(ips) = target_ips { @@ -3523,4 +4051,59 @@ mod tests { let err_zero = KillSwitchError::ZeroFiltersInstalled("0 filters".to_string()); assert!(err_zero.to_string().contains("0 filters")); } + + #[test] + fn test_ws4_quarantine_port_sanitization_and_structs() { + assert!(is_blocked_quarantine_port(0)); + assert!(is_blocked_quarantine_port(53)); + assert!(is_blocked_quarantine_port(135)); + assert!(is_blocked_quarantine_port(445)); + assert!(is_blocked_quarantine_port(853)); + assert!(is_blocked_quarantine_port(1080)); + assert!(is_blocked_quarantine_port(3128)); + assert!(is_blocked_quarantine_port(5985)); + assert!(is_blocked_quarantine_port(8080)); + assert!(is_blocked_quarantine_port(8888)); + assert!(is_blocked_quarantine_port(9050)); + assert!(!is_blocked_quarantine_port(DEFAULT_CONTROL_PORT)); + + let sanitized = sanitize_firewall_preserved_ports(&[53, 445, 1080, 8080, 9050, 3456]); + assert_eq!(sanitized, vec![3456]); + + let fallback = sanitize_firewall_preserved_ports(&[53, 8080]); + assert!(!fallback.is_empty()); + assert!(fallback.iter().all(|p| !is_blocked_quarantine_port(*p))); + + let bound_ports = discover_firewall_bound_control_ports(); + assert!(!bound_ports.is_empty()); + assert!(!bound_ports.contains(&3031)); + assert!(!bound_ports.contains(&4040)); + + assert!(is_exact_localhost_v4([127, 0, 0, 1])); + assert!(!is_exact_localhost_v4([127, 0, 0, 2])); + assert!(is_exact_localhost_v6(Ipv6Addr::LOCALHOST.octets())); + assert!(!is_exact_localhost_v6( + Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1).octets() + )); + + assert_eq!( + std::mem::size_of::(), + std::mem::size_of::() * 2 + ); + assert_eq!(std::mem::size_of::(), 52); + assert_eq!(std::mem::size_of::(), 56); + } + + #[test] + fn test_ws4_wfp_isolator_fails_closed_when_unelevated() { + #[cfg(windows)] + if !is_current_process_elevated() && !is_authorized_self_diagnostic() { + let isolator = WindowsWfpIsolator; + let res = isolator.engage_quarantine(&[DEFAULT_CONTROL_PORT], "test", "fail-closed"); + assert!( + matches!(res, Err(KillSwitchError::InsufficientPrivileges { .. })), + "Expected fail-closed InsufficientPrivileges, got: {res:?}" + ); + } + } } diff --git a/crates/killswitch-core/tests/containment_integration_tests.rs b/crates/killswitch-core/tests/containment_integration_tests.rs index be6ccaa..800050f 100644 --- a/crates/killswitch-core/tests/containment_integration_tests.rs +++ b/crates/killswitch-core/tests/containment_integration_tests.rs @@ -186,16 +186,18 @@ fn test_parse_proc_net_tcp_table() { fn test_linux_netlink_isolator_lifecycle() { let isolator = LinuxNetlinkIsolator::new(); let preserved = vec![3030, 53, 67, 68]; - let receipt = isolator - .engage_quarantine( - &preserved, - "secops_linux", - "Ransomware outbreak containment", - ) - .expect("Engage quarantine receipt"); + let receipt = match isolator.engage_quarantine( + &preserved, + "secops_linux", + "Ransomware outbreak containment", + ) { + Ok(r) => r, + Err(KillSwitchError::InsufficientPrivileges { .. }) => return, + Err(e) => panic!("Engage quarantine receipt unexpected error: {e:?}"), + }; assert_eq!(receipt.engine, NetworkIsolationEngine::LinuxNetlink); - assert_eq!(receipt.preserved_ports, preserved); + assert_eq!(receipt.preserved_ports, vec![3030]); assert_eq!(receipt.engaged_by, "secops_linux"); let restore_res = isolator.restore_quarantine(&receipt); diff --git a/crates/killswitch-core/tests/empirical_challenge_m1_2.rs b/crates/killswitch-core/tests/empirical_challenge_m1_2.rs index bf70dd0..43a2e0f 100644 --- a/crates/killswitch-core/tests/empirical_challenge_m1_2.rs +++ b/crates/killswitch-core/tests/empirical_challenge_m1_2.rs @@ -16,8 +16,8 @@ use killswitch_core::{ state_ledger::StateLedger, wfp::{ apply_bfe_registry_quarantine_rules, discover_active_control_ports, - engage_windows_network_quarantine_with_ports, is_current_process_elevated, - is_elevated_administrator, WindowsWfpIsolator, + engage_windows_network_quarantine_with_ports, is_authorized_self_diagnostic, + is_current_process_elevated, is_elevated_administrator, WindowsWfpIsolator, }, }; use killswitch_types::{ @@ -186,14 +186,23 @@ fn test_challenge_task1_bfe_registry_rules_have_zero_dns_dhcp_permits() { for rule_name in &rules { let lower = rule_name.to_lowercase(); + let is_allow = rule_name.starts_with("KillSwitch-Allow-"); assert!( - !lower.contains("dns"), - "Rule '{}' contains 'dns' — DNS must not be permitted in quarantine!", + !(is_allow && (lower.contains("dns") || lower.contains("port53"))), + "Allow rule '{}' must not permit DNS in quarantine!", rule_name ); assert!( - !lower.contains("dhcp"), - "Rule '{}' contains 'dhcp' — DHCP must not be permitted in quarantine!", + !(is_allow + && (lower.contains("dhcp") + || lower.contains("port67") + || lower.contains("port68"))), + "Allow rule '{}' must not permit DHCP in quarantine!", + rule_name + ); + assert!( + !rule_name.contains("Allow-Loopback"), + "Blanket loopback permit rule '{}' is forbidden!", rule_name ); } @@ -217,23 +226,31 @@ fn test_challenge_task2_only_local_loopback_preserved_on_control_port() { assert!( !allow_rules.is_empty(), - "Must have at least one allow rule for loopback/WebUI when elevated" + "Must have at least one port-scoped WebUI allow rule when elevated" ); for r in &allow_rules { assert!( - r.contains("Loopback") || r.contains("WebUI"), - "Allow rule '{}' is not loopback or WebUI restricted!", + r.contains("WebUI") && !r.contains("Allow-Loopback"), + "Allow rule '{}' must be strictly port-scoped to WebUI without blanket Allow-Loopback!", r ); } - // Verify block rules cover inbound and outbound non-loopback + // Verify block rules cover inbound/outbound non-loopback, 127.0.0.2+ subrange, and IMDS let block_rules: Vec<_> = rules .iter() .filter(|r| r.starts_with("KillSwitch-Block-")) .collect(); + assert!( + block_rules.iter().any(|r| r.contains("Loopback-Subrange")), + "Missing Loopback-Subrange block rule" + ); + assert!( + block_rules.iter().any(|r| r.contains("IMDS")), + "Missing IMDS block rule" + ); assert!( block_rules.iter().any(|r| r.contains("Inbound-Low")), "Missing Inbound-Low block rule" @@ -267,20 +284,30 @@ fn test_challenge_task2_only_local_loopback_preserved_on_control_port() { rules ); } else { - // On non-Windows platforms without HKLM, verify loopback restriction + // On non-Windows platforms without HKLM, verify strictly WebUI port-scoped rule names assert!( rules .iter() - .all(|r| r.contains("Loopback") || r.contains("WebUI")), - "Non-Windows quarantine rules must be loopback-restricted" + .all(|r| r.contains("WebUI") && !r.contains("Allow-Loopback")), + "Non-Windows quarantine rules must be strictly WebUI-restricted" ); } - // Empirically verify that IsolationReceipt strictly preserves ONLY loopback IPs + // Empirically verify that IsolationReceipt strictly preserves ONLY loopback IPs (or fails closed) let isolator = WindowsWfpIsolator; - let receipt = isolator - .engage_quarantine(&[DEFAULT_CONTROL_PORT], "challenger", "task2 loopback test") - .expect("Isolation receipt generation must succeed"); + let receipt = match isolator.engage_quarantine( + &[DEFAULT_CONTROL_PORT], + "challenger", + "task2 loopback test", + ) { + Ok(r) => r, + Err(KillSwitchError::InsufficientPrivileges { .. }) + if cfg!(windows) && !is_current_process_elevated() => + { + return; + } + Err(e) => panic!("Unexpected WindowsWfpIsolator error: {:?}", e), + }; assert_eq!( receipt.preserved_ports, @@ -459,15 +486,22 @@ fn test_challenge_task3_windows_wfp_isolator_trait_contract() { let isolator = WindowsWfpIsolator; let ports = vec![DEFAULT_CONTROL_PORT]; - // In a cargo test runner environment, the WindowsWfpIsolator trait implementation - // handles un-elevated runners gracefully for state machine integration testing, - // but ensures 3 valid contract receipt filter IDs are populated rather than 0. let receipt_res = isolator.engage_quarantine(&ports, "tester", "trait verification"); - assert!( - receipt_res.is_ok(), - "WindowsWfpIsolator::engage_quarantine must succeed in test runner" + if cfg!(windows) && !is_current_process_elevated() && !is_authorized_self_diagnostic() { + assert!( + matches!( + receipt_res, + Err(KillSwitchError::InsufficientPrivileges { .. }) + ), + "Un-elevated WindowsWfpIsolator outside self-diagnostic must fail closed, got: {:?}", + receipt_res + ); + return; + } + + let receipt = receipt_res.expect( + "WindowsWfpIsolator::engage_quarantine must succeed when elevated, non-Windows, or under authorized self-diagnostic", ); - let receipt = receipt_res.unwrap(); assert!( !receipt.wfp_filter_ids.is_empty(), "Receipt wfp_filter_ids must NEVER be empty (0 filters is forbidden)!" diff --git a/crates/killswitch-core/tests/empirical_challenge_m2_2.rs b/crates/killswitch-core/tests/empirical_challenge_m2_2.rs index ace980b..3c2e25f 100644 --- a/crates/killswitch-core/tests/empirical_challenge_m2_2.rs +++ b/crates/killswitch-core/tests/empirical_challenge_m2_2.rs @@ -197,7 +197,7 @@ fn test_quarantine_receipt_preserved_ports_and_ips_integrity() { }; assert_eq!(receipt_macos.engine, NetworkIsolationEngine::DarwinPf); - assert_eq!(receipt_macos.preserved_ports, preserved_ports); + assert_eq!(receipt_macos.preserved_ports, vec![DEFAULT_CONTROL_PORT]); assert!(receipt_macos .preserved_ips .contains(&IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)))); @@ -205,21 +205,27 @@ fn test_quarantine_receipt_preserved_ports_and_ips_integrity() { .preserved_ips .contains(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)))); - // 2. Windows WFP Isolator receipt contract + // 2. Windows WFP Isolator receipt contract (fails closed when un-elevated outside diagnostic CI; + // rejects privileged/DNS/DHCP ports via sanitize_firewall_preserved_ports) let wfp_isolator = WindowsWfpIsolator; - let receipt_wfp = wfp_isolator - .engage_quarantine( - &preserved_ports, - "admin", - "Windows WFP Receipt Verification", - ) - .unwrap(); + let receipt_wfp = match wfp_isolator.engage_quarantine( + &preserved_ports, + "admin", + "Windows WFP Receipt Verification", + ) { + Ok(r) => r, + Err(KillSwitchError::InsufficientPrivileges { .. }) => return, + Err(e) => panic!( + "Windows WFP Quarantine engagement failed unexpectedly: {:?}", + e + ), + }; assert_eq!( receipt_wfp.engine, NetworkIsolationEngine::WindowsWfpDynamic ); - assert_eq!(receipt_wfp.preserved_ports, preserved_ports); + assert_eq!(receipt_wfp.preserved_ports, vec![DEFAULT_CONTROL_PORT]); assert!(receipt_wfp .preserved_ips .contains(&IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)))); @@ -242,44 +248,51 @@ fn test_darwin_pf_quarantine_rules_structure_and_order() { let preserved_ports = vec![DEFAULT_CONTROL_PORT, 53, 67, 68]; let (rules, syntax) = generate_quarantine_rules("test_killswitch_anchor", &preserved_ports); - assert!(rules.len() >= 7, "Expected at least 7 generated PF rules"); + assert!( + rules.len() >= 20, + "Expected hardened IMDS/discovery/proxy/lateral + localhost control PF rules" + ); - // Invariant: First rule must be quick pass on lo0 - assert_eq!(rules[0].action, PfAction::Pass); - assert_eq!(rules[0].direction, PfDirection::InOut); + // Invariant: IMDS & discovery drops precede any localhost control pass; zero blanket lo0 pass + assert_eq!(rules[0].action, PfAction::Drop); assert!(rules[0].quick); - assert_eq!(rules[0].interface.as_deref(), Some("lo0")); - - // Invariant: Rules 1 & 2 must be explicit 127.0.0.1 and ::1 quick passes - assert_eq!(rules[1].src, "127.0.0.1"); - assert!(rules[1].quick); - assert_eq!(rules[2].src, "::1"); - assert!(rules[2].quick); + assert_eq!(rules[0].dst, "169.254.0.0/16"); + assert!(!syntax.contains("pass quick on lo0 all")); + assert!(!syntax.contains("from 127.0.0.1 to any")); + assert!(!syntax.contains("from ::1 to any")); - // Invariant: Port 3030 must be preserved for inbound and outbound TCP + // Invariant: Port 3030 must be preserved strictly between 127.0.0.1<->127.0.0.1 and ::1<->::1 on lo0 let port_3030_rules: Vec<_> = rules .iter() .filter(|r| r.src_port == Some(3030) || r.dst_port == Some(3030)) .collect(); assert_eq!( port_3030_rules.len(), - 2, - "Must have in and out rules for 3030" + 8, + "Must have in/out src/dst rules for 3030 on 127.0.0.1 and ::1" ); for r in &port_3030_rules { assert_eq!(r.action, PfAction::Pass); assert_eq!(r.protocol, PfProtocol::Tcp); assert!(r.quick); + assert_eq!(r.interface.as_deref(), Some("lo0")); + assert!(r.src == "127.0.0.1" || r.src == "::1"); + assert_eq!(r.src, r.dst); } - // Invariant: DNS 53 (UDP & TCP) and DHCP 67/68 must strictly NOT be preserved - assert!(!rules.iter().any(|r| r.dst_port == Some(53))); + // Invariant: DNS 53 and DHCP 67/68 must be explicitly dropped and never passed + assert!(rules + .iter() + .any(|r| r.action == PfAction::Drop && r.dst_port == Some(53))); + assert!(!rules + .iter() + .any(|r| r.action == PfAction::Pass && r.dst_port == Some(53))); assert!(!rules .iter() - .any(|r| r.dst_port == Some(67) || r.src_port == Some(67))); + .any(|r| r.action == PfAction::Pass && (r.dst_port == Some(67) || r.src_port == Some(67)))); assert!(!rules .iter() - .any(|r| r.dst_port == Some(68) || r.src_port == Some(68))); + .any(|r| r.action == PfAction::Pass && (r.dst_port == Some(68) || r.src_port == Some(68)))); // Invariant: Last two rules must be hermetic block drop in & out all with quick: true let last_rule_in = &rules[rules.len() - 2]; diff --git a/crates/killswitch-core/tests/macos_pf_and_service_tests.rs b/crates/killswitch-core/tests/macos_pf_and_service_tests.rs index b2c9b5f..673e27a 100644 --- a/crates/killswitch-core/tests/macos_pf_and_service_tests.rs +++ b/crates/killswitch-core/tests/macos_pf_and_service_tests.rs @@ -31,39 +31,41 @@ fn test_f29_macos_pf_anchor_quarantine_rules_generation() { "Syntax must reference anchor 'killswitch'" ); - // Invariant: lo0, 127.0.0.1, ::1 preserved with quick + // Invariant: Zero blanket lo0 / from 127.0.0.1 to any / from ::1 to any bypasses assert!( - syntax.contains("pass quick on lo0 all"), - "Rule syntax must preserve lo0 interface" + !syntax.contains("pass quick on lo0 all"), + "Rule syntax must NOT contain blanket lo0 pass" ); assert!( - syntax.contains("pass quick from 127.0.0.1 to any"), - "Rule syntax must explicitly pass 127.0.0.1" + !syntax.contains("from 127.0.0.1 to any"), + "Rule syntax must NOT contain blanket 127.0.0.1 to any pass" ); assert!( - syntax.contains("pass quick from ::1 to any"), - "Rule syntax must explicitly pass ::1" + !syntax.contains("from ::1 to any"), + "Rule syntax must NOT contain blanket ::1 to any pass" ); - // Invariant: local control port 3030 preserved + // Invariant: IMDS and local control port 3030 exact-localhost preservation + assert!(syntax.contains("169.254.0.0/16")); + assert!(syntax.contains("fe80::/10")); assert!( - syntax.contains("port 3030"), - "Rule syntax must preserve port 3030" + syntax.contains("pass in quick on lo0 proto tcp from 127.0.0.1 to 127.0.0.1 port 3030"), + "Rule syntax must strictly preserve port 3030 between 127.0.0.1 <-> 127.0.0.1" ); - // Invariant: DNS 53 and DHCP 67/68 must strictly NOT be preserved + // Invariant: DNS 53 and DHCP 67/68 must have explicit block drops and zero pass rules assert!( - !syntax.contains("port 53"), - "Rule syntax must not preserve DNS 53" - ); - assert!( - !syntax.contains("port 67"), - "Rule syntax must not preserve DHCP 67" - ); - assert!( - !syntax.contains("port 68"), - "Rule syntax must not preserve DHCP 68" + syntax.contains("block drop quick proto tcp from any to any port 53"), + "Rule syntax must explicitly block DNS 53" ); + for port in ["port 53 ", "port 67 ", "port 68 "] { + assert!( + !syntax + .lines() + .any(|l| l.starts_with("pass ") && l.contains(port)), + "Rule syntax must not preserve {port}" + ); + } // Invariant: Default hermetic block drop with quick assert!( @@ -118,6 +120,7 @@ fn test_f29_macos_pf_isolator_lifecycle_and_contract() { #[test] fn test_f29_darwin_socket_inspection() { + let _probe_listener = std::net::TcpListener::bind("127.0.0.1:0").ok(); let sockets = get_active_darwin_sockets().expect("get_active_darwin_sockets must succeed"); assert!(!sockets.is_empty(), "Socket list should not be empty"); diff --git a/crates/killswitch-kernel-patcher/Cargo.toml b/crates/killswitch-kernel-patcher/Cargo.toml new file mode 100644 index 0000000..e30296e --- /dev/null +++ b/crates/killswitch-kernel-patcher/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "killswitch-kernel-patcher" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +description = "NVD API 2.0 / CISA KEV kernel vulnerability scanner and OS-native patch orchestrator" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +thiserror = { workspace = true } +reqwest = { workspace = true } + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_System_LibraryLoader", +] } +winreg = { workspace = true } + +[target.'cfg(unix)'.dependencies] +libc = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/crates/killswitch-kernel-patcher/run_m1_tests.bat b/crates/killswitch-kernel-patcher/run_m1_tests.bat new file mode 100644 index 0000000..c183997 --- /dev/null +++ b/crates/killswitch-kernel-patcher/run_m1_tests.bat @@ -0,0 +1,11 @@ +@echo off +cargo test -p killswitch-kernel-patcher --test cpe_tests +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% +cargo test -p killswitch-kernel-patcher --test discovery_tests +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% +cargo test -p killswitch-kernel-patcher --test privilege_tests +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% +cargo test -p killswitch-kernel-patcher +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% +cargo clippy -p killswitch-kernel-patcher --all-targets -- -D warnings +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% diff --git a/crates/killswitch-kernel-patcher/src/cpe.rs b/crates/killswitch-kernel-patcher/src/cpe.rs new file mode 100644 index 0000000..703843b --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/cpe.rs @@ -0,0 +1,336 @@ +//! NIST IR 7695 Common Platform Enumeration (CPE 2.3) formatting, escaping, and canonicalization. + +use serde::{Deserialize, Serialize}; + +/// CPE 2.3 part classification component. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum CpePart { + /// Applications and packages ("a"). + Application, + /// Operating system platforms and kernels ("o"). + OperatingSystem, + /// Hardware devices and chipsets ("h"). + Hardware, +} + +impl CpePart { + /// Returns the single-character string representation for formatted string binding. + #[must_use] + pub fn as_str(&self) -> &'static str { + match self { + Self::Application => "a", + Self::OperatingSystem => "o", + Self::Hardware => "h", + } + } +} + +/// NIST IR 7695 compliant CPE 2.3 Formatted String Binding representation. +/// +/// Contains exactly 11 attributes following the `cpe:2.3:` prefix, serialized +/// with 10 separating colons for a total of exactly 12 unescaped delimiter colons. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Cpe23 { + /// Part component (`a`, `o`, `h`). + pub part: CpePart, + /// Vendor identifier (e.g. `linux`, `microsoft`, `apple`). + pub vendor: String, + /// Product name (e.g. `linux_kernel`, `windows_11`, `macos`). + pub product: String, + /// Version identifier (e.g. `6.8.0`, `23h2`, `14.4.1`). + pub version: String, + /// Update/service pack identifier (or `*`). + pub update: String, + /// Edition identifier (or `*`). + pub edition: String, + /// Language code (or `*`). + pub language: String, + /// Software edition identifier (or `*`). + pub sw_edition: String, + /// Target software environment (or `*`). + pub target_sw: String, + /// Target hardware architecture (or `*`). + pub target_hw: String, + /// Other qualifiers (or `*`). + pub other: String, +} + +impl Default for Cpe23 { + fn default() -> Self { + Self { + part: CpePart::OperatingSystem, + vendor: "*".to_string(), + product: "*".to_string(), + version: "*".to_string(), + update: "*".to_string(), + edition: "*".to_string(), + language: "*".to_string(), + sw_edition: "*".to_string(), + target_sw: "*".to_string(), + target_hw: "*".to_string(), + other: "*".to_string(), + } + } +} + +impl Cpe23 { + /// Creates a new operating system CPE 2.3 with specified vendor, product, and version. + /// Remaining attributes default to wildcard ANY (`*`). + pub fn new_os( + vendor: impl Into, + product: impl Into, + version: impl Into, + ) -> Self { + Self { + part: CpePart::OperatingSystem, + vendor: vendor.into(), + product: product.into(), + version: version.into(), + ..Default::default() + } + } + + /// Serializes the CPE 2.3 instance into a NIST IR 7695 compliant formatted string binding. + #[must_use] + pub fn to_formatted_string(&self) -> String { + format!( + "cpe:2.3:{}:{}:{}:{}:{}:{}:{}:{}:{}:{}:{}", + self.part.as_str(), + escape_cpe_attribute(&self.vendor), + escape_cpe_attribute(&self.product), + escape_cpe_attribute(&self.version), + escape_cpe_attribute(&self.update), + escape_cpe_attribute(&self.edition), + escape_cpe_attribute(&self.language), + escape_cpe_attribute(&self.sw_edition), + escape_cpe_attribute(&self.target_sw), + escape_cpe_attribute(&self.target_hw), + escape_cpe_attribute(&self.other), + ) + } +} + +/// Escapes an attribute string for CPE 2.3 Formatted String Binding according to NIST IR 7695 Section 5.3.2. +#[must_use] +pub fn escape_cpe_attribute(input: &str) -> String { + let trimmed = input.trim(); + if trimmed.is_empty() || trimmed == "*" { + return "*".to_string(); + } + if trimmed == "-" { + return "-".to_string(); + } + + let mut out = String::with_capacity(trimmed.len() + 8); + let mut chars = trimmed.chars().peekable(); + + while let Some(ch) = chars.next() { + match ch { + '\\' => { + if let Some(&next) = chars.peek() { + if matches!( + next, + ':' | '\\' + | '*' + | '?' + | '/' + | '%' + | ';' + | '!' + | '"' + | '#' + | '$' + | '&' + | '\'' + | '(' + | ')' + | '+' + | ',' + | '<' + | '=' + | '>' + | '@' + | '[' + | ']' + | '^' + | '`' + | '{' + | '|' + | '}' + | '~' + ) { + out.push('\\'); + out.push(chars.next().unwrap()); + continue; + } + } + out.push('\\'); + out.push('\\'); + } + ':' => { + out.push('\\'); + out.push(':'); + } + '*' => { + out.push('\\'); + out.push('*'); + } + '?' => { + out.push('\\'); + out.push('?'); + } + '/' => { + out.push('\\'); + out.push('/'); + } + '%' => { + out.push('\\'); + out.push('%'); + } + ';' => { + out.push('\\'); + out.push(';'); + } + '!' | '"' | '#' | '$' | '&' | '\'' | '(' | ')' | '+' | ',' | '<' | '=' | '>' | '@' + | '[' | ']' | '^' | '`' | '{' | '|' | '}' | '~' => { + out.push('\\'); + out.push(ch); + } + c if c.is_whitespace() => { + if !out.ends_with('_') { + out.push('_'); + } + } + other => { + out.push(other.to_ascii_lowercase()); + } + } + } + + if out.is_empty() { + "*".to_string() + } else { + out + } +} + +/// Splits a CPE 2.3 string on delimiter colons while ignoring escaped colons (`\:`). +#[must_use] +pub fn split_unescaped_colons(s: &str) -> Vec { + let mut parts = Vec::new(); + let mut current = String::new(); + let mut chars = s.chars().peekable(); + + while let Some(ch) = chars.next() { + if ch == '\\' { + if let Some(&next) = chars.peek() { + if next == ':' { + chars.next(); + current.push('\\'); + current.push(':'); + continue; + } + } + current.push('\\'); + } else if ch == ':' { + parts.push(std::mem::take(&mut current)); + } else { + current.push(ch); + } + } + parts.push(current); + parts +} + +/// Canonicalizes Linux kernel release strings (e.g. "6.8.0-49-generic" -> "6.8.0"). +#[must_use] +pub fn canonicalize_linux_kernel_version(raw: &str) -> String { + let trimmed = raw.trim(); + let mut parts = Vec::new(); + let mut current_num = String::new(); + + for ch in trimmed.chars() { + if ch.is_ascii_digit() { + current_num.push(ch); + } else if ch == '.' { + if !current_num.is_empty() { + parts.push(std::mem::take(&mut current_num)); + if parts.len() == 3 { + break; + } + } else { + break; + } + } else { + if !current_num.is_empty() { + parts.push(std::mem::take(&mut current_num)); + } + break; + } + } + if !current_num.is_empty() && parts.len() < 3 { + parts.push(current_num); + } + + if parts.len() >= 2 { + parts.join(".") + } else if !trimmed.is_empty() { + escape_cpe_attribute(trimmed) + } else { + "*".to_string() + } +} + +/// Canonicalizes Windows OS build number, server flag, and display version to NVD CPE product and version. +#[must_use] +pub fn canonicalize_windows_cpe( + build: u32, + is_server: bool, + display_version: Option<&str>, +) -> (&'static str, String) { + if is_server { + let product = if build >= 26100 { + "windows_server_2025" + } else if build >= 20348 { + "windows_server_2022" + } else if build >= 17763 { + "windows_server_2019" + } else if build >= 14393 { + "windows_server_2016" + } else { + "windows_server" + }; + (product, "*".to_string()) + } else { + let product = if build >= 22000 { + "windows_11" + } else if build >= 10240 { + "windows_10" + } else { + "windows" + }; + let version = display_version + .map(escape_cpe_attribute) + .filter(|v| v != "*") + .unwrap_or_else(|| "*".to_string()); + (product, version) + } +} + +/// Canonicalizes macOS product version (e.g. "14.4.1 (a)" -> "14.4.1"). +#[must_use] +pub fn canonicalize_macos_version(raw: &str) -> String { + let trimmed = raw.trim(); + let clean = if let Some(idx) = trimmed.find('(') { + trimmed[..idx].trim() + } else if let Some(idx) = trimmed.find(' ') { + trimmed[..idx].trim() + } else { + trimmed + }; + if clean.is_empty() { + "*".to_string() + } else { + escape_cpe_attribute(clean) + } +} diff --git a/crates/killswitch-kernel-patcher/src/discovery/linux.rs b/crates/killswitch-kernel-patcher/src/discovery/linux.rs new file mode 100644 index 0000000..166ad4f --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/discovery/linux.rs @@ -0,0 +1,126 @@ +//! Linux host kernel discovery via `/proc/sys/kernel/osrelease`, `/etc/os-release`, and `libc::uname`. + +#[cfg(target_os = "linux")] +use crate::cpe::{canonicalize_linux_kernel_version, Cpe23}; +use crate::error::PatcherError; +use crate::types::HostKernelInfo; +#[cfg(target_os = "linux")] +use crate::types::OsFamily; + +/// Metadata parsed from `/etc/os-release` or `/usr/lib/os-release`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct OsRelease { + pub id: String, + pub version_id: String, + pub pretty_name: String, + pub id_like: Vec, +} + +/// Parses standard freedesktop.org `/etc/os-release` file content. +#[must_use] +pub fn parse_os_release_content(content: &str) -> OsRelease { + let mut info = OsRelease::default(); + for line in content.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if let Some((k, v)) = line.split_once('=') { + let key = k.trim(); + let mut val = v.trim(); + if ((val.starts_with('"') && val.ends_with('"')) + || (val.starts_with('\'') && val.ends_with('\''))) + && val.len() >= 2 + { + val = &val[1..val.len() - 1]; + } + match key { + "ID" => info.id = val.to_ascii_lowercase(), + "VERSION_ID" => info.version_id = val.to_string(), + "PRETTY_NAME" => info.pretty_name = val.to_string(), + "ID_LIKE" => { + info.id_like = val + .split_whitespace() + .map(|s| s.to_ascii_lowercase()) + .collect(); + } + _ => {} + } + } + } + info +} + +#[cfg(target_os = "linux")] +pub fn detect_linux_os_release() -> OsRelease { + use std::fs; + if let Ok(content) = fs::read_to_string("/etc/os-release") { + return parse_os_release_content(&content); + } + if let Ok(content) = fs::read_to_string("/usr/lib/os-release") { + return parse_os_release_content(&content); + } + OsRelease::default() +} + +#[cfg(target_os = "linux")] +pub fn detect_linux_kernel_release() -> Result { + use std::fs; + if let Ok(content) = fs::read_to_string("/proc/sys/kernel/osrelease") { + let release = content.trim().to_string(); + if !release.is_empty() { + return Ok(release); + } + } + + // Fallback to libc::uname + unsafe { + let mut uts = std::mem::zeroed::(); + if libc::uname(&mut uts) != 0 { + return Err(PatcherError::DetectionFailed( + "uname syscall failed".to_string(), + )); + } + let c_str = std::ffi::CStr::from_ptr(uts.release.as_ptr()); + let release = c_str.to_string_lossy().trim().to_string(); + if release.is_empty() { + Err(PatcherError::DetectionFailed( + "Empty kernel release returned by uname".to_string(), + )) + } else { + Ok(release) + } + } +} + +#[cfg(target_os = "linux")] +pub fn detect_linux_host_kernel() -> Result { + let kernel_release = detect_linux_kernel_release()?; + let os_release = detect_linux_os_release(); + let base_version = canonicalize_linux_kernel_version(&kernel_release); + let cpe = Cpe23::new_os("linux", "linux_kernel", base_version); + let cpe23 = cpe.to_formatted_string(); + + let os_version = if !os_release.version_id.is_empty() { + os_release.version_id + } else if !os_release.pretty_name.is_empty() { + os_release.pretty_name + } else { + "unknown".to_string() + }; + + Ok(HostKernelInfo { + os_family: OsFamily::Linux, + kernel_release, + os_version, + cpe23, + architecture: std::env::consts::ARCH.to_string(), + }) +} + +#[cfg(not(target_os = "linux"))] +pub fn detect_linux_host_kernel() -> Result { + Err(PatcherError::UnsupportedPlatform( + "Linux detection invoked on non-Linux host".to_string(), + )) +} diff --git a/crates/killswitch-kernel-patcher/src/discovery/macos.rs b/crates/killswitch-kernel-patcher/src/discovery/macos.rs new file mode 100644 index 0000000..00b25ab --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/discovery/macos.rs @@ -0,0 +1,95 @@ +//! macOS host kernel discovery using `libc::sysctlbyname`. + +#[cfg(target_os = "macos")] +use crate::cpe::{canonicalize_macos_version, Cpe23}; +use crate::error::PatcherError; +use crate::types::HostKernelInfo; +#[cfg(target_os = "macos")] +use crate::types::OsFamily; + +#[cfg(target_os = "macos")] +pub fn sysctl_string(name: &str) -> Result { + use std::ffi::CString; + use std::ptr; + + let c_name = CString::new(name) + .map_err(|e| PatcherError::DetectionFailed(format!("Invalid sysctl name '{name}': {e}")))?; + + let mut size: libc::size_t = 0; + let ret = unsafe { + libc::sysctlbyname( + c_name.as_ptr(), + ptr::null_mut(), + &mut size, + ptr::null_mut(), + 0, + ) + }; + if ret != 0 || size == 0 { + return Err(PatcherError::DetectionFailed(format!( + "sysctlbyname('{name}') failed to query size: errno={}", + std::io::Error::last_os_error() + ))); + } + + let mut buf = vec![0u8; size]; + let ret = unsafe { + libc::sysctlbyname( + c_name.as_ptr(), + buf.as_mut_ptr() as *mut libc::c_void, + &mut size, + ptr::null_mut(), + 0, + ) + }; + if ret != 0 { + return Err(PatcherError::DetectionFailed(format!( + "sysctlbyname('{name}') failed to retrieve value: errno={}", + std::io::Error::last_os_error() + ))); + } + + while buf.last() == Some(&0) { + buf.pop(); + } + String::from_utf8(buf).map_err(|e| { + PatcherError::DetectionFailed(format!("sysctlbyname('{name}') returned non-UTF8: {e}")) + }) +} + +#[cfg(target_os = "macos")] +pub fn detect_macos_host_kernel() -> Result { + let kernel_release = sysctl_string("kern.osrelease")?; + let os_version = sysctl_string("kern.osproductversion") + .map(|v| canonicalize_macos_version(&v)) + .unwrap_or_else(|_| { + // Darwin math fallback: Darwin 20+ -> macOS (Darwin - 9) + if let Some(major) = kernel_release + .split('.') + .next() + .and_then(|s| s.parse::().ok()) + .filter(|&m| m >= 20) + { + return format!("{}.0", major - 9); + } + "14.0".to_string() + }); + + let cpe = Cpe23::new_os("apple", "macos", &os_version); + let cpe23 = cpe.to_formatted_string(); + + Ok(HostKernelInfo { + os_family: OsFamily::MacOS, + kernel_release, + os_version, + cpe23, + architecture: std::env::consts::ARCH.to_string(), + }) +} + +#[cfg(not(target_os = "macos"))] +pub fn detect_macos_host_kernel() -> Result { + Err(PatcherError::UnsupportedPlatform( + "macOS detection invoked on non-macOS host".to_string(), + )) +} diff --git a/crates/killswitch-kernel-patcher/src/discovery/mod.rs b/crates/killswitch-kernel-patcher/src/discovery/mod.rs new file mode 100644 index 0000000..d0bb96b --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/discovery/mod.rs @@ -0,0 +1,162 @@ +//! Host operating system and kernel discovery. + +pub mod linux; +pub mod macos; +pub mod windows; + +use crate::cpe::{ + canonicalize_linux_kernel_version, canonicalize_macos_version, canonicalize_windows_cpe, Cpe23, +}; +use crate::error::PatcherError; +use crate::types::{HostKernelInfo, OsFamily}; + +/// Returns the compile-time host CPU architecture. +#[inline] +#[must_use] +pub fn detect_architecture() -> String { + std::env::consts::ARCH.to_string() +} + +/// Dispatches kernel detection to the current operating system platform. +pub fn detect_host_kernel() -> Result { + #[cfg(target_os = "windows")] + { + windows::detect_windows_kernel() + } + #[cfg(target_os = "linux")] + { + linux::detect_linux_host_kernel() + } + #[cfg(target_os = "macos")] + { + macos::detect_macos_host_kernel() + } + #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))] + { + Err(PatcherError::UnsupportedPlatform( + std::env::consts::OS.to_string(), + )) + } +} + +/// Pure parser for Linux kernel discovery metadata (decoupled for testing). +#[must_use] +pub fn parse_linux_kernel_info( + kernel_release: &str, + os_release_content: Option<&str>, + arch: &str, +) -> HostKernelInfo { + let os_release = os_release_content + .map(linux::parse_os_release_content) + .unwrap_or_default(); + + let base_version = canonicalize_linux_kernel_version(kernel_release); + let cpe = Cpe23::new_os("linux", "linux_kernel", base_version); + let cpe23 = cpe.to_formatted_string(); + + let os_version = if !os_release.version_id.is_empty() { + os_release.version_id + } else if !os_release.pretty_name.is_empty() { + os_release.pretty_name + } else { + "unknown".to_string() + }; + + HostKernelInfo { + os_family: OsFamily::Linux, + kernel_release: kernel_release.trim().to_string(), + os_version, + cpe23, + architecture: arch.to_string(), + } +} + +/// Pure parser for Windows kernel discovery metadata (decoupled for testing). +#[must_use] +pub fn parse_windows_kernel_info( + major: u32, + minor: u32, + build: u32, + ubr: Option, + product_name: Option<&str>, + display_version: Option<&str>, + arch: &str, +) -> HostKernelInfo { + let is_server = product_name + .map(|p| p.to_ascii_lowercase().contains("server")) + .unwrap_or(false); + + let (cpe_product, cpe_version) = canonicalize_windows_cpe(build, is_server, display_version); + let cpe = Cpe23::new_os("microsoft", cpe_product, cpe_version); + let cpe23 = cpe.to_formatted_string(); + + let kernel_release = match ubr { + Some(u) => format!("{major}.{minor}.{build}.{u}"), + None => format!("{major}.{minor}.{build}"), + }; + + let os_version = match (product_name, display_version) { + (Some(p), Some(dv)) => format!("{p} {dv} (Build {kernel_release})"), + (Some(p), None) => format!("{p} (Build {kernel_release})"), + (None, Some(dv)) => { + let label = if is_server { + "Windows Server" + } else if build >= 22000 { + "Windows 11" + } else { + "Windows 10" + }; + format!("{label} {dv} (Build {kernel_release})") + } + (None, None) => { + let label = if is_server { + "Windows Server" + } else if build >= 22000 { + "Windows 11" + } else { + "Windows 10" + }; + format!("{label} (Build {kernel_release})") + } + }; + + HostKernelInfo { + os_family: OsFamily::Windows, + kernel_release, + os_version, + cpe23, + architecture: arch.to_string(), + } +} + +/// Pure parser for macOS kernel discovery metadata (decoupled for testing). +#[must_use] +pub fn parse_macos_kernel_info( + os_product_version: Option<&str>, + kernel_release: &str, + arch: &str, +) -> HostKernelInfo { + let os_version = os_product_version + .map(canonicalize_macos_version) + .unwrap_or_else(|| { + if let Some(major_str) = kernel_release.split('.').next() { + if let Ok(major) = major_str.parse::() { + if major >= 20 { + return format!("{}.0", major - 9); + } + } + } + "14.0".to_string() + }); + + let cpe = Cpe23::new_os("apple", "macos", &os_version); + let cpe23 = cpe.to_formatted_string(); + + HostKernelInfo { + os_family: OsFamily::MacOS, + kernel_release: kernel_release.trim().to_string(), + os_version, + cpe23, + architecture: arch.to_string(), + } +} diff --git a/crates/killswitch-kernel-patcher/src/discovery/windows.rs b/crates/killswitch-kernel-patcher/src/discovery/windows.rs new file mode 100644 index 0000000..6672eaf --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/discovery/windows.rs @@ -0,0 +1,181 @@ +//! Windows host kernel discovery using dynamic `ntdll!RtlGetVersion` and registry inspection. + +#[cfg(windows)] +use crate::cpe::{canonicalize_windows_cpe, Cpe23}; +use crate::error::PatcherError; +use crate::types::HostKernelInfo; +#[cfg(windows)] +use crate::types::OsFamily; + +#[cfg(windows)] +#[repr(C)] +#[derive(Debug, Copy, Clone)] +#[allow(non_snake_case)] +pub struct OSVERSIONINFOEXW { + pub dwOSVersionInfoSize: u32, + pub dwMajorVersion: u32, + pub dwMinorVersion: u32, + pub dwBuildNumber: u32, + pub dwPlatformId: u32, + pub szCSDVersion: [u16; 128], + pub wServicePackMajor: u16, + pub wServicePackMinor: u16, + pub wSuiteMask: u16, + pub wProductType: u8, + pub wReserved: u8, +} + +#[cfg(windows)] +type RtlGetVersionFn = unsafe extern "system" fn(*mut OSVERSIONINFOEXW) -> i32; + +/// Raw NT kernel version fields extracted via `RtlGetVersion`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawNtVersion { + pub major: u32, + pub minor: u32, + pub build: u32, + pub is_workstation: bool, +} + +#[cfg(windows)] +pub fn query_ntdll_rtl_get_version() -> Result { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8); + if ntdll.is_null() { + return Err(PatcherError::DetectionFailed( + "ntdll.dll module handle not found".into(), + )); + } + let proc = GetProcAddress(ntdll, c"RtlGetVersion".as_ptr() as *const u8); + let Some(proc) = proc else { + return Err(PatcherError::DetectionFailed( + "RtlGetVersion symbol not found in ntdll.dll".into(), + )); + }; + let rtl_get_version: RtlGetVersionFn = std::mem::transmute(proc); + + let mut os_info: OSVERSIONINFOEXW = std::mem::zeroed(); + os_info.dwOSVersionInfoSize = std::mem::size_of::() as u32; + + let status = rtl_get_version(&mut os_info); + if status != 0 { + return Err(PatcherError::DetectionFailed(format!( + "RtlGetVersion failed with NTSTATUS 0x{status:08X}" + ))); + } + + Ok(RawNtVersion { + major: os_info.dwMajorVersion, + minor: os_info.dwMinorVersion, + build: os_info.dwBuildNumber, + is_workstation: os_info.wProductType == 1, + }) + } +} + +/// Registry metadata read from `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct WindowsRegistryInfo { + pub ubr: Option, + pub display_version: Option, + pub product_name: Option, + pub edition_id: Option, + pub installation_type: Option, +} + +#[cfg(windows)] +pub fn query_windows_registry() -> WindowsRegistryInfo { + use winreg::enums::HKEY_LOCAL_MACHINE; + use winreg::RegKey; + + let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); + let key = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"); + + match key { + Ok(k) => { + let ubr: Option = k.get_value("UBR").ok(); + let display_version: Option = k + .get_value("DisplayVersion") + .or_else(|_| k.get_value("ReleaseId")) + .ok(); + let product_name: Option = k.get_value("ProductName").ok(); + let edition_id: Option = k.get_value("EditionID").ok(); + let installation_type: Option = k.get_value("InstallationType").ok(); + WindowsRegistryInfo { + ubr, + display_version, + product_name, + edition_id, + installation_type, + } + } + Err(_) => WindowsRegistryInfo::default(), + } +} + +#[cfg(windows)] +pub fn detect_windows_kernel() -> Result { + let raw = query_ntdll_rtl_get_version()?; + let reg = query_windows_registry(); + + let is_server = !raw.is_workstation + || reg + .installation_type + .as_deref() + .map(|s| s.eq_ignore_ascii_case("Server")) + .unwrap_or(false); + + let (cpe_product, cpe_version) = + canonicalize_windows_cpe(raw.build, is_server, reg.display_version.as_deref()); + let cpe = Cpe23::new_os("microsoft", cpe_product, cpe_version); + let cpe23 = cpe.to_formatted_string(); + + let kernel_release = match reg.ubr { + Some(ubr) => format!("{}.{}.{}.{}", raw.major, raw.minor, raw.build, ubr), + None => format!("{}.{}.{}", raw.major, raw.minor, raw.build), + }; + + let product_label = if is_server { + if raw.build >= 26100 { + "Windows Server 2025" + } else if raw.build >= 20348 { + "Windows Server 2022" + } else if raw.build >= 17763 { + "Windows Server 2019" + } else if raw.build >= 14393 { + "Windows Server 2016" + } else { + "Windows Server" + } + } else if raw.build >= 22000 { + "Windows 11" + } else if raw.build >= 10240 { + "Windows 10" + } else { + "Windows" + }; + + let os_version = match (reg.product_name.as_deref(), reg.display_version.as_deref()) { + (Some(p), Some(dv)) => format!("{p} {dv} (Build {kernel_release})"), + (Some(p), None) => format!("{p} (Build {kernel_release})"), + (None, Some(dv)) => format!("{product_label} {dv} (Build {kernel_release})"), + (None, None) => format!("{product_label} (Build {kernel_release})"), + }; + + Ok(HostKernelInfo { + os_family: OsFamily::Windows, + kernel_release, + os_version, + cpe23, + architecture: std::env::consts::ARCH.to_string(), + }) +} + +#[cfg(not(windows))] +pub fn detect_windows_kernel() -> Result { + Err(PatcherError::UnsupportedPlatform( + "Windows detection invoked on non-Windows host".to_string(), + )) +} diff --git a/crates/killswitch-kernel-patcher/src/error.rs b/crates/killswitch-kernel-patcher/src/error.rs new file mode 100644 index 0000000..b34c4d6 --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/error.rs @@ -0,0 +1,34 @@ +//! Error types for `killswitch-kernel-patcher`. + +use thiserror::Error; + +/// Error taxonomy for the `killswitch-kernel-patcher` crate. +#[derive(Debug, Error)] +pub enum PatcherError { + #[error("Insufficient privileges: kernel patch execution requires root/Administrator")] + InsufficientPrivileges, + + #[error("Unsupported platform: {0}")] + UnsupportedPlatform(String), + + #[error("Kernel detection failed: {0}")] + DetectionFailed(String), + + #[error("NVD API error: {0}")] + NvdApiError(String), + + #[error("Network error: {0}")] + Network(#[from] reqwest::Error), + + #[error("Serialization error: {0}")] + Serialization(#[from] serde_json::Error), + + #[error("Command execution error: {0}")] + ExecutionFailed(String), + + #[error("Rate limited by NVD API")] + RateLimited, + + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), +} diff --git a/crates/killswitch-kernel-patcher/src/lib.rs b/crates/killswitch-kernel-patcher/src/lib.rs new file mode 100644 index 0000000..fb1e652 --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/lib.rs @@ -0,0 +1,15 @@ +//! `killswitch-kernel-patcher`: NVD API 2.0 / CISA KEV kernel vulnerability scanner and OS-native patch orchestrator. + +pub mod cpe; +pub mod discovery; +pub mod error; +pub mod patcher; +pub mod privilege; +pub mod types; + +// Re-exports +pub use cpe::Cpe23; +pub use error::PatcherError; +pub use patcher::KernelPatcher; +pub use privilege::is_elevated; +pub use types::{HostKernelInfo, KernelVulnerability, OsFamily, PatchExecutionResult, ScanOptions}; diff --git a/crates/killswitch-kernel-patcher/src/patcher.rs b/crates/killswitch-kernel-patcher/src/patcher.rs new file mode 100644 index 0000000..eed9027 --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/patcher.rs @@ -0,0 +1,381 @@ +//! NVD API 2.0 vulnerability scanner and OS-native patch orchestrator. + +use serde_json::Value; +use std::time::Duration; + +use crate::error::PatcherError; +use crate::privilege::is_elevated; +use crate::types::{HostKernelInfo, KernelVulnerability, PatchExecutionResult, ScanOptions}; + +/// Orchestrates OS kernel vulnerability scanning against NVD API 2.0 and native patch execution. +#[derive(Debug, Clone)] +pub struct KernelPatcher { + base_url: String, + client: reqwest::Client, +} + +impl Default for KernelPatcher { + fn default() -> Self { + Self::new() + } +} + +impl KernelPatcher { + /// Constructs a patcher pointing to the official NIST NVD API 2.0 endpoint. + #[must_use] + pub fn new() -> Self { + Self::with_base_url("https://services.nvd.nist.gov/rest/json/cves/2.0") + } + + /// Constructs a patcher pointing to a custom endpoint URL (useful for testing and mirrors). + #[must_use] + pub fn with_base_url(base_url: impl Into) -> Self { + Self { + base_url: base_url.into(), + client: reqwest::Client::new(), + } + } + + /// Queries NVD API 2.0 for vulnerabilities matching the target or detected kernel CPE, + /// extracting CVSS v3.1 metrics and CISA KEV metadata, and ranking findings KEV-first. + pub async fn scan_kernel_vulnerabilities( + &self, + options: &ScanOptions, + ) -> Result, PatcherError> { + let target_cpe = match &options.cpe { + Some(c) => c.clone(), + None => HostKernelInfo::detect_host_kernel()?.cpe23, + }; + + let separator = if self.base_url.contains('?') { + '&' + } else { + '?' + }; + let url = format!("{}{}cpeName={}", self.base_url, separator, target_cpe); + + let mut req = self + .client + .get(&url) + .timeout(Duration::from_secs(options.timeout_secs)); + + // API Key resolution: options.api_key takes precedence, then runtime env NVD_API_KEY. + // Invariant: Never passed via CLI arguments to prevent leaking into OS process tables. + let resolved_api_key = options + .api_key + .as_deref() + .map(str::trim) + .filter(|k| !k.is_empty()) + .map(ToOwned::to_owned) + .or_else(|| { + std::env::var("NVD_API_KEY") + .ok() + .map(|k| k.trim().to_string()) + .filter(|k| !k.is_empty()) + }); + + if let Some(key) = resolved_api_key { + req = req.header("apiKey", key); + } + + let resp = req.send().await.map_err(PatcherError::Network)?; + + if resp.status().as_u16() == 429 { + return Err(PatcherError::RateLimited); + } + + if !resp.status().is_success() { + return Err(PatcherError::NvdApiError(format!( + "NVD API returned HTTP error: {}", + resp.status() + ))); + } + + let body_text = resp.text().await.map_err(PatcherError::Network)?; + let parsed: Value = + serde_json::from_str(&body_text).map_err(PatcherError::Serialization)?; + + let mut vulnerabilities = Vec::new(); + + if let Some(vuln_items) = parsed.get("vulnerabilities").and_then(|v| v.as_array()) { + for item in vuln_items { + let Some(cve) = item.get("cve") else { continue }; + let Some(id) = cve.get("id").and_then(|i| i.as_str()) else { + continue; + }; + + // Description: English description preferred + let mut description = String::new(); + if let Some(desc_array) = cve.get("descriptions").and_then(|d| d.as_array()) { + for d in desc_array { + if d.get("lang").and_then(|l| l.as_str()) == Some("en") { + if let Some(v) = d.get("value").and_then(|s| s.as_str()) { + description = v.to_string(); + break; + } + } + } + if description.is_empty() { + if let Some(first) = desc_array + .first() + .and_then(|d| d.get("value")) + .and_then(|s| s.as_str()) + { + description = first.to_string(); + } + } + } + + // CVSS v3.1 Metrics + let mut cvss_score: Option = None; + let mut cvss_severity: Option = None; + + if let Some(v31_array) = cve + .get("metrics") + .and_then(|m| m.get("cvssMetricV31")) + .and_then(|a| a.as_array()) + { + if let Some(first_v31) = v31_array.first() { + if let Some(data) = first_v31.get("cvssData") { + cvss_score = data + .get("baseScore") + .and_then(|s| s.as_f64()) + .map(|f| f as f32); + cvss_severity = data + .get("baseSeverity") + .and_then(|s| s.as_str()) + .map(|s| s.to_string()); + } + } + } + + // CISA KEV Fields + let cisa_exploit_add = cve + .get("cisaExploitAdd") + .and_then(|s| s.as_str()) + .map(ToString::to_string); + let cisa_action_due = cve + .get("cisaActionDue") + .and_then(|s| s.as_str()) + .map(ToString::to_string); + let cisa_required_action = cve + .get("cisaRequiredAction") + .and_then(|s| s.as_str()) + .map(ToString::to_string); + let cisa_vulnerability_name = cve + .get("cisaVulnerabilityName") + .and_then(|s| s.as_str()) + .map(ToString::to_string); + + let is_cisa_kev = cisa_exploit_add.is_some() + || cisa_action_due.is_some() + || cisa_required_action.is_some() + || cisa_vulnerability_name.is_some(); + + // Threshold & KEV-only filters + if options.kev_only && !is_cisa_kev { + continue; + } + + if let Some(min_score) = options.min_cvss_score { + let score = cvss_score.unwrap_or(0.0); + if score < min_score { + continue; + } + } + + vulnerabilities.push(KernelVulnerability { + cve_id: id.to_string(), + description, + cvss_v31_score: cvss_score, + cvss_v31_severity: cvss_severity, + is_cisa_kev, + cisa_exploit_add, + cisa_action_due, + cisa_required_action, + cisa_vulnerability_name, + }); + } + } + + // Rank findings: CISA KEV entries first, descending by CVSS v3.1 base score + vulnerabilities.sort_by(|a, b| match (a.is_cisa_kev, b.is_cisa_kev) { + (true, false) => std::cmp::Ordering::Less, + (false, true) => std::cmp::Ordering::Greater, + _ => { + let sa = a.cvss_v31_score.unwrap_or(-1.0); + let sb = b.cvss_v31_score.unwrap_or(-1.0); + sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal) + } + }); + + Ok(vulnerabilities) + } + + /// Executes or dry-runs the OS-native kernel patch workflow. + /// + /// Non-dry-run operations require elevated privileges and will immediately fail closed + /// with `PatcherError::InsufficientPrivileges` if not running as root/Administrator. + pub async fn apply_os_kernel_patch( + &self, + dry_run: bool, + ) -> Result { + if !dry_run && !is_elevated() { + return Err(PatcherError::InsufficientPrivileges); + } + + #[cfg(target_os = "windows")] + { + let command = "UsoClient.exe".to_string(); + let args = vec!["StartInstall".to_string()]; + let os_subsystem = "UsoClient".to_string(); + + if dry_run { + Ok(PatchExecutionResult { + dry_run: true, + command: command.clone(), + args: args.clone(), + success: true, + output: format!( + "[DRY-RUN] Planned execution: {} {}", + command, + args.join(" ") + ), + os_subsystem, + }) + } else { + let status = tokio::process::Command::new(&command) + .args(&args) + .output() + .await + .map_err(|e| PatcherError::ExecutionFailed(e.to_string()))?; + let output = String::from_utf8_lossy(&status.stdout).to_string(); + Ok(PatchExecutionResult { + dry_run: false, + command, + args, + success: status.status.success(), + output, + os_subsystem, + }) + } + } + + #[cfg(target_os = "linux")] + { + let has_livepatch = std::path::Path::new("/usr/bin/canonical-livepatch").exists() + || std::path::Path::new("/snap/bin/canonical-livepatch").exists(); + + let (command, args, os_subsystem) = if has_livepatch { + ( + "canonical-livepatch".to_string(), + vec!["refresh".to_string()], + "canonical-livepatch".to_string(), + ) + } else if std::path::Path::new("/usr/bin/apt-get").exists() { + ( + "apt-get".to_string(), + vec![ + "upgrade".to_string(), + "-y".to_string(), + "linux-image-generic".to_string(), + ], + "apt-get".to_string(), + ) + } else { + ( + "dnf".to_string(), + vec![ + "upgrade".to_string(), + "--security".to_string(), + "-y".to_string(), + "kernel".to_string(), + ], + "dnf".to_string(), + ) + }; + + if dry_run { + Ok(PatchExecutionResult { + dry_run: true, + command: command.clone(), + args: args.clone(), + success: true, + output: format!( + "[DRY-RUN] Planned execution: {} {}", + command, + args.join(" ") + ), + os_subsystem, + }) + } else { + let status = tokio::process::Command::new(&command) + .args(&args) + .output() + .await + .map_err(|e| PatcherError::ExecutionFailed(e.to_string()))?; + let output = format!( + "{}{}", + String::from_utf8_lossy(&status.stdout), + String::from_utf8_lossy(&status.stderr) + ); + Ok(PatchExecutionResult { + dry_run: false, + command, + args, + success: status.status.success(), + output, + os_subsystem, + }) + } + } + + #[cfg(target_os = "macos")] + { + let command = "softwareupdate".to_string(); + let args = vec!["--install".to_string(), "--recommended".to_string()]; + let os_subsystem = "softwareupdate".to_string(); + + if dry_run { + Ok(PatchExecutionResult { + dry_run: true, + command: command.clone(), + args: args.clone(), + success: true, + output: format!( + "[DRY-RUN] Planned execution: {} {}", + command, + args.join(" ") + ), + os_subsystem, + }) + } else { + let status = tokio::process::Command::new(&command) + .args(&args) + .output() + .await + .map_err(|e| PatcherError::ExecutionFailed(e.to_string()))?; + let output = format!( + "{}{}", + String::from_utf8_lossy(&status.stdout), + String::from_utf8_lossy(&status.stderr) + ); + Ok(PatchExecutionResult { + dry_run: false, + command, + args, + success: status.status.success(), + output, + os_subsystem, + }) + } + } + + #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))] + { + Err(PatcherError::UnsupportedPlatform( + std::env::consts::OS.to_string(), + )) + } + } +} diff --git a/crates/killswitch-kernel-patcher/src/privilege.rs b/crates/killswitch-kernel-patcher/src/privilege.rs new file mode 100644 index 0000000..361d6bc --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/privilege.rs @@ -0,0 +1,63 @@ +//! Privilege elevation verification. + +/// Returns `true` if the calling process possesses elevated administrative / root privileges. +/// Enforces fail-closed semantics: returns `false` on any OS API failure or error. +#[must_use] +pub fn is_elevated() -> bool { + #[cfg(windows)] + { + windows::is_current_process_elevated() + } + #[cfg(unix)] + { + unix::is_current_process_elevated() + } + #[cfg(not(any(windows, unix)))] + { + false + } +} + +#[cfg(unix)] +pub mod unix { + /// Checks if the effective UID of the current process is root (0). + /// + /// Safety: `libc::geteuid()` is an infallible, stateless POSIX syscall. + #[inline] + #[must_use] + pub fn is_current_process_elevated() -> bool { + unsafe { libc::geteuid() == 0 } + } +} + +#[cfg(windows)] +pub mod windows { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::Security::{ + GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + /// Checks if the current process token has elevated privileges (`TokenElevation`). + /// Fails closed and returns `false` on any Win32 API failure. + #[must_use] + pub fn is_current_process_elevated() -> bool { + unsafe { + let mut token: HANDLE = std::ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + return false; + } + let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 }; + let mut return_length: u32 = 0; + let ok = GetTokenInformation( + token, + TokenElevation, + &mut elevation as *mut _ as *mut core::ffi::c_void, + std::mem::size_of::() as u32, + &mut return_length, + ); + CloseHandle(token); + ok != 0 && elevation.TokenIsElevated != 0 + } + } +} diff --git a/crates/killswitch-kernel-patcher/src/types.rs b/crates/killswitch-kernel-patcher/src/types.rs new file mode 100644 index 0000000..145625f --- /dev/null +++ b/crates/killswitch-kernel-patcher/src/types.rs @@ -0,0 +1,141 @@ +//! Core type definitions for `killswitch-kernel-patcher`. + +use crate::error::PatcherError; +use serde::{Deserialize, Serialize}; + +/// Operating system platform family detected on the host. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum OsFamily { + Linux, + Windows, + MacOS, + Unknown(String), +} + +impl OsFamily { + #[inline] + #[must_use] + pub fn is_linux(&self) -> bool { + matches!(self, Self::Linux) + } + + #[inline] + #[must_use] + pub fn is_windows(&self) -> bool { + matches!(self, Self::Windows) + } + + #[inline] + #[must_use] + pub fn is_macos(&self) -> bool { + matches!(self, Self::MacOS) + } +} + +impl std::fmt::Display for OsFamily { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Linux => write!(f, "Linux"), + Self::Windows => write!(f, "Windows"), + Self::MacOS => write!(f, "macOS"), + Self::Unknown(name) => write!(f, "Unknown ({name})"), + } + } +} + +/// Host operating system and kernel version discovery metadata. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HostKernelInfo { + /// Operating system platform family. + pub os_family: OsFamily, + /// Kernel release version (e.g. "6.8.0-45-generic", "10.0.22631.3880", "23.4.0"). + pub kernel_release: String, + /// User-facing OS version (e.g. "24.04", "Windows 11 23H2", "14.4.1"). + pub os_version: String, + /// NIST Common Platform Enumeration 2.3 formatted identifier. + pub cpe23: String, + /// Target hardware CPU architecture (e.g. "x86_64", "aarch64"). + pub architecture: String, +} + +impl HostKernelInfo { + /// Probes the host system and constructs verified `HostKernelInfo`. + pub fn detect_host_kernel() -> Result { + crate::discovery::detect_host_kernel() + } + + /// Returns the CPE 2.3 formatted string. + #[inline] + #[must_use] + pub fn to_cpe23(&self) -> String { + self.cpe23.clone() + } +} + +/// Kernel vulnerability record parsed from NVD API 2.0 / CISA KEV catalog. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct KernelVulnerability { + /// Common Vulnerabilities and Exposures (CVE) identifier (e.g. "CVE-2024-21338"). + pub cve_id: String, + /// Primary vulnerability description. + pub description: String, + /// CVSS v3.1 base score if scored (0.0 - 10.0). + pub cvss_v31_score: Option, + /// CVSS v3.1 qualitative severity rating ("LOW", "MEDIUM", "HIGH", "CRITICAL"). + pub cvss_v31_severity: Option, + /// Whether this vulnerability is listed in the CISA Known Exploited Vulnerabilities catalog. + pub is_cisa_kev: bool, + /// Date added to the CISA KEV catalog (YYYY-MM-DD). + pub cisa_exploit_add: Option, + /// Remediation due date mandated by CISA BOD 22-01. + pub cisa_action_due: Option, + /// Required remediation action specified by CISA. + pub cisa_required_action: Option, + /// Descriptive vulnerability name from CISA KEV. + pub cisa_vulnerability_name: Option, +} + +/// Options configuring the NVD vulnerability scan. +#[derive(Debug, Clone)] +pub struct ScanOptions { + /// Target CPE 2.3 string (defaults to auto-detected host kernel CPE). + pub cpe: Option, + /// Minimum CVSS score threshold for returned findings (inclusive). + pub min_cvss_score: Option, + /// If true, only return vulnerabilities confirmed in the CISA KEV catalog. + pub kev_only: bool, + /// Optional NVD API key (resolved from `std::env::var("NVD_API_KEY")`, never CLI arguments). + pub api_key: Option, + /// HTTP request timeout in seconds. + pub timeout_secs: u64, +} + +impl Default for ScanOptions { + fn default() -> Self { + Self { + cpe: None, + min_cvss_score: None, + kev_only: false, + api_key: None, + timeout_secs: 30, + } + } +} + +/// Result of an OS-native kernel patch execution or dry-run evaluation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PatchExecutionResult { + /// True if executed in safe simulation mode with zero system modifications. + pub dry_run: bool, + /// Primary executable command that was or would be invoked. + pub command: String, + /// Command-line arguments. + pub args: Vec, + /// Whether the process exited successfully (exit code 0). + pub success: bool, + /// Combined stdout and stderr output. + pub output: String, + /// Subsystem identifier (e.g. "canonical-livepatch", "apt", "dnf", "UsoClient", "softwareupdate"). + pub os_subsystem: String, +} diff --git a/crates/killswitch-kernel-patcher/tests/common/mod.rs b/crates/killswitch-kernel-patcher/tests/common/mod.rs new file mode 100644 index 0000000..289bc57 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/common/mod.rs @@ -0,0 +1,692 @@ +//! Shared test harness, authentic NVD API 2.0 JSON fixtures, ephemeral Tokio mock server, +//! and verification helper utilities for `killswitch-kernel-patcher`. + +#![allow(dead_code)] + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::oneshot; + +use killswitch_kernel_patcher::{HostKernelInfo, KernelVulnerability, OsFamily, ScanOptions}; + +// ============================================================================= +// 1. Authentic NIST NVD API 2.0 JSON Fixtures +// ============================================================================= + +/// Empty valid NVD API 2.0 response with 0 CVE entries. +pub const FIXTURE_EMPTY_NVD_JSON: &str = r#"{ + "resultsPerPage": 0, + "startIndex": 0, + "totalResults": 0, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [] +}"#; + +/// Single CISA KEV vulnerability fixture (CVE-2024-1086: Linux netfilter use-after-free). +pub const FIXTURE_SINGLE_KEV_CVE_JSON: &str = r#"{ + "resultsPerPage": 1, + "startIndex": 0, + "totalResults": 1, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2024-1086", + "sourceIdentifier": "cve@mitre.org", + "published": "2024-01-31T13:15:08.527", + "lastModified": "2024-02-05T14:15:09.123", + "vulnStatus": "Analyzed", + "descriptions": [ + { + "lang": "en", + "value": "A use-after-free vulnerability in the Linux kernel netfilter nf_tables component allows local privilege escalation." + } + ], + "metrics": { + "cvssMetricV31": [ + { + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": { + "version": "3.1", + "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", + "attackVector": "LOCAL", + "attackComplexity": "LOW", + "privilegesRequired": "LOW", + "userInteraction": "NONE", + "scope": "UNCHANGED", + "confidentialityImpact": "HIGH", + "integrityImpact": "HIGH", + "availabilityImpact": "HIGH", + "baseScore": 7.8, + "baseSeverity": "HIGH" + }, + "exploitabilityScore": 1.8, + "impactScore": 5.9 + } + ] + }, + "cisaExploitAdd": "2024-03-25", + "cisaActionDue": "2024-04-15", + "cisaRequiredAction": "Apply mitigations per vendor instructions or discontinue use of the product.", + "cisaVulnerabilityName": "Linux Kernel Netfilter Use-After-Free Vulnerability" + } + } + ] +}"#; + +/// Single Windows CISA KEV vulnerability fixture (CVE-2024-21338: Windows Kernel EoP). +pub const FIXTURE_WINDOWS_KEV_CVE_JSON: &str = r#"{ + "resultsPerPage": 1, + "startIndex": 0, + "totalResults": 1, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2024-21338", + "sourceIdentifier": "secure@microsoft.com", + "published": "2024-02-13T18:15:00.000", + "lastModified": "2024-02-29T10:00:00.000", + "vulnStatus": "Analyzed", + "descriptions": [ + { + "lang": "en", + "value": "Windows Kernel Elevation of Privilege Vulnerability allowing an attacker with local access to gain SYSTEM privileges." + } + ], + "metrics": { + "cvssMetricV31": [ + { + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": { + "version": "3.1", + "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", + "attackVector": "LOCAL", + "attackComplexity": "LOW", + "privilegesRequired": "LOW", + "userInteraction": "NONE", + "scope": "UNCHANGED", + "confidentialityImpact": "HIGH", + "integrityImpact": "HIGH", + "availabilityImpact": "HIGH", + "baseScore": 7.8, + "baseSeverity": "HIGH" + }, + "exploitabilityScore": 1.8, + "impactScore": 5.9 + } + ] + }, + "cisaExploitAdd": "2024-02-29", + "cisaActionDue": "2024-03-21", + "cisaRequiredAction": "Apply updates per vendor instructions.", + "cisaVulnerabilityName": "Microsoft Windows Kernel Privilege Escalation Vulnerability" + } + } + ] +}"#; + +/// Single Non-KEV High-Severity vulnerability fixture (CVE-2024-9999, CVSS 9.8 Critical). +pub const FIXTURE_NON_KEV_CRITICAL_CVE_JSON: &str = r#"{ + "resultsPerPage": 1, + "startIndex": 0, + "totalResults": 1, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2024-9999", + "sourceIdentifier": "cve@mitre.org", + "published": "2024-05-01T10:00:00.000", + "lastModified": "2024-05-02T10:00:00.000", + "vulnStatus": "Analyzed", + "descriptions": [ + { + "lang": "en", + "value": "Unauthenticated remote memory corruption flaw." + } + ], + "metrics": { + "cvssMetricV31": [ + { + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": { + "version": "3.1", + "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", + "attackVector": "NETWORK", + "attackComplexity": "LOW", + "privilegesRequired": "NONE", + "userInteraction": "NONE", + "scope": "UNCHANGED", + "confidentialityImpact": "HIGH", + "integrityImpact": "HIGH", + "availabilityImpact": "HIGH", + "baseScore": 9.8, + "baseSeverity": "CRITICAL" + }, + "exploitabilityScore": 3.9, + "impactScore": 5.9 + } + ] + } + } + } + ] +}"#; + +/// Multi-CVE fixture containing 5 entries designed for KEV-first prioritization and CVSS sorting tests: +/// 1. CVE-2024-1086: KEV = true, CVSS = 7.8 +/// 2. CVE-2024-9999: KEV = false, CVSS = 9.8 (High CVSS but non-KEV) +/// 3. CVE-2023-4567: KEV = true, CVSS = 5.3 (Lower CVSS but KEV) +/// 4. CVE-2022-1234: KEV = false, CVSS = 4.3 (Low CVSS non-KEV) +/// 5. CVE-2021-0001: KEV = false, CVSS = None (Missing metrics) +pub const FIXTURE_MULTI_CVE_RANKING_JSON: &str = r#"{ + "resultsPerPage": 5, + "startIndex": 0, + "totalResults": 5, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2024-9999", + "descriptions": [{"lang": "en", "value": "Critical remote code execution without KEV"}], + "metrics": { + "cvssMetricV31": [{ + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": {"version": "3.1", "baseScore": 9.8, "baseSeverity": "CRITICAL"} + }] + } + } + }, + { + "cve": { + "id": "CVE-2024-1086", + "descriptions": [{"lang": "en", "value": "Linux netfilter local root"}], + "metrics": { + "cvssMetricV31": [{ + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": {"version": "3.1", "baseScore": 7.8, "baseSeverity": "HIGH"} + }] + }, + "cisaExploitAdd": "2024-03-25", + "cisaActionDue": "2024-04-15", + "cisaRequiredAction": "Apply updates.", + "cisaVulnerabilityName": "Linux Kernel Netfilter Privilege Escalation" + } + }, + { + "cve": { + "id": "CVE-2023-4567", + "descriptions": [{"lang": "en", "value": "Medium severity KEV vulnerability"}], + "metrics": { + "cvssMetricV31": [{ + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": {"version": "3.1", "baseScore": 5.3, "baseSeverity": "MEDIUM"} + }] + }, + "cisaExploitAdd": "2023-10-10", + "cisaActionDue": "2023-11-01", + "cisaRequiredAction": "Patch immediately.", + "cisaVulnerabilityName": "Older Active Exploit" + } + }, + { + "cve": { + "id": "CVE-2022-1234", + "descriptions": [{"lang": "en", "value": "Low severity non-KEV issue"}], + "metrics": { + "cvssMetricV31": [{ + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": {"version": "3.1", "baseScore": 4.3, "baseSeverity": "MEDIUM"} + }] + } + } + }, + { + "cve": { + "id": "CVE-2021-0001", + "descriptions": [{"lang": "en", "value": "Unscored informational finding"}], + "metrics": {} + } + } + ] +}"#; + +/// Fixture containing CISA KEV vulnerability with partial optional fields (cisaActionDue omitted). +pub const FIXTURE_PARTIAL_KEV_JSON: &str = r#"{ + "resultsPerPage": 1, + "startIndex": 0, + "totalResults": 1, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2024-02-29T12:00:00.000", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2024-21338", + "sourceIdentifier": "secure@microsoft.com", + "published": "2024-02-13T18:15:58.200", + "lastModified": "2024-02-29T21:15:47.300", + "vulnStatus": "Modified", + "cisaExploitAdd": "2024-02-29", + "descriptions": [ + { + "lang": "en", + "value": "Windows Kernel Elevation of Privilege Vulnerability (appid.sys AppLocker driver previously exploited in the wild as a zero-day)." + } + ], + "metrics": { + "cvssMetricV31": [ + { + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": { + "version": "3.1", + "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", + "baseScore": 7.8, + "baseSeverity": "HIGH" + } + } + ] + } + } + } + ] +}"#; + +/// Fixture containing both CVSS v3.1 Primary and CVSS v2.0 Secondary metrics. +pub const FIXTURE_MULTI_METRIC_JSON: &str = r#"{ + "resultsPerPage": 1, + "startIndex": 0, + "totalResults": 1, + "format": "NVD_CVE", + "version": "2.0", + "timestamp": "2023-08-01T12:00:00.000", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2023-38606", + "sourceIdentifier": "product-security@apple.com", + "published": "2023-07-24T21:15:10.500", + "lastModified": "2023-08-01T15:15:00.000", + "vulnStatus": "Analyzed", + "cisaExploitAdd": "2023-07-25", + "cisaActionDue": "2023-08-15", + "cisaRequiredAction": "Apply mitigations per vendor instructions.", + "descriptions": [ + { + "lang": "en", + "value": "An app may be able to modify sensitive kernel state. Apple is aware of a report that this issue may have been actively exploited." + } + ], + "metrics": { + "cvssMetricV31": [ + { + "source": "nvd@nist.gov", + "type": "Primary", + "cvssData": { + "version": "3.1", + "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", + "baseScore": 7.8, + "baseSeverity": "HIGH" + } + } + ], + "cvssMetricV2": [ + { + "source": "nvd@nist.gov", + "type": "Secondary", + "cvssData": { + "version": "2.0", + "vectorString": "AV:L/AC:M/Au:N/C:C/I:C/A:C", + "baseScore": 6.9 + } + } + ] + } + } + } + ] +}"#; + +/// NVD API 429 Rate Limit error response body. +pub const FIXTURE_RATE_LIMIT_429_BODY: &str = r#"{ + "message": "Request forbidden by administrative rules: Rate limit exceeded" +}"#; + +/// Malformed JSON payload to test fail-closed deserialization error handling. +pub const FIXTURE_MALFORMED_JSON: &str = + r#"{"resultsPerPage": 1, "vulnerabilities": [{"cve": {"id": "CVE-2024"#; + +// ============================================================================= +// 2. Ephemeral In-Memory Mock NVD Server (`MockNvdServer`) +// ============================================================================= + +pub trait IntoStatusCode { + fn to_code(self) -> u16; +} + +impl IntoStatusCode for u16 { + fn to_code(self) -> u16 { + self + } +} + +impl IntoStatusCode for reqwest::StatusCode { + fn to_code(self) -> u16 { + self.as_u16() + } +} + +/// Lightweight, in-process HTTP mock server running on an ephemeral OS-assigned port. +pub struct MockNvdServer { + pub addr: SocketAddr, + pub endpoint_url: String, + shutdown_tx: Option>, + received_headers: Arc>>, + request_count: Arc>, +} + +impl MockNvdServer { + /// Launches an ephemeral mock server returning 200 OK with the given JSON fixture. + pub async fn start(fixture_json: &'static str) -> Self { + Self::start_with_config(fixture_json, 200, 0).await + } + + /// Launches an ephemeral mock server returning a custom HTTP status code and body. + pub async fn start_with_status(status: S, body: &'static str) -> Self { + Self::start_with_config(body, status.to_code(), 0).await + } + + /// Launches an ephemeral mock server introducing an artificial delay to test timeouts. + pub async fn start_with_delay(fixture_json: &'static str, delay_ms: u64) -> Self { + Self::start_with_config(fixture_json, 200, delay_ms).await + } + + async fn start_with_config(body: &'static str, status_code: u16, delay_ms: u64) -> Self { + let received_headers = Arc::new(Mutex::new(Vec::new())); + let request_count = Arc::new(Mutex::new(0)); + + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("Failed to bind ephemeral TCP port on 127.0.0.1"); + let addr = listener.local_addr().expect("Failed to get local address"); + let endpoint_url = format!("http://{}/rest/json/cves/2.0", addr); + + let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>(); + + let headers_clone = Arc::clone(&received_headers); + let count_clone = Arc::clone(&request_count); + let body_str = body.to_string(); + + tokio::spawn(async move { + loop { + tokio::select! { + _ = &mut shutdown_rx => { + break; + } + accept_res = listener.accept() => { + match accept_res { + Ok((mut stream, _)) => { + let h_clone = Arc::clone(&headers_clone); + let c_clone = Arc::clone(&count_clone); + let b_clone = body_str.clone(); + + tokio::spawn(async move { + let mut buf = [0u8; 4096]; + let mut received = Vec::new(); + + // Read HTTP request until headers are complete (\r\n\r\n) or connection closes + while let Ok(n) = stream.read(&mut buf).await { + if n == 0 { + break; + } + received.extend_from_slice(&buf[..n]); + if received.windows(4).any(|w| w == b"\r\n\r\n") { + break; + } + } + + // Parse request headers + if !received.is_empty() { + *c_clone.lock().unwrap() += 1; + let req_str = String::from_utf8_lossy(&received); + for line in req_str.lines() { + if let Some((k, v)) = line.split_once(':') { + h_clone.lock().unwrap().push(( + k.trim().to_string(), + v.trim().to_string(), + )); + } + } + } + + if delay_ms > 0 { + tokio::time::sleep(Duration::from_millis(delay_ms)).await; + } + + let reason = match status_code { + 200 => "OK", + 400 => "Bad Request", + 403 => "Forbidden", + 404 => "Not Found", + 429 => "Too Many Requests", + 500 => "Internal Server Error", + 503 => "Service Unavailable", + _ => "Response", + }; + + let response = format!( + "HTTP/1.1 {} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + status_code, reason, b_clone.len(), b_clone + ); + + let _ = stream.write_all(response.as_bytes()).await; + let _ = stream.flush().await; + }); + } + Err(_) => { + break; + } + } + } + } + } + }); + + Self { + addr, + endpoint_url, + shutdown_tx: Some(shutdown_tx), + received_headers, + request_count, + } + } + + /// Returns the last received `apiKey` header value, if any was transmitted. + pub fn last_api_key(&self) -> Option { + self.received_headers + .lock() + .unwrap() + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("apiKey")) + .map(|(_, v)| v.clone()) + } + + /// Checks if a specific header was sent by the client. + pub fn has_header(&self, header_name: &str) -> bool { + self.received_headers + .lock() + .unwrap() + .iter() + .any(|(k, _)| k.eq_ignore_ascii_case(header_name)) + } + + /// Returns the total number of HTTP requests received by this mock server instance. + pub fn total_requests(&self) -> usize { + *self.request_count.lock().unwrap() + } +} + +impl Drop for MockNvdServer { + fn drop(&mut self) { + if let Some(tx) = self.shutdown_tx.take() { + let _ = tx.send(()); + } + } +} + +// ============================================================================= +// 3. Test Fixture & Verification Helper Utilities +// ============================================================================= + +/// Generates a synthetic but structurally authentic `HostKernelInfo` for testing. +pub fn sample_host_kernel(os: OsFamily) -> HostKernelInfo { + match os { + OsFamily::Linux => HostKernelInfo { + os_family: OsFamily::Linux, + kernel_release: "6.8.0-40-generic".to_string(), + os_version: "Ubuntu 24.04 LTS".to_string(), + cpe23: "cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*".to_string(), + architecture: "x86_64".to_string(), + }, + OsFamily::Windows => HostKernelInfo { + os_family: OsFamily::Windows, + kernel_release: "10.0.26100".to_string(), + os_version: "Windows 11 Pro 24H2".to_string(), + cpe23: "cpe:2.3:o:microsoft:windows_11:*:*:*:*:*:*:*:*".to_string(), + architecture: "x86_64".to_string(), + }, + OsFamily::MacOS => HostKernelInfo { + os_family: OsFamily::MacOS, + kernel_release: "23.5.0".to_string(), + os_version: "macOS 14.5".to_string(), + cpe23: "cpe:2.3:o:apple:macos:14.5:*:*:*:*:*:*:*".to_string(), + architecture: "aarch64".to_string(), + }, + OsFamily::Unknown(ref name) => HostKernelInfo { + os_family: os.clone(), + kernel_release: "0.0.0".to_string(), + os_version: format!("Generic {}", name), + cpe23: "cpe:2.3:o:unknown:unknown:0.0.0:*:*:*:*:*:*:*".to_string(), + architecture: "unknown".to_string(), + }, + } +} + +/// Creates default `ScanOptions` configured for test execution against a custom endpoint. +pub fn test_scan_options( + cpe: Option<&str>, + min_cvss: Option, + kev_only: bool, + api_key: Option<&str>, +) -> ScanOptions { + ScanOptions { + cpe: cpe.map(|s| s.to_string()), + min_cvss_score: min_cvss, + kev_only, + api_key: api_key.map(|s| s.to_string()), + timeout_secs: 5, + } +} + +/// Asserts that vulnerabilities are sorted strictly according to the KillSwitch specification: +/// 1. All CISA KEV entries (`is_cisa_kev == true`) appear before any non-KEV entry. +/// 2. Within the KEV subset, CVSS scores are monotonically non-increasing. +/// 3. Within the non-KEV subset, CVSS scores are monotonically non-increasing. +pub fn assert_vulnerability_ranking(vulns: &[KernelVulnerability]) { + let mut seen_non_kev = false; + let mut last_kev_score: Option = None; + let mut last_non_kev_score: Option = None; + + for v in vulns { + if v.is_cisa_kev { + assert!( + !seen_non_kev, + "Ranking invariant violated: KEV entry '{}' appeared after non-KEV entries", + v.cve_id + ); + if let (Some(prev), Some(curr)) = (last_kev_score, v.cvss_v31_score) { + assert!( + prev >= curr, + "KEV CVSS descending order violated: {} had score {} but previous was {}", + v.cve_id, + curr, + prev + ); + } + last_kev_score = v.cvss_v31_score; + } else { + seen_non_kev = true; + if let (Some(prev), Some(curr)) = (last_non_kev_score, v.cvss_v31_score) { + assert!( + prev >= curr, + "Non-KEV CVSS descending order violated: {} had score {} but previous was {}", + v.cve_id, + curr, + prev + ); + } + last_non_kev_score = v.cvss_v31_score; + } + } +} + +/// Verifies that a generated string matches standard CPE 2.3 syntax. +pub fn assert_valid_cpe23(cpe: &str) { + assert!( + cpe.starts_with("cpe:2.3:o:"), + "CPE 2.3 must start with 'cpe:2.3:o:': got '{}'", + cpe + ); + let parts: Vec<&str> = cpe.split(':').collect(); + assert_eq!( + parts.len(), + 13, + "CPE 2.3 formatted string must have exactly 13 colon-separated fields: got {} in '{}'", + parts.len(), + cpe + ); +} + +/// Fast non-panicking connectivity probe to verify if NIST NVD is reachable. +pub async fn is_live_nvd_reachable() -> bool { + let client = reqwest::Client::builder() + .timeout(Duration::from_millis(2000)) + .build(); + + match client { + Ok(c) => { + match c + .get("https://services.nvd.nist.gov/rest/json/cves/2.0?resultsPerPage=1") + .send() + .await + { + Ok(resp) => resp.status().is_success() || resp.status().as_u16() == 429, + Err(_) => false, + } + } + Err(_) => false, + } +} diff --git a/crates/killswitch-kernel-patcher/tests/cpe_tests.rs b/crates/killswitch-kernel-patcher/tests/cpe_tests.rs new file mode 100644 index 0000000..d8f48f5 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/cpe_tests.rs @@ -0,0 +1,178 @@ +//! Dedicated CPE 2.3 formatting, mapping, and escaping test suite. + +mod common; +use common::*; +use killswitch_kernel_patcher::cpe::{ + canonicalize_linux_kernel_version, canonicalize_macos_version, canonicalize_windows_cpe, + escape_cpe_attribute, split_unescaped_colons, Cpe23, CpePart, +}; +use killswitch_kernel_patcher::discovery::{ + parse_linux_kernel_info, parse_macos_kernel_info, parse_windows_kernel_info, +}; +use killswitch_kernel_patcher::{HostKernelInfo, OsFamily}; + +#[test] +fn test_cpe_linux_standard_kernel() { + let info = HostKernelInfo { + os_family: OsFamily::Linux, + kernel_release: "6.8.0-40-generic".to_string(), + os_version: "Ubuntu 24.04 LTS".to_string(), + cpe23: "cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*".to_string(), + architecture: "x86_64".to_string(), + }; + let cpe = info.to_cpe23(); + assert_valid_cpe23(&cpe); + assert!(cpe.starts_with("cpe:2.3:o:linux:linux_kernel:6.8.0")); +} + +#[test] +fn test_cpe_linux_version_canonicalization() { + assert_eq!( + canonicalize_linux_kernel_version("6.8.0-40-generic"), + "6.8.0" + ); + assert_eq!( + canonicalize_linux_kernel_version("5.15.0-89-generic"), + "5.15.0" + ); + assert_eq!(canonicalize_linux_kernel_version("6.6.137+"), "6.6.137"); + assert_eq!(canonicalize_linux_kernel_version("5.4"), "5.4"); +} + +#[test] +fn test_cpe_windows_11_pro() { + let info = HostKernelInfo { + os_family: OsFamily::Windows, + kernel_release: "10.0.26100".to_string(), + os_version: "Windows 11 Pro 24H2".to_string(), + cpe23: "cpe:2.3:o:microsoft:windows_11:24h2:*:*:*:*:*:*:*".to_string(), + architecture: "x86_64".to_string(), + }; + let cpe = info.to_cpe23(); + assert_valid_cpe23(&cpe); + assert!(cpe.starts_with("cpe:2.3:o:microsoft:windows_11:")); +} + +#[test] +fn test_cpe_windows_server_2022() { + let (product, version) = canonicalize_windows_cpe(20348, true, None); + assert_eq!(product, "windows_server_2022"); + assert_eq!(version, "*"); + + let info = parse_windows_kernel_info( + 10, + 0, + 20348, + Some(1607), + Some("Windows Server 2022 Datacenter"), + Some("21H2"), + "x86_64", + ); + assert_valid_cpe23(&info.cpe23); + assert!(info.cpe23.contains("windows_server_2022")); +} + +#[test] +fn test_cpe_macos_sonoma() { + let info = HostKernelInfo { + os_family: OsFamily::MacOS, + kernel_release: "23.5.0".to_string(), + os_version: "macOS 14.5".to_string(), + cpe23: "cpe:2.3:o:apple:macos:14.5:*:*:*:*:*:*:*".to_string(), + architecture: "aarch64".to_string(), + }; + let cpe = info.to_cpe23(); + assert_valid_cpe23(&cpe); + assert!(cpe.starts_with("cpe:2.3:o:apple:macos:14.5")); +} + +#[test] +fn test_cpe_macos_canonicalize_version() { + assert_eq!(canonicalize_macos_version("14.4.1 (a)"), "14.4.1"); + assert_eq!(canonicalize_macos_version("14.5"), "14.5"); + assert_eq!(canonicalize_macos_version("13.6.3"), "13.6.3"); +} + +#[test] +fn test_cpe_colon_escaping_invariant() { + let escaped = escape_cpe_attribute("6.8.0:rc1"); + assert_eq!(escaped, r"6.8.0\:rc1"); + + let cpe = Cpe23::new_os("linux", "linux_kernel", &escaped); + let formatted = cpe.to_formatted_string(); + + let parts = split_unescaped_colons(&formatted); + assert_eq!( + parts.len(), + 13, + "Delimiter colons must remain 12 (13 parts)" + ); + assert_eq!(parts[0], "cpe"); + assert_eq!(parts[1], "2.3"); + assert_eq!(parts[2], "o"); + assert_eq!(parts[3], "linux"); + assert_eq!(parts[4], "linux_kernel"); + assert_eq!(parts[5], r"6.8.0\:rc1"); +} + +#[test] +fn test_cpe_whitespace_and_special_char_escaping() { + assert_eq!(escape_cpe_attribute("Windows 11 Pro"), "windows_11_pro"); + assert_eq!(escape_cpe_attribute(""), "*"); + assert_eq!(escape_cpe_attribute(" "), "*"); + assert_eq!(escape_cpe_attribute("*"), "*"); + assert_eq!(escape_cpe_attribute("-"), "-"); +} + +#[test] +fn test_cpe_structural_token_count_13_fields() { + let cpe = Cpe23::new_os("vendor_x", "product_y", "1.0.0"); + let formatted = cpe.to_formatted_string(); + assert_valid_cpe23(&formatted); + + let parts = split_unescaped_colons(&formatted); + assert_eq!(parts.len(), 13); + assert_eq!(parts[0], "cpe"); + assert_eq!(parts[1], "2.3"); + assert_eq!(parts[2], "o"); + assert_eq!(parts[3], "vendor_x"); + assert_eq!(parts[4], "product_y"); + assert_eq!(parts[5], "1.0.0"); + for part in &parts[6..13] { + assert_eq!(part.as_str(), "*"); + } +} + +#[test] +fn test_cpe_part_representations() { + assert_eq!(CpePart::Application.as_str(), "a"); + assert_eq!(CpePart::OperatingSystem.as_str(), "o"); + assert_eq!(CpePart::Hardware.as_str(), "h"); +} + +#[test] +fn test_parse_linux_kernel_info_pure() { + let info = parse_linux_kernel_info( + "6.8.0-45-generic", + Some("ID=ubuntu\nVERSION_ID=\"24.04\"\nPRETTY_NAME=\"Ubuntu 24.04 LTS\"\n"), + "x86_64", + ); + assert_eq!(info.os_family, OsFamily::Linux); + assert_eq!(info.kernel_release, "6.8.0-45-generic"); + assert_eq!(info.os_version, "24.04"); + assert_eq!( + info.cpe23, + "cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*" + ); + assert_eq!(info.architecture, "x86_64"); +} + +#[test] +fn test_parse_macos_kernel_info_pure() { + let info = parse_macos_kernel_info(Some("14.5"), "23.5.0", "aarch64"); + assert_eq!(info.os_family, OsFamily::MacOS); + assert_eq!(info.kernel_release, "23.5.0"); + assert_eq!(info.os_version, "14.5"); + assert_eq!(info.cpe23, "cpe:2.3:o:apple:macos:14.5:*:*:*:*:*:*:*"); + assert_eq!(info.architecture, "aarch64"); +} diff --git a/crates/killswitch-kernel-patcher/tests/discovery_tests.rs b/crates/killswitch-kernel-patcher/tests/discovery_tests.rs new file mode 100644 index 0000000..ee374c7 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/discovery_tests.rs @@ -0,0 +1,149 @@ +use killswitch_kernel_patcher::discovery::*; +use killswitch_kernel_patcher::types::*; + +#[test] +fn test_synthetic_linux_discovery() { + let os_release_mock = r#" +NAME="Ubuntu" +VERSION="22.04.4 LTS (Jammy Jellyfish)" +ID=ubuntu +ID_LIKE=debian +PRETTY_NAME="Ubuntu 22.04.4 LTS" +VERSION_ID="22.04" +HOME_URL="https://www.ubuntu.com/" +"#; + + let info = parse_linux_kernel_info("6.8.0-49-generic", Some(os_release_mock), "x86_64"); + assert_eq!(info.os_family, OsFamily::Linux); + assert_eq!(info.kernel_release, "6.8.0-49-generic"); + assert_eq!(info.os_version, "22.04"); + assert_eq!( + info.cpe23, + "cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*" + ); + assert_eq!(info.architecture, "x86_64"); + assert!(info.os_family.is_linux()); + assert!(!info.os_family.is_windows()); + assert!(!info.os_family.is_macos()); +} + +#[test] +fn test_synthetic_windows_11_discovery() { + let info = parse_windows_kernel_info( + 10, + 0, + 22631, + Some(3880), + Some("Windows 11 Enterprise"), + Some("23H2"), + "x86_64", + ); + assert_eq!(info.os_family, OsFamily::Windows); + assert_eq!(info.kernel_release, "10.0.22631.3880"); + assert!(info.os_version.contains("Windows 11 Enterprise")); + assert!(info.os_version.contains("23H2")); + assert_eq!( + info.cpe23, + "cpe:2.3:o:microsoft:windows_11:23h2:*:*:*:*:*:*:*" + ); + assert_eq!(info.architecture, "x86_64"); + assert!(info.os_family.is_windows()); +} + +#[test] +fn test_synthetic_windows_server_discovery() { + let info = parse_windows_kernel_info( + 10, + 0, + 20348, + Some(1200), + Some("Windows Server 2022 Datacenter"), + None, + "x86_64", + ); + assert_eq!(info.os_family, OsFamily::Windows); + assert_eq!(info.kernel_release, "10.0.20348.1200"); + assert!(info.os_version.contains("Windows Server 2022 Datacenter")); + assert_eq!( + info.cpe23, + "cpe:2.3:o:microsoft:windows_server_2022:*:*:*:*:*:*:*:*" + ); + assert_eq!(info.architecture, "x86_64"); +} + +#[test] +fn test_synthetic_macos_discovery() { + let info = parse_macos_kernel_info(Some("14.4.1"), "23.4.0", "aarch64"); + assert_eq!(info.os_family, OsFamily::MacOS); + assert_eq!(info.kernel_release, "23.4.0"); + assert_eq!(info.os_version, "14.4.1"); + assert_eq!(info.cpe23, "cpe:2.3:o:apple:macos:14.4.1:*:*:*:*:*:*:*"); + assert_eq!(info.architecture, "aarch64"); + assert!(info.os_family.is_macos()); +} + +#[test] +fn test_parse_os_release_variations() { + // Arch Linux (no VERSION_ID) + let arch_content = r#" +NAME="Arch Linux" +PRETTY_NAME="Arch Linux" +ID=arch +BUILD_ID=rolling +"#; + let arch_info = linux::parse_os_release_content(arch_content); + assert_eq!(arch_info.id, "arch"); + assert_eq!(arch_info.version_id, ""); + assert_eq!(arch_info.pretty_name, "Arch Linux"); + + // Fedora + let fedora_content = r#" +NAME="Fedora Linux" +VERSION="39 (Workstation Edition)" +ID=fedora +VERSION_ID=39 +PRETTY_NAME="Fedora Linux 39 (Workstation Edition)" +ID_LIKE="rhel fedora" +"#; + let fedora_info = linux::parse_os_release_content(fedora_content); + assert_eq!(fedora_info.id, "fedora"); + assert_eq!(fedora_info.version_id, "39"); + assert_eq!(fedora_info.id_like, vec!["rhel", "fedora"]); +} + +#[test] +fn test_detect_architecture() { + let arch = detect_architecture(); + assert_eq!(arch, std::env::consts::ARCH); +} + +#[test] +fn test_live_host_kernel_detection() { + let result = HostKernelInfo::detect_host_kernel(); + assert!( + result.is_ok(), + "detect_host_kernel() must succeed on host platform" + ); + let info = result.unwrap(); + + #[cfg(target_os = "windows")] + assert_eq!(info.os_family, OsFamily::Windows); + #[cfg(target_os = "linux")] + assert_eq!(info.os_family, OsFamily::Linux); + #[cfg(target_os = "macos")] + assert_eq!(info.os_family, OsFamily::MacOS); + + assert!( + !info.kernel_release.is_empty(), + "kernel_release must not be empty" + ); + assert!( + !info.architecture.is_empty(), + "architecture must not be empty" + ); + assert!( + info.cpe23.starts_with("cpe:2.3:o:"), + "CPE must start with 'cpe:2.3:o:'" + ); + assert_eq!(info.to_cpe23(), info.cpe23); +} diff --git a/crates/killswitch-kernel-patcher/tests/live_nvd_integration_tests.rs b/crates/killswitch-kernel-patcher/tests/live_nvd_integration_tests.rs new file mode 100644 index 0000000..c75068b --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/live_nvd_integration_tests.rs @@ -0,0 +1,82 @@ +//! Live NVD API 2.0 network integration test suite. +//! Connects to live NIST REST API with network reachability checks, rate limit tolerance, +//! and secret hygiene enforcement (reading NVD_API_KEY strictly from runtime environment). + +mod common; +use common::*; +use killswitch_kernel_patcher::{KernelPatcher, PatcherError}; + +#[tokio::test] +async fn test_live_nvd_reachability_probe() { + let reachable = is_live_nvd_reachable().await; + println!("NIST NVD live reachability status: {}", reachable); +} + +#[tokio::test] +async fn test_live_nvd_api_query_with_or_without_key() { + if !is_live_nvd_reachable().await { + println!("Live NVD endpoint unreachable or rate limited; skipping live network test"); + return; + } + + let patcher = KernelPatcher::new(); + + // Mandatory Secret Hygiene: Read strictly from runtime environment variable + let api_key = std::env::var("NVD_API_KEY").ok(); + + let query_cpe = "cpe:2.3:o:linux:linux_kernel:6.1.0:*:*:*:*:*:*:*"; + let options = test_scan_options(Some(query_cpe), None, false, api_key.as_deref()); + + match patcher.scan_kernel_vulnerabilities(&options).await { + Ok(vulns) => { + println!( + "Live NVD 2.0 query returned {} vulnerabilities", + vulns.len() + ); + if !vulns.is_empty() { + assert_vulnerability_ranking(&vulns); + } + } + Err(PatcherError::RateLimited) => { + println!("NVD returned 429 Too Many Requests; tolerated gracefully"); + } + Err(PatcherError::Network(e)) => { + println!( + "Network transport error contacting NIST: {}; tolerated gracefully", + e + ); + } + Err(other) => { + panic!("Unexpected error querying live NVD API: {:?}", other); + } + } +} + +#[tokio::test] +async fn test_live_nvd_ranking_validation() { + if !is_live_nvd_reachable().await { + println!("Live NVD endpoint unreachable; skipping ranking validation"); + return; + } + + let patcher = KernelPatcher::new(); + let api_key = std::env::var("NVD_API_KEY").ok(); + + // Scan a known older kernel to get a rich set of CVEs + let query_cpe = "cpe:2.3:o:linux:linux_kernel:5.10.0:*:*:*:*:*:*:*"; + let options = test_scan_options(Some(query_cpe), None, false, api_key.as_deref()); + + match patcher.scan_kernel_vulnerabilities(&options).await { + Ok(vulns) => { + if !vulns.is_empty() { + assert_vulnerability_ranking(&vulns); + } + } + Err(PatcherError::RateLimited) | Err(PatcherError::Network(_)) => { + // Tolerated gracefully in automated runs + } + Err(e) => { + panic!("Unexpected error in live scan: {:?}", e); + } + } +} diff --git a/crates/killswitch-kernel-patcher/tests/nvd_parsing_tests.rs b/crates/killswitch-kernel-patcher/tests/nvd_parsing_tests.rs new file mode 100644 index 0000000..43cfac2 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/nvd_parsing_tests.rs @@ -0,0 +1,167 @@ +//! Dedicated NVD API 2.0 JSON parsing, metric extraction, and KEV prioritization test suite. + +mod common; +use common::*; +use killswitch_kernel_patcher::{KernelPatcher, PatcherError}; + +#[tokio::test] +async fn test_nvd_parsing_single_kev_fields() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert_eq!(v.cve_id, "CVE-2024-1086"); + assert!(v.is_cisa_kev); + assert_eq!(v.cvss_v31_score, Some(7.8)); + assert_eq!(v.cvss_v31_severity.as_deref(), Some("HIGH")); + assert_eq!(v.cisa_exploit_add.as_deref(), Some("2024-03-25")); + assert_eq!(v.cisa_action_due.as_deref(), Some("2024-04-15")); + assert!(v.cisa_required_action.is_some()); + assert!(v.cisa_vulnerability_name.is_some()); + assert!(v.description.contains("netfilter")); +} + +#[tokio::test] +async fn test_nvd_parsing_windows_kev_fields() { + let server = MockNvdServer::start(FIXTURE_WINDOWS_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert_eq!(v.cve_id, "CVE-2024-21338"); + assert!(v.is_cisa_kev); + assert_eq!(v.cvss_v31_score, Some(7.8)); + assert_eq!(v.cisa_exploit_add.as_deref(), Some("2024-02-29")); + assert!(v + .description + .contains("Windows Kernel Elevation of Privilege")); +} + +#[tokio::test] +async fn test_nvd_parsing_non_kev_critical() { + let server = MockNvdServer::start(FIXTURE_NON_KEV_CRITICAL_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert_eq!(v.cve_id, "CVE-2024-9999"); + assert!(!v.is_cisa_kev); + assert_eq!(v.cvss_v31_score, Some(9.8)); + assert_eq!(v.cvss_v31_severity.as_deref(), Some("CRITICAL")); + assert_eq!(v.cisa_exploit_add, None); +} + +#[tokio::test] +async fn test_nvd_parsing_multi_cve_sorting() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert_eq!(vulns.len(), 5); + assert_vulnerability_ranking(&vulns); + + // Explicit ordering assertion + assert_eq!(vulns[0].cve_id, "CVE-2024-1086"); + assert_eq!(vulns[1].cve_id, "CVE-2023-4567"); + assert_eq!(vulns[2].cve_id, "CVE-2024-9999"); + assert_eq!(vulns[3].cve_id, "CVE-2022-1234"); + assert_eq!(vulns[4].cve_id, "CVE-2021-0001"); +} + +#[tokio::test] +async fn test_nvd_parsing_partial_kev_fields() { + let server = MockNvdServer::start(FIXTURE_PARTIAL_KEV_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert!(v.is_cisa_kev); + assert_eq!(v.cisa_action_due, None); + assert_eq!(v.cisa_required_action, None); +} + +#[tokio::test] +async fn test_nvd_parsing_multi_metric_precedence() { + let server = MockNvdServer::start(FIXTURE_MULTI_METRIC_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert_eq!( + v.cvss_v31_score, + Some(7.8), + "Must select CVSS v3.1 score over v2.0 score" + ); +} + +#[tokio::test] +async fn test_nvd_parsing_empty_results() { + let server = MockNvdServer::start(FIXTURE_EMPTY_NVD_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Parsing failed"); + + assert!(vulns.is_empty()); +} + +#[tokio::test] +async fn test_nvd_parsing_malformed_json_fails_closed() { + let server = MockNvdServer::start(FIXTURE_MALFORMED_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!(matches!(res, Err(PatcherError::Serialization(_)))); +} + +#[tokio::test] +async fn test_nvd_parsing_rate_limit_429() { + let server = MockNvdServer::start_with_status(429, FIXTURE_RATE_LIMIT_429_BODY).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!(matches!(res, Err(PatcherError::RateLimited))); +} diff --git a/crates/killswitch-kernel-patcher/tests/patch_dry_run_tests.rs b/crates/killswitch-kernel-patcher/tests/patch_dry_run_tests.rs new file mode 100644 index 0000000..fcc7066 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/patch_dry_run_tests.rs @@ -0,0 +1,92 @@ +//! Dedicated OS kernel patch orchestration, dry-run safety, and privilege boundary test suite. + +mod common; +use killswitch_kernel_patcher::{is_elevated, KernelPatcher, PatchExecutionResult, PatcherError}; + +#[tokio::test] +async fn test_patch_dry_run_execution_structure() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + + assert!(res.dry_run); + assert!(res.success); + assert!(!res.command.is_empty()); + assert!(!res.args.is_empty()); + assert!(!res.os_subsystem.is_empty()); + assert!(res.output.contains("[DRY-RUN]")); +} + +#[tokio::test] +async fn test_patch_live_fails_closed_under_non_root() { + let patcher = KernelPatcher::new(); + if !is_elevated() { + let res = patcher.apply_os_kernel_patch(false).await; + assert!( + matches!(res, Err(PatcherError::InsufficientPrivileges)), + "Expected InsufficientPrivileges under non-elevated user, got: {:?}", + res + ); + } +} + +#[test] +fn test_patch_execution_result_json_roundtrip() { + let original = PatchExecutionResult { + dry_run: true, + command: "UsoClient.exe".to_string(), + args: vec!["StartInstall".to_string()], + success: true, + output: "[DRY-RUN] Planned execution: UsoClient.exe StartInstall".to_string(), + os_subsystem: "UsoClient".to_string(), + }; + + let json = serde_json::to_string(&original).expect("Serialization failed"); + let deserialized: PatchExecutionResult = + serde_json::from_str(&json).expect("Deserialization failed"); + + assert_eq!(original.dry_run, deserialized.dry_run); + assert_eq!(original.command, deserialized.command); + assert_eq!(original.args, deserialized.args); + assert_eq!(original.success, deserialized.success); + assert_eq!(original.output, deserialized.output); + assert_eq!(original.os_subsystem, deserialized.os_subsystem); +} + +#[tokio::test] +async fn test_patch_dry_run_never_mutates_system() { + let patcher = KernelPatcher::new(); + // In dry run mode, no privileged OS command or kernel package mutation occurs + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + assert!(res.dry_run); + assert!(res.output.contains("[DRY-RUN]")); +} + +#[tokio::test] +async fn test_patch_dry_run_platform_routing() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + + #[cfg(target_os = "windows")] + { + assert_eq!(res.os_subsystem, "UsoClient"); + assert_eq!(res.command, "UsoClient.exe"); + } + #[cfg(target_os = "linux")] + { + assert!(["canonical-livepatch", "apt-get", "dnf"].contains(&res.os_subsystem.as_str())); + } + #[cfg(target_os = "macos")] + { + assert_eq!(res.os_subsystem, "softwareupdate"); + assert_eq!(res.command, "softwareupdate"); + } +} diff --git a/crates/killswitch-kernel-patcher/tests/privilege_tests.rs b/crates/killswitch-kernel-patcher/tests/privilege_tests.rs new file mode 100644 index 0000000..1479394 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/privilege_tests.rs @@ -0,0 +1,63 @@ +use killswitch_kernel_patcher::privilege::is_elevated; + +#[test] +fn test_is_elevated_execution_safety() { + // 1. Facade delegation invariant: is_elevated() must strictly match the OS platform module output + let facade_val = is_elevated(); + + #[cfg(windows)] + { + let platform_val = + killswitch_kernel_patcher::privilege::windows::is_current_process_elevated(); + assert_eq!( + facade_val, platform_val, + "Facade is_elevated() must be identical to Win32 platform implementation" + ); + } + + #[cfg(unix)] + { + let platform_val = + killswitch_kernel_patcher::privilege::unix::is_current_process_elevated(); + assert_eq!( + facade_val, platform_val, + "Facade is_elevated() must be identical to POSIX platform implementation" + ); + } + + // 2. Sequential stability: multiple invocations must remain consistent without leaking or corrupting token handles + for _ in 0..10 { + assert_eq!( + is_elevated(), + facade_val, + "is_elevated() must remain invariant across repeated sequential invocations" + ); + } +} + +#[test] +fn test_is_elevated_thread_safety() { + let handles: Vec<_> = (0..16).map(|_| std::thread::spawn(is_elevated)).collect(); + + let mut results = Vec::new(); + for handle in handles { + results.push(handle.join().expect("thread join failed")); + } + + let first = results[0]; + for res in results { + assert_eq!( + res, first, + "Concurrent is_elevated calls must be idempotent" + ); + } +} + +#[test] +fn test_is_elevated_idempotency() { + let r1 = is_elevated(); + let r2 = is_elevated(); + let r3 = is_elevated(); + assert_eq!(r1, r2); + assert_eq!(r2, r3); +} diff --git a/crates/killswitch-kernel-patcher/tests/tier1_feature_coverage_tests.rs b/crates/killswitch-kernel-patcher/tests/tier1_feature_coverage_tests.rs new file mode 100644 index 0000000..3d2e1e7 --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/tier1_feature_coverage_tests.rs @@ -0,0 +1,664 @@ +//! Tier 1: Category-Partition Feature Coverage Test Suite for `killswitch-kernel-patcher`. +//! Covers Features F1 through F8 with >=5 tests per feature (total 40 tests). + +mod common; +use common::*; +use killswitch_kernel_patcher::cpe::{ + canonicalize_linux_kernel_version, canonicalize_macos_version, canonicalize_windows_cpe, + escape_cpe_attribute, split_unescaped_colons, Cpe23, +}; +use killswitch_kernel_patcher::{ + is_elevated, HostKernelInfo, KernelPatcher, OsFamily, PatcherError, ScanOptions, +}; + +// ============================================================================= +// Feature 1: Host Platform & Kernel Discovery (F1) +// ============================================================================= + +#[test] +fn test_tier1_f1_01_detect_current_host_returns_ok() { + let res = HostKernelInfo::detect_host_kernel(); + assert!( + res.is_ok(), + "Host kernel detection must succeed on host OS: {:?}", + res.err() + ); + let info = res.unwrap(); + assert!( + !info.kernel_release.is_empty(), + "kernel_release must not be empty" + ); + assert!( + !info.architecture.is_empty(), + "architecture must not be empty" + ); +} + +#[test] +fn test_tier1_f1_02_detect_os_family_matches_target() { + let info = HostKernelInfo::detect_host_kernel().expect("Kernel detection failed"); + #[cfg(target_os = "windows")] + assert_eq!(info.os_family, OsFamily::Windows); + #[cfg(target_os = "linux")] + assert_eq!(info.os_family, OsFamily::Linux); + #[cfg(target_os = "macos")] + assert_eq!(info.os_family, OsFamily::MacOS); +} + +#[test] +fn test_tier1_f1_03_kernel_release_semantic_format() { + let info = HostKernelInfo::detect_host_kernel().expect("Kernel detection failed"); + #[cfg(target_os = "windows")] + { + // Windows kernel release is typically major.minor.build[.ubr] + let parts: Vec<&str> = info.kernel_release.split('.').collect(); + assert!( + parts.len() >= 3, + "Windows release should have at least 3 parts: {}", + info.kernel_release + ); + for p in &parts { + assert!( + p.chars().all(|c| c.is_ascii_digit()), + "Part '{}' is not numeric", + p + ); + } + } + #[cfg(not(target_os = "windows"))] + { + assert!( + info.kernel_release.contains('.') + || info.kernel_release.chars().any(|c| c.is_ascii_digit()), + "Release string should contain version digits: {}", + info.kernel_release + ); + } +} + +#[test] +fn test_tier1_f1_04_architecture_canonical_naming() { + let info = HostKernelInfo::detect_host_kernel().expect("Kernel detection failed"); + assert!( + ["x86_64", "aarch64", "x86", "arm"].contains(&info.architecture.as_str()), + "Unexpected architecture nomenclature: {}", + info.architecture + ); +} + +#[test] +fn test_tier1_f1_05_detect_host_cpe_field_consistency() { + let info = HostKernelInfo::detect_host_kernel().expect("Kernel detection failed"); + assert_eq!(info.cpe23, info.to_cpe23()); + assert!(info.cpe23.starts_with("cpe:2.3:o:")); + assert_valid_cpe23(&info.cpe23); +} + +// ============================================================================= +// Feature 2: CPE 2.3 Formatting & Mapping (F2) +// ============================================================================= + +#[test] +fn test_tier1_f2_01_cpe_linux_kernel_canonical_format() { + let base_version = canonicalize_linux_kernel_version("6.8.0-40-generic"); + let cpe = Cpe23::new_os("linux", "linux_kernel", base_version); + let cpe_str = cpe.to_formatted_string(); + assert_eq!(cpe_str, "cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*"); +} + +#[test] +fn test_tier1_f2_02_cpe_windows_11_mapping() { + let (product, version) = canonicalize_windows_cpe(22631, false, Some("23H2")); + let cpe = Cpe23::new_os("microsoft", product, version); + let cpe_str = cpe.to_formatted_string(); + assert_eq!(cpe_str, "cpe:2.3:o:microsoft:windows_11:23h2:*:*:*:*:*:*:*"); +} + +#[test] +fn test_tier1_f2_03_cpe_macos_darwin_mapping() { + let version = canonicalize_macos_version("14.5 (23F79)"); + let cpe = Cpe23::new_os("apple", "macos", version); + let cpe_str = cpe.to_formatted_string(); + assert_eq!(cpe_str, "cpe:2.3:o:apple:macos:14.5:*:*:*:*:*:*:*"); +} + +#[test] +fn test_tier1_f2_04_cpe_field_count_11_attributes() { + let cpe = Cpe23::new_os("vendor", "product", "1.0.0"); + let formatted = cpe.to_formatted_string(); + let parts = split_unescaped_colons(&formatted); + assert_eq!( + parts.len(), + 13, + "Must have exactly prefix (2) + 11 attributes = 13 fields" + ); + assert_eq!(parts[0], "cpe"); + assert_eq!(parts[1], "2.3"); + assert_eq!(parts[2], "o"); +} + +#[test] +fn test_tier1_f2_05_cpe_special_character_escaping() { + let escaped = escape_cpe_attribute("version:6.8.0"); + assert_eq!(escaped, r"version\:6.8.0"); + let cpe = Cpe23::new_os("vendor", "product", escaped); + let formatted = cpe.to_formatted_string(); + let parts = split_unescaped_colons(&formatted); + assert_eq!( + parts.len(), + 13, + "Escaped colon must not introduce extra field" + ); +} + +// ============================================================================= +// Feature 3: Privilege Elevation Detection (F3) +// ============================================================================= + +#[test] +fn test_tier1_f3_01_is_elevated_callable_without_panic() { + let _ = is_elevated(); +} + +#[test] +fn test_tier1_f3_02_is_elevated_deterministic_repeatability() { + let initial = is_elevated(); + for _ in 0..100 { + assert_eq!( + is_elevated(), + initial, + "Privilege check must be idempotent and deterministic" + ); + } +} + +#[test] +fn test_tier1_f3_03_is_elevated_thread_safety() { + let mut handles = Vec::new(); + for _ in 0..16 { + handles.push(std::thread::spawn(is_elevated)); + } + let expected = is_elevated(); + for h in handles { + assert_eq!(h.join().unwrap(), expected); + } +} + +#[tokio::test] +async fn test_tier1_f3_04_is_elevated_tokio_task_consistency() { + let main_thread_val = is_elevated(); + let async_task_val = tokio::spawn(async { is_elevated() }) + .await + .expect("Tokio task join failed"); + + assert_eq!( + main_thread_val, async_task_val, + "is_elevated() inside tokio async task runtime must match caller thread" + ); + + #[cfg(windows)] + { + assert_eq!( + main_thread_val, + killswitch_kernel_patcher::privilege::windows::is_current_process_elevated(), + "Elevation status must match Win32 TokenElevation query" + ); + } + + #[cfg(unix)] + { + assert_eq!( + main_thread_val, + killswitch_kernel_patcher::privilege::unix::is_current_process_elevated(), + "Elevation status must match POSIX geteuid query" + ); + } +} + +#[tokio::test] +async fn test_tier1_f3_05_is_elevated_fail_closed_contract() { + let patcher = KernelPatcher::new(); + let elevated = is_elevated(); + + // Verify fail-closed linkage: non-elevated callers MUST be blocked with InsufficientPrivileges + let patch_result = patcher.apply_os_kernel_patch(false).await; + match patch_result { + Err(PatcherError::InsufficientPrivileges) => { + assert!( + !elevated, + "InsufficientPrivileges returned but is_elevated() reported true" + ); + } + other => { + assert!( + elevated, + "Expected InsufficientPrivileges for non-elevated caller, got: {:?}", + other + ); + } + } +} + +// ============================================================================= +// Feature 4: NVD API 2.0 HTTP Client & Auth (F4) +// ============================================================================= + +#[tokio::test] +async fn test_tier1_f4_01_client_constructs_with_default_options() { + let patcher = KernelPatcher::new(); + let opts = ScanOptions::default(); + assert!(opts.cpe.is_none()); + assert!(opts.min_cvss_score.is_none()); + assert!(!opts.kev_only); + assert!(opts.api_key.is_none()); + assert_eq!(opts.timeout_secs, 30); + let _ = patcher; +} + +#[tokio::test] +async fn test_tier1_f4_02_client_attaches_apikey_header_when_present() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let test_key = "secret_api_key_test_value_12345"; + let opts = test_scan_options(None, None, false, Some(test_key)); + + let _ = patcher.scan_kernel_vulnerabilities(&opts).await; + assert_eq!(server.last_api_key(), Some(test_key.to_string())); +} + +#[tokio::test] +async fn test_tier1_f4_03_client_omits_apikey_header_when_none() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let _ = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!( + !server.has_header("apiKey"), + "apiKey header should be omitted when None" + ); +} + +#[tokio::test] +async fn test_tier1_f4_04_client_encodes_cpe_query_parameter() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let cpe = "cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*"; + let opts = test_scan_options(Some(cpe), None, false, None); + + let _ = patcher.scan_kernel_vulnerabilities(&opts).await; + assert_eq!(server.total_requests(), 1); +} + +#[tokio::test] +async fn test_tier1_f4_05_client_respects_custom_timeout() { + let server = MockNvdServer::start_with_delay(FIXTURE_SINGLE_KEV_CVE_JSON, 1000).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let mut opts = test_scan_options(None, None, false, None); + opts.timeout_secs = 1; + + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + // Fast fail or successful finish within bound + assert!(res.is_ok() || matches!(res, Err(PatcherError::Network(_)))); +} + +// ============================================================================= +// Feature 5: Vulnerability JSON Parsing (F5) +// ============================================================================= + +#[tokio::test] +async fn test_tier1_f5_01_parse_standard_cve_with_cvss31() { + let server = MockNvdServer::start(FIXTURE_NON_KEV_CRITICAL_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert_eq!(v.cve_id, "CVE-2024-9999"); + assert_eq!(v.cvss_v31_score, Some(9.8)); + assert_eq!(v.cvss_v31_severity.as_deref(), Some("CRITICAL")); + assert!(!v.is_cisa_kev); +} + +#[tokio::test] +async fn test_tier1_f5_02_parse_cisa_kev_fields() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert!(v.is_cisa_kev); + assert_eq!(v.cisa_exploit_add.as_deref(), Some("2024-03-25")); + assert_eq!(v.cisa_action_due.as_deref(), Some("2024-04-15")); + assert!(v.cisa_required_action.is_some()); + assert!(v.cisa_vulnerability_name.is_some()); +} + +#[tokio::test] +async fn test_tier1_f5_03_parse_description_english() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 1); + assert!(vulns[0].description.contains("netfilter")); +} + +#[tokio::test] +async fn test_tier1_f5_04_parse_multiple_vulnerabilities_array() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 5); +} + +#[tokio::test] +async fn test_tier1_f5_05_parse_empty_vulnerabilities_list() { + let server = MockNvdServer::start(FIXTURE_EMPTY_NVD_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert!(vulns.is_empty()); +} + +// ============================================================================= +// Feature 6: KEV Prioritization & CVSS Ranking (F6) +// ============================================================================= + +#[tokio::test] +async fn test_tier1_f6_01_kev_precedes_non_kev_regardless_of_cvss() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + // Invariant: All KEV entries must appear before non-KEV entries + let first_non_kev_idx = vulns + .iter() + .position(|v| !v.is_cisa_kev) + .unwrap_or(vulns.len()); + for v in &vulns[..first_non_kev_idx] { + assert!(v.is_cisa_kev); + } + for v in &vulns[first_non_kev_idx..] { + assert!(!v.is_cisa_kev); + } +} + +#[tokio::test] +async fn test_tier1_f6_02_kev_items_sorted_by_descending_cvss() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + let kev_items: Vec<_> = vulns.iter().filter(|v| v.is_cisa_kev).collect(); + for window in kev_items.windows(2) { + if let (Some(a), Some(b)) = (window[0].cvss_v31_score, window[1].cvss_v31_score) { + assert!(a >= b, "KEV CVSS scores must be descending: {} vs {}", a, b); + } + } +} + +#[tokio::test] +async fn test_tier1_f6_03_non_kev_items_sorted_by_descending_cvss() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + let non_kev: Vec<_> = vulns.iter().filter(|v| !v.is_cisa_kev).collect(); + for window in non_kev.windows(2) { + if let (Some(a), Some(b)) = (window[0].cvss_v31_score, window[1].cvss_v31_score) { + assert!( + a >= b, + "Non-KEV CVSS scores must be descending: {} vs {}", + a, + b + ); + } + } +} + +#[tokio::test] +async fn test_tier1_f6_04_kev_only_filter_excludes_non_kev() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, true, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert!(!vulns.is_empty()); + for v in &vulns { + assert!( + v.is_cisa_kev, + "All findings must be CISA KEV entries when kev_only is true" + ); + } +} + +#[tokio::test] +async fn test_tier1_f6_05_min_cvss_threshold_filtering() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, Some(7.0), false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + for v in &vulns { + assert!(v.cvss_v31_score.unwrap_or(0.0) >= 7.0); + } +} + +// ============================================================================= +// Feature 7: Fail-Closed Patch Dispatch (F7) +// ============================================================================= + +#[tokio::test] +async fn test_tier1_f7_01_non_elevated_live_patch_fails_closed() { + let patcher = KernelPatcher::new(); + if !is_elevated() { + let res = patcher.apply_os_kernel_patch(false).await; + assert!(matches!(res, Err(PatcherError::InsufficientPrivileges))); + } +} + +#[tokio::test] +async fn test_tier1_f7_02_windows_subsystem_dispatch_routes_to_usoclient() { + #[cfg(target_os = "windows")] + { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run planning failed"); + assert_eq!(res.os_subsystem, "UsoClient"); + assert_eq!(res.command, "UsoClient.exe"); + } +} + +#[tokio::test] +async fn test_tier1_f7_03_linux_subsystem_dispatch_routes_to_package_manager() { + #[cfg(target_os = "linux")] + { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run planning failed"); + assert!(["canonical-livepatch", "apt-get", "dnf"].contains(&res.os_subsystem.as_str())); + } +} + +#[tokio::test] +async fn test_tier1_f7_04_macos_subsystem_dispatch_routes_to_softwareupdate() { + #[cfg(target_os = "macos")] + { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run planning failed"); + assert_eq!(res.os_subsystem, "softwareupdate"); + assert_eq!(res.command, "softwareupdate"); + } +} + +#[test] +fn test_tier1_f7_05_unsupported_platform_returns_error() { + // Calling an out-of-target platform discovery function on the current host + // must genuinely return PatcherError::UnsupportedPlatform from crate logic. + #[cfg(target_os = "windows")] + { + let res_linux = killswitch_kernel_patcher::discovery::linux::detect_linux_host_kernel(); + assert!( + matches!(res_linux, Err(PatcherError::UnsupportedPlatform(ref s)) if s.contains("non-Linux")), + "detect_linux_host_kernel on Windows must return UnsupportedPlatform: {:?}", + res_linux + ); + + let res_macos = killswitch_kernel_patcher::discovery::macos::detect_macos_host_kernel(); + assert!( + matches!(res_macos, Err(PatcherError::UnsupportedPlatform(ref s)) if s.contains("non-macOS")), + "detect_macos_host_kernel on Windows must return UnsupportedPlatform: {:?}", + res_macos + ); + } + + #[cfg(target_os = "linux")] + { + let res_macos = killswitch_kernel_patcher::discovery::macos::detect_macos_host_kernel(); + assert!( + matches!(res_macos, Err(PatcherError::UnsupportedPlatform(ref s)) if s.contains("non-macOS")), + "detect_macos_host_kernel on Linux must return UnsupportedPlatform: {:?}", + res_macos + ); + + let res_windows = killswitch_kernel_patcher::discovery::windows::detect_windows_kernel(); + assert!( + matches!(res_windows, Err(PatcherError::UnsupportedPlatform(ref s)) if s.contains("non-Windows")), + "detect_windows_kernel on Linux must return UnsupportedPlatform: {:?}", + res_windows + ); + } + + #[cfg(target_os = "macos")] + { + let res_windows = killswitch_kernel_patcher::discovery::windows::detect_windows_kernel(); + assert!( + matches!(res_windows, Err(PatcherError::UnsupportedPlatform(ref s)) if s.contains("non-Windows")), + "detect_windows_kernel on macOS must return UnsupportedPlatform: {:?}", + res_windows + ); + + let res_linux = killswitch_kernel_patcher::discovery::linux::detect_linux_host_kernel(); + assert!( + matches!(res_linux, Err(PatcherError::UnsupportedPlatform(ref s)) if s.contains("non-Linux")), + "detect_linux_host_kernel on macOS must return UnsupportedPlatform: {:?}", + res_linux + ); + } +} + +// ============================================================================= +// Feature 8: Safe Dry-Run Mode (F8) +// ============================================================================= + +#[tokio::test] +async fn test_tier1_f8_01_dry_run_flag_true_in_result() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + assert!(res.dry_run, "Dry run result must have dry_run == true"); +} + +#[tokio::test] +async fn test_tier1_f8_02_dry_run_does_not_mutate_system_state() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + assert!(res.success); + assert!(res.output.contains("[DRY-RUN]")); +} + +#[tokio::test] +async fn test_tier1_f8_03_dry_run_succeeds_even_when_not_elevated() { + let patcher = KernelPatcher::new(); + let res = patcher.apply_os_kernel_patch(true).await; + assert!(res.is_ok(), "Dry run must succeed regardless of elevation"); +} + +#[tokio::test] +async fn test_tier1_f8_04_dry_run_formats_exact_command_and_args() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + assert!(!res.command.is_empty()); + assert!(!res.args.is_empty()); +} + +#[tokio::test] +async fn test_tier1_f8_05_dry_run_success_flag_and_descriptive_output() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + assert!(res.success); + assert!(!res.output.is_empty()); +} diff --git a/crates/killswitch-kernel-patcher/tests/tier2_boundary_corner_tests.rs b/crates/killswitch-kernel-patcher/tests/tier2_boundary_corner_tests.rs new file mode 100644 index 0000000..1f13d4c --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/tier2_boundary_corner_tests.rs @@ -0,0 +1,764 @@ +//! Tier 2: Boundary Value Analysis & Corner Cases Test Suite for `killswitch-kernel-patcher`. +//! Covers Features F1 through F8 with >=5 edge/boundary tests per feature (total 40 tests). + +mod common; +use common::*; +use killswitch_kernel_patcher::cpe::{ + canonicalize_linux_kernel_version, escape_cpe_attribute, split_unescaped_colons, Cpe23, +}; +use killswitch_kernel_patcher::discovery::{ + parse_linux_kernel_info, parse_macos_kernel_info, parse_windows_kernel_info, +}; +use killswitch_kernel_patcher::{is_elevated, KernelPatcher, PatchExecutionResult, PatcherError}; + +// ============================================================================= +// Feature 1: Host Platform & Kernel Discovery (F1 - Tier 2) +// ============================================================================= + +#[test] +fn test_tier2_f1_01_whitespace_and_newlines_in_kernel_version() { + let raw = " 6.8.0-generic \r\n "; + let canonical = canonicalize_linux_kernel_version(raw); + assert_eq!(canonical, "6.8.0"); + + let info = parse_linux_kernel_info(raw, None, "x86_64"); + assert_eq!(info.kernel_release, "6.8.0-generic"); +} + +#[test] +fn test_tier2_f1_02_unrecognized_custom_os_family() { + let unknown_os = killswitch_kernel_patcher::OsFamily::Unknown("CustomYoctoOS".into()); + assert!(!unknown_os.is_linux()); + assert!(!unknown_os.is_windows()); + assert!(!unknown_os.is_macos()); + assert_eq!(format!("{}", unknown_os), "Unknown (CustomYoctoOS)"); +} + +#[test] +fn test_tier2_f1_03_empty_system_info_fallback_handling() { + // When raw kernel release and os-release are completely empty, + // discovery parsers must gracefully fall back to safe canonical defaults without panicking. + let linux_empty = parse_linux_kernel_info("", Some(""), ""); + assert_eq!( + linux_empty.os_version, "unknown", + "Empty os-release must fall back to 'unknown'" + ); + assert_eq!( + linux_empty.cpe23, "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", + "Empty kernel version must canonicalize to wildcard CPE" + ); + + let macos_empty = parse_macos_kernel_info(None, "", ""); + assert!( + macos_empty.cpe23.starts_with("cpe:2.3:o:apple:macos:"), + "Empty macOS version must fall back to valid apple:macos CPE" + ); + + let windows_empty = parse_windows_kernel_info(0, 0, 0, None, None, None, ""); + assert!( + windows_empty.os_version.contains("Build 0.0.0"), + "Zeroed Windows version must format safely: {}", + windows_empty.os_version + ); +} + +#[test] +fn test_tier2_f1_04_extreme_length_kernel_release() { + let long_release = "6.".to_string() + &"9".repeat(5000); + let canonical = canonicalize_linux_kernel_version(&long_release); + assert!(canonical.len() < 6000); +} + +#[test] +fn test_tier2_f1_05_non_ascii_os_release_metadata() { + let os_release_content = + "ID=french_linux\nPRETTY_NAME=\"Édition Française 2026\"\nVERSION_ID=\"1.0\"\n"; + let info = parse_linux_kernel_info("6.8.0", Some(os_release_content), "x86_64"); + assert_eq!(info.os_version, "1.0"); + assert!(!info.os_version.contains('\u{FFFD}')); +} + +// ============================================================================= +// Feature 2: CPE 2.3 Formatting & Mapping (F2 - Tier 2) +// ============================================================================= + +#[test] +fn test_tier2_f2_01_empty_cpe_version_wildcard() { + let escaped = escape_cpe_attribute(""); + assert_eq!(escaped, "*"); + let cpe = Cpe23::new_os("vendor", "product", escaped); + assert_eq!( + cpe.to_formatted_string(), + "cpe:2.3:o:vendor:product:*:*:*:*:*:*:*:*" + ); +} + +#[test] +fn test_tier2_f2_02_colon_in_version_must_be_escaped() { + let escaped = escape_cpe_attribute("6.8.0:rc1"); + assert_eq!(escaped, r"6.8.0\:rc1"); + let cpe = Cpe23::new_os("vendor", "product", escaped); + let formatted = cpe.to_formatted_string(); + let parts = split_unescaped_colons(&formatted); + assert_eq!(parts.len(), 13); +} + +#[test] +fn test_tier2_f2_03_space_in_vendor_or_product() { + let escaped_product = escape_cpe_attribute("Windows 11 Enterprise"); + assert_eq!(escaped_product, "windows_11_enterprise"); + let cpe = Cpe23::new_os("microsoft", escaped_product, "23h2"); + assert!(cpe.to_formatted_string().contains("windows_11_enterprise")); +} + +#[test] +fn test_tier2_f2_04_traversal_characters_in_cpe_attributes() { + let malicious = "../../etc/shadow"; + let escaped = escape_cpe_attribute(malicious); + // Traversal slashes are escaped per NIST IR 7695 + assert!(escaped.contains(r"\.\./\.\./") || !escaped.contains("../")); +} + +#[test] +fn test_tier2_f2_05_malformed_cpe_detection() { + let malformed = "invalid:cpe:string"; + assert!(!malformed.starts_with("cpe:2.3:o:")); + assert_ne!(malformed.split(':').count(), 13); +} + +// ============================================================================= +// Feature 3: Privilege Elevation Detection (F3 - Tier 2) +// ============================================================================= + +#[tokio::test] +async fn test_tier2_f3_01_token_query_failure_fails_closed() { + let patcher = KernelPatcher::new(); + let elevated = is_elevated(); + + // Contract: Fail-closed invariant mandates that live patch execution MUST be rejected + // with InsufficientPrivileges whenever is_elevated() evaluates to false. + let patch_res = patcher.apply_os_kernel_patch(false).await; + if !elevated { + assert!( + matches!(patch_res, Err(PatcherError::InsufficientPrivileges)), + "Non-elevated execution must fail closed with InsufficientPrivileges, got: {:?}", + patch_res + ); + } else { + assert!( + !matches!(patch_res, Err(PatcherError::InsufficientPrivileges)), + "Elevated execution must not fail with InsufficientPrivileges" + ); + } +} + +#[test] +fn test_tier2_f3_02_restricted_filtered_token_uac() { + let elevated = is_elevated(); + + #[cfg(windows)] + { + let platform_elevated = + killswitch_kernel_patcher::privilege::windows::is_current_process_elevated(); + assert_eq!( + elevated, platform_elevated, + "Elevation status under UAC token filtering must strictly match windows::is_current_process_elevated" + ); + } + + #[cfg(unix)] + { + let expected = unsafe { libc::geteuid() == 0 }; + assert_eq!( + elevated, expected, + "Elevation status must strictly match POSIX geteuid == 0 under standard/restricted user" + ); + } + + // Invariant: The elevation status must remain constant across repeated queries + // even when called from different OS threads (filtered token is process-bound) + let thread_result = std::thread::spawn(is_elevated) + .join() + .expect("Thread panicked"); + assert_eq!( + elevated, thread_result, + "Filtered token elevation status must be identical across all threads of the process" + ); +} + +#[test] +fn test_tier2_f3_03_unix_setuid_mismatch() { + // Evaluates effective credentials + let elevated = is_elevated(); + #[cfg(unix)] + { + let expected = unsafe { libc::geteuid() == 0 }; + assert_eq!(elevated, expected); + } + let _ = elevated; +} + +#[test] +fn test_tier2_f3_04_appcontainer_sandbox_restriction() { + let elevated = is_elevated(); + + #[cfg(windows)] + { + assert_eq!( + elevated, + killswitch_kernel_patcher::privilege::windows::is_current_process_elevated(), + "is_elevated() must match windows::is_current_process_elevated" + ); + + if elevated { + assert!( + std::env::var("APP_CONTAINER").is_err(), + "Process cannot be elevated while reporting APP_CONTAINER environment" + ); + } + } + + #[cfg(unix)] + { + let euid = unsafe { libc::geteuid() }; + if elevated { + assert_eq!(euid, 0, "Elevated process must have euid == 0"); + } else { + assert_ne!(euid, 0, "Non-elevated process must have non-zero euid"); + } + } +} + +#[tokio::test] +async fn test_tier2_f3_05_privilege_gate_live_vs_dry_run_contrast() { + let patcher = KernelPatcher::new(); + let elevated = is_elevated(); + + // Dry-run mode MUST succeed even in unprivileged environments + let dry_run_res = patcher.apply_os_kernel_patch(true).await; + assert!( + dry_run_res.is_ok(), + "Dry-run patch planning must always succeed regardless of elevation: {:?}", + dry_run_res.err() + ); + + // Live mode MUST strictly enforce the privilege boundary: + let live_res = patcher.apply_os_kernel_patch(false).await; + if !elevated { + assert!( + matches!(live_res, Err(PatcherError::InsufficientPrivileges)), + "Live patch execution without elevation must return InsufficientPrivileges, got: {:?}", + live_res + ); + } else { + assert!( + !matches!(live_res, Err(PatcherError::InsufficientPrivileges)), + "Live patch execution with elevation must pass the privilege check" + ); + } +} + +// ============================================================================= +// Feature 4: NVD API 2.0 HTTP Client & Auth (F4 - Tier 2) +// ============================================================================= + +#[tokio::test] +async fn test_tier2_f4_01_http_429_rate_limited_error_mapping() { + let server = MockNvdServer::start_with_status(429, FIXTURE_RATE_LIMIT_429_BODY).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!(matches!(res, Err(PatcherError::RateLimited))); +} + +#[tokio::test] +async fn test_tier2_f4_02_http_403_forbidden_invalid_api_key() { + let server = MockNvdServer::start_with_status(403, r#"{"message": "Invalid API Key"}"#).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, Some("invalid_key")); + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!(matches!(res, Err(PatcherError::NvdApiError(_)))); +} + +#[tokio::test] +async fn test_tier2_f4_03_http_503_service_unavailable() { + let server = + MockNvdServer::start_with_status(503, r#"{"message": "Service Unavailable"}"#).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!(matches!(res, Err(PatcherError::NvdApiError(_)))); +} + +#[tokio::test] +async fn test_tier2_f4_04_empty_api_key_treated_as_none() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, Some(" ")); + let _ = patcher.scan_kernel_vulnerabilities(&opts).await; + + // Blank or whitespace-only keys should not be sent + if server.has_header("apiKey") { + let key = server.last_api_key().unwrap(); + assert!(!key.trim().is_empty()); + } +} + +#[tokio::test] +async fn test_tier2_f4_05_micro_timeout_connection_drop() { + let server = MockNvdServer::start_with_delay(FIXTURE_SINGLE_KEV_CVE_JSON, 500).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let mut opts = test_scan_options(None, None, false, None); + opts.timeout_secs = 1; + + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + assert!(res.is_ok() || matches!(res, Err(PatcherError::Network(_)))); +} + +// ============================================================================= +// Feature 5: Vulnerability JSON Parsing (F5 - Tier 2) +// ============================================================================= + +#[tokio::test] +async fn test_tier2_f5_01_missing_optional_kev_fields() { + let server = MockNvdServer::start(FIXTURE_PARTIAL_KEV_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert!(v.is_cisa_kev); + assert_eq!(v.cisa_exploit_add.as_deref(), Some("2024-02-29")); + assert_eq!(v.cisa_action_due, None); +} + +#[tokio::test] +async fn test_tier2_f5_02_missing_all_cvss_metrics() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + let unscored = vulns + .iter() + .find(|v| v.cve_id == "CVE-2021-0001") + .expect("Missing unscored CVE"); + assert_eq!(unscored.cvss_v31_score, None); + assert_eq!(unscored.cvss_v31_severity, None); +} + +#[tokio::test] +async fn test_tier2_f5_03_multi_metric_precedence_v31_over_v2() { + let server = MockNvdServer::start(FIXTURE_MULTI_METRIC_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 1); + let v = &vulns[0]; + assert_eq!( + v.cvss_v31_score, + Some(7.8), + "Must select CVSS v3.1 score over legacy v2.0" + ); + assert_eq!(v.cvss_v31_severity.as_deref(), Some("HIGH")); +} + +#[tokio::test] +async fn test_tier2_f5_04_malformed_truncated_json() { + let server = MockNvdServer::start(FIXTURE_MALFORMED_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&opts).await; + + assert!(matches!(res, Err(PatcherError::Serialization(_)))); +} + +#[tokio::test] +async fn test_tier2_f5_05_cvss_score_boundaries_0_and_10() { + let fixture_extremes = r#"{ + "resultsPerPage": 2, "startIndex": 0, "totalResults": 2, "format": "NVD_CVE", "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [ + {"cve": {"id": "CVE-2024-0000", "descriptions": [{"lang": "en", "value": "Zero score"}], "metrics": {"cvssMetricV31": [{"source": "nvd@nist.gov", "type": "Primary", "cvssData": {"version": "3.1", "baseScore": 0.0, "baseSeverity": "NONE"}}]}}}, + {"cve": {"id": "CVE-2024-1000", "descriptions": [{"lang": "en", "value": "Max score"}], "metrics": {"cvssMetricV31": [{"source": "nvd@nist.gov", "type": "Primary", "cvssData": {"version": "3.1", "baseScore": 10.0, "baseSeverity": "CRITICAL"}}]}}} + ] + }"#; + + let server = MockNvdServer::start(fixture_extremes).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert_eq!(vulns.len(), 2); + assert_eq!(vulns[0].cvss_v31_score, Some(10.0)); + assert_eq!(vulns[1].cvss_v31_score, Some(0.0)); +} + +// ============================================================================= +// Feature 6: KEV Prioritization & CVSS Ranking (F6 - Tier 2) +// ============================================================================= + +#[tokio::test] +async fn test_tier2_f6_01_unscored_cve_sorted_last() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + let last = vulns.last().expect("Must have last item"); + assert_eq!(last.cve_id, "CVE-2021-0001", "Unscored item must sort last"); + assert_eq!(last.cvss_v31_score, None); +} + +#[tokio::test] +async fn test_tier2_f6_02_cvss_threshold_exact_boundary() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + // Exact match for 7.8 + let opts = test_scan_options(None, Some(7.8), false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + + assert!(vulns + .iter() + .any(|v| v.cve_id == "CVE-2024-1086" && v.cvss_v31_score == Some(7.8))); + for v in &vulns { + assert!(v.cvss_v31_score.unwrap_or(0.0) >= 7.8); + } +} + +#[tokio::test] +async fn test_tier2_f6_03_cvss_threshold_at_zero_and_ten() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + // min_cvss = 0.0 -> all scored retained + let opts_0 = test_scan_options(None, Some(0.0), false, None); + let vulns_0 = patcher + .scan_kernel_vulnerabilities(&opts_0) + .await + .expect("Scan failed"); + assert!(!vulns_0.is_empty()); + + // min_cvss = 10.0 -> none of the fixture items reach 10.0 + let opts_10 = test_scan_options(None, Some(10.0), false, None); + let vulns_10 = patcher + .scan_kernel_vulnerabilities(&opts_10) + .await + .expect("Scan failed"); + assert!(vulns_10.is_empty()); +} + +#[tokio::test] +async fn test_tier2_f6_04_equal_cvss_scores_deterministic_tiebreak() { + let fixture_ties = r#"{ + "resultsPerPage": 2, "startIndex": 0, "totalResults": 2, "format": "NVD_CVE", "version": "2.0", + "timestamp": "2026-11-13T21:00:00.000", + "vulnerabilities": [ + {"cve": {"id": "CVE-2024-2000", "descriptions": [{"lang": "en", "value": "Tie B"}], "metrics": {"cvssMetricV31": [{"source": "nvd@nist.gov", "type": "Primary", "cvssData": {"version": "3.1", "baseScore": 8.0, "baseSeverity": "HIGH"}}]}}}, + {"cve": {"id": "CVE-2024-1000", "descriptions": [{"lang": "en", "value": "Tie A"}], "metrics": {"cvssMetricV31": [{"source": "nvd@nist.gov", "type": "Primary", "cvssData": {"version": "3.1", "baseScore": 8.0, "baseSeverity": "HIGH"}}]}}} + ] + }"#; + + let server = MockNvdServer::start(fixture_ties).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let run1 = patcher.scan_kernel_vulnerabilities(&opts).await.unwrap(); + let run2 = patcher.scan_kernel_vulnerabilities(&opts).await.unwrap(); + + assert_eq!( + run1[0].cve_id, run2[0].cve_id, + "Tiebreaking must be strictly deterministic across calls" + ); +} + +#[tokio::test] +async fn test_tier2_f6_05_all_items_homogenous_or_empty() { + let server = MockNvdServer::start(FIXTURE_EMPTY_NVD_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let opts = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&opts) + .await + .expect("Scan failed"); + assert!(vulns.is_empty()); +} + +// ============================================================================= +// Feature 7: Fail-Closed Patch Dispatch (F7 - Tier 2) +// ============================================================================= + +#[tokio::test] +async fn test_tier2_f7_01_planned_binary_matches_host_subsystem() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + + #[cfg(target_os = "windows")] + { + assert_eq!(res.command, "UsoClient.exe"); + assert_eq!(res.os_subsystem, "UsoClient"); + assert!( + res.args + .iter() + .any(|a| a == "StartInstall" || a == "StartInteractiveScan"), + "Windows patch dispatch must invoke StartInstall or StartInteractiveScan, got: {:?}", + res.args + ); + } + + #[cfg(target_os = "linux")] + { + assert!( + ["canonical-livepatch", "apt-get", "dnf"].contains(&res.command.as_str()), + "Linux patch command must be a supported orchestrator: {}", + res.command + ); + assert_eq!(res.command, res.os_subsystem); + } + + #[cfg(target_os = "macos")] + { + assert_eq!(res.command, "softwareupdate"); + assert_eq!(res.os_subsystem, "softwareupdate"); + assert!(res.args.contains(&"--install".to_string())); + } +} + +#[tokio::test] +async fn test_tier2_f7_02_unprivileged_live_patch_error_contract() { + let patcher = KernelPatcher::new(); + if !is_elevated() { + let err = patcher + .apply_os_kernel_patch(false) + .await + .expect_err("Live patch without elevation must fail"); + assert!(matches!(err, PatcherError::InsufficientPrivileges)); + let msg = format!("{err}"); + assert!( + msg.contains("Insufficient privileges") || msg.contains("Administrator"), + "Error display message must clearly explain privilege requirement: {}", + msg + ); + } +} + +#[tokio::test] +async fn test_tier2_f7_03_dry_run_execution_result_invariants() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run planning failed"); + + // Comprehensive invariant verification on real PatchExecutionResult returned by crate + assert!(res.dry_run, "dry_run must be true"); + assert!(res.success, "dry-run planning must report success = true"); + assert!(!res.command.is_empty(), "command must not be empty"); + assert!(!res.args.is_empty(), "args must not be empty"); + for arg in &res.args { + assert!(!arg.trim().is_empty(), "Arguments must not be blank"); + } + assert!( + res.output.contains(&res.command), + "Dry run output '{}' must reference planned command '{}'", + res.output, + res.command + ); + assert!( + res.output.starts_with("[DRY-RUN]"), + "Dry run output must be prefixed with [DRY-RUN]: '{}'", + res.output + ); +} + +#[tokio::test] +async fn test_tier2_f7_04_privilege_check_precedes_command_lookup() { + let patcher = KernelPatcher::new(); + if !is_elevated() { + let res = patcher.apply_os_kernel_patch(false).await; + // Must fail with InsufficientPrivileges before attempting execution + assert!(matches!(res, Err(PatcherError::InsufficientPrivileges))); + } +} + +#[tokio::test] +async fn test_tier2_f7_05_command_injection_prevention_in_args() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run planning failed"); + + // Shell metacharacters that must NEVER appear in discrete argv tokens + let forbidden_chars = [';', '&', '|', '`', '$', '>', '<', '\n', '\r', '\0']; + + for ch in forbidden_chars { + assert!( + !res.command.contains(ch), + "Command '{}' contains dangerous shell metacharacter '{}'", + res.command, + ch + ); + for arg in &res.args { + assert!( + !arg.contains(ch), + "Argument '{}' contains dangerous shell metacharacter '{}'", + arg, + ch + ); + } + } +} + +// ============================================================================= +// Feature 8: Safe Dry-Run Mode (F8 - Tier 2) +// ============================================================================= + +#[test] +fn test_tier2_f8_01_unsupported_platform_error_display_and_traits() { + // Invoke genuine crate discovery for non-host platforms to verify UnsupportedPlatform error generation + #[cfg(target_os = "windows")] + let err = killswitch_kernel_patcher::discovery::linux::detect_linux_host_kernel() + .expect_err("Must fail on non-Linux"); + + #[cfg(target_os = "linux")] + let err = killswitch_kernel_patcher::discovery::windows::detect_windows_kernel() + .expect_err("Must fail on non-Windows"); + + #[cfg(target_os = "macos")] + let err = killswitch_kernel_patcher::discovery::windows::detect_windows_kernel() + .expect_err("Must fail on non-Windows"); + + // Verify error taxonomy and Display trait formatting + match &err { + PatcherError::UnsupportedPlatform(platform_msg) => { + assert!( + !platform_msg.is_empty(), + "UnsupportedPlatform message must not be empty" + ); + let display_str = format!("{err}"); + assert!( + display_str.starts_with("Unsupported platform:"), + "Display representation must start with 'Unsupported platform:': '{}'", + display_str + ); + } + other => panic!( + "Expected PatcherError::UnsupportedPlatform, got: {:?}", + other + ), + } +} + +#[tokio::test] +async fn test_tier2_f8_02_dry_run_args_vector_exact_tokens() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + for arg in &res.args { + assert!( + !arg.contains(' '), + "Arguments should be separate argv tokens: '{}'", + arg + ); + } +} + +#[test] +fn test_tier2_f8_03_dry_run_json_serialization_roundtrip() { + let original = PatchExecutionResult { + dry_run: true, + command: "apt-get".to_string(), + args: vec!["update".to_string(), "--only-upgrade".to_string()], + success: true, + output: "[DRY-RUN] Planned patch".to_string(), + os_subsystem: "apt".to_string(), + }; + let json = serde_json::to_string(&original).expect("Serialize failed"); + let back: PatchExecutionResult = serde_json::from_str(&json).expect("Deserialize failed"); + assert_eq!(original, back); +} + +#[tokio::test] +async fn test_tier2_f8_04_dry_run_high_concurrency_stress() { + let patcher = std::sync::Arc::new(KernelPatcher::new()); + let mut tasks = Vec::new(); + + for _ in 0..50 { + let p = std::sync::Arc::clone(&patcher); + tasks.push(tokio::spawn( + async move { p.apply_os_kernel_patch(true).await }, + )); + } + + for task in tasks { + let res = task.await.expect("Join failed").expect("Dry run failed"); + assert!(res.dry_run); + assert!(res.success); + } +} + +#[tokio::test] +async fn test_tier2_f8_05_dry_run_output_utf8_hygiene() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + + // Output must contain 0 control characters (except newline \n or \r) + for b in res.output.bytes() { + if b < 0x20 { + assert!( + b == b'\n' || b == b'\r' || b == b'\t', + "Illegal control byte 0x{:02X}", + b + ); + } + } + assert!( + !res.output.contains('\u{FFFD}'), + "Output must not contain replacement characters" + ); +} diff --git a/crates/killswitch-kernel-patcher/tests/tier3_pairwise_combinations_tests.rs b/crates/killswitch-kernel-patcher/tests/tier3_pairwise_combinations_tests.rs new file mode 100644 index 0000000..e09148e --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/tier3_pairwise_combinations_tests.rs @@ -0,0 +1,262 @@ +//! Tier 3: Pairwise Combinatorial Feature Interactions Test Suite for `killswitch-kernel-patcher`. +//! Covers 12 cross-feature interaction combinations across Discovery, Auth, Scanning, Scoring, +//! Privilege Evaluation, and Patch Orchestration. + +mod common; +use common::*; +use killswitch_kernel_patcher::{is_elevated, HostKernelInfo, KernelPatcher, PatcherError}; + +#[tokio::test] +async fn test_tier3_01_kev_prioritization_with_dry_run_dispatch() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let options = test_scan_options( + Some("cpe:2.3:o:linux:linux_kernel:6.8.0:*:*:*:*:*:*:*"), + None, + false, + None, + ); + let vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + + // Invariant 1: Top vulnerability MUST be CISA KEV even if a non-KEV has higher CVSS + assert!(vulns[0].is_cisa_kev, "Top finding must be KEV"); + assert_eq!(vulns[0].cve_id, "CVE-2024-1086"); + + // Invariant 2: Trigger dry-run patch planning based on discovered KEV threat + let patch_res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run patch planning failed"); + assert!(patch_res.dry_run); + assert!(patch_res.success); + assert!(!patch_res.command.is_empty()); + assert!(!patch_res.args.is_empty()); + assert!(patch_res.output.contains("[DRY-RUN]")); +} + +#[tokio::test] +async fn test_tier3_02_cvss_threshold_filter_and_dispatch_gate() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + // Scenario A: Filter min_cvss_score >= 8.0 (Only CVE-2024-9999 with 9.8 should survive) + let options = test_scan_options(None, Some(8.0), false, None); + let filtered_vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + for v in &filtered_vulns { + assert!(v.cvss_v31_score.unwrap_or(0.0) >= 8.0); + } + assert_eq!(filtered_vulns.len(), 1); + assert_eq!(filtered_vulns[0].cve_id, "CVE-2024-9999"); + + // Scenario B: Filter min_cvss_score >= 9.9 (Zero should survive) + let empty_options = test_scan_options(None, Some(9.9), false, None); + let empty_res = patcher + .scan_kernel_vulnerabilities(&empty_options) + .await + .expect("Scan failed"); + assert_eq!(empty_res.len(), 0); +} + +#[tokio::test] +async fn test_tier3_03_nvd_api_key_auth_with_kev_only_filter() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let test_key = "test_nvd_api_key_secret_abc123"; + let options = test_scan_options(None, None, true, Some(test_key)); + + let vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + + // Verify header arrived at mock server + assert_eq!(server.last_api_key(), Some(test_key.to_string())); + + // Verify kev_only filtering removed all non-KEV items + assert!(!vulns.is_empty()); + for v in &vulns { + assert!( + v.is_cisa_kev, + "All returned findings must be CISA KEV entries" + ); + } + assert!(!vulns.iter().any(|v| v.cve_id == "CVE-2024-9999")); +} + +#[tokio::test] +async fn test_tier3_04_host_discovery_cpe_to_nvd_query_dispatch() { + let server = MockNvdServer::start(FIXTURE_EMPTY_NVD_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let host_info = HostKernelInfo::detect_host_kernel().expect("Host kernel detection failed"); + let cpe = host_info.to_cpe23(); + assert_valid_cpe23(&cpe); + + // Call scan with default host CPE + let options = test_scan_options(Some(&cpe), None, false, None); + let _ = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + + assert_eq!(server.total_requests(), 1); +} + +#[tokio::test] +async fn test_tier3_05_privilege_boundary_live_vs_dry_run_interaction() { + let patcher = KernelPatcher::new(); + + if !is_elevated() { + // Invariant: Non-elevated live patch MUST fail closed with InsufficientPrivileges + let live_res = patcher.apply_os_kernel_patch(false).await; + assert!( + matches!(live_res, Err(PatcherError::InsufficientPrivileges)), + "Expected InsufficientPrivileges under non-elevated context, got {:?}", + live_res + ); + } + + // Invariant: Dry run MUST succeed regardless of privilege state + let dry_res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run must always succeed"); + assert!(dry_res.dry_run); + assert!(dry_res.success); +} + +#[tokio::test] +async fn test_tier3_06_rate_limited_response_without_api_key() { + let server = MockNvdServer::start_with_status(429, FIXTURE_RATE_LIMIT_429_BODY).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let options = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&options).await; + + assert!(matches!(res, Err(PatcherError::RateLimited))); +} + +#[tokio::test] +async fn test_tier3_07_empty_vulnerability_set_patch_dispatch() { + let server = MockNvdServer::start(FIXTURE_EMPTY_NVD_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let options = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + assert!(vulns.is_empty()); + + // When 0 vulnerabilities exist, verify patch dry-run can still be audited cleanly + let dry_res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run succeeded"); + assert!(dry_res.dry_run); +} + +#[tokio::test] +async fn test_tier3_08_custom_cpe_override_with_cvss_threshold() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let custom_cpe = "cpe:2.3:o:microsoft:windows_server_2022:10.0.20348:*:*:*:*:*:*:*"; + let options = test_scan_options(Some(custom_cpe), Some(7.0), false, None); + + let vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + for v in &vulns { + assert!(v.cvss_v31_score.unwrap_or(0.0) >= 7.0); + } +} + +#[tokio::test] +async fn test_tier3_09_multi_metric_kev_sorting_tiebreak() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let options = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Scan failed"); + + // Invariant: CVSS ranking order + assert_vulnerability_ranking(&vulns); +} + +#[tokio::test] +async fn test_tier3_10_linux_subsystem_livepatch_fallback_dry_run() { + let patcher = KernelPatcher::new(); + let res = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run planning failed"); + + #[cfg(target_os = "linux")] + { + assert!(["canonical-livepatch", "apt-get", "dnf"].contains(&res.os_subsystem.as_str())); + } + #[cfg(target_os = "windows")] + { + assert_eq!(res.os_subsystem, "UsoClient"); + assert_eq!(res.command, "UsoClient.exe"); + } + #[cfg(target_os = "macos")] + { + assert_eq!(res.os_subsystem, "softwareupdate"); + assert_eq!(res.command, "softwareupdate"); + } +} + +#[tokio::test] +async fn test_tier3_11_malformed_nvd_payload_safeguard_patch_pipeline() { + let server = MockNvdServer::start(FIXTURE_MALFORMED_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let options = test_scan_options(None, None, false, None); + let res = patcher.scan_kernel_vulnerabilities(&options).await; + + assert!(matches!(res, Err(PatcherError::Serialization(_)))); +} + +#[tokio::test] +async fn test_tier3_12_concurrent_scan_and_dry_run_stress() { + use std::sync::Arc; + let server = Arc::new(MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await); + let patcher = Arc::new(KernelPatcher::with_base_url(&server.endpoint_url)); + + let mut set = tokio::task::JoinSet::new(); + + for _ in 0..20 { + let p = Arc::clone(&patcher); + set.spawn(async move { + let options = test_scan_options(None, None, false, None); + let vulns = p.scan_kernel_vulnerabilities(&options).await.unwrap(); + let dry = p.apply_os_kernel_patch(true).await.unwrap(); + (vulns.len(), dry.dry_run) + }); + } + + let mut completed = 0; + while let Some(res) = set.join_next().await { + let (v_len, dry_run) = res.expect("Task panicked"); + assert_eq!(v_len, 5); + assert!(dry_run); + completed += 1; + } + + assert_eq!(completed, 20); + assert_eq!(server.total_requests(), 20); +} diff --git a/crates/killswitch-kernel-patcher/tests/tier4_real_world_scenarios_tests.rs b/crates/killswitch-kernel-patcher/tests/tier4_real_world_scenarios_tests.rs new file mode 100644 index 0000000..c3e762f --- /dev/null +++ b/crates/killswitch-kernel-patcher/tests/tier4_real_world_scenarios_tests.rs @@ -0,0 +1,162 @@ +//! Tier 4: Real-World Scenarios Test Suite for `killswitch-kernel-patcher`. +//! Covers Scenarios S1 through S5 exercising end-to-end operational flows. + +mod common; +use common::*; +use killswitch_kernel_patcher::{ + is_elevated, HostKernelInfo, KernelPatcher, OsFamily, PatcherError, +}; + +#[test] +fn test_tier4_s1_active_host_kernel_discovery() { + let info = HostKernelInfo::detect_host_kernel().expect("Host kernel detection failed"); + + // Platform validation + #[cfg(target_os = "windows")] + assert_eq!(info.os_family, OsFamily::Windows); + #[cfg(target_os = "linux")] + assert_eq!(info.os_family, OsFamily::Linux); + #[cfg(target_os = "macos")] + assert_eq!(info.os_family, OsFamily::MacOS); + + // Release and architecture + assert!( + !info.kernel_release.is_empty(), + "Kernel release cannot be empty" + ); + assert!( + !info.architecture.is_empty(), + "Architecture cannot be empty" + ); + assert!( + ["x86_64", "aarch64", "x86", "arm"].contains(&info.architecture.as_str()), + "Architecture should be canonical, got {}", + info.architecture + ); + + // CPE 2.3 verification + let cpe = info.to_cpe23(); + assert_valid_cpe23(&cpe); + assert_eq!(info.cpe23, cpe); +} + +#[tokio::test] +async fn test_tier4_s2_offline_kev_pipeline() { + let server = MockNvdServer::start(FIXTURE_MULTI_CVE_RANKING_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + let options = test_scan_options(None, None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&options) + .await + .expect("Offline scan failed"); + + assert_eq!(vulns.len(), 5, "Fixture contains exactly 5 vulnerabilities"); + + // Invariant: KEV entries must strictly precede non-KEV entries + assert_vulnerability_ranking(&vulns); + + // Verifying specific positions + assert_eq!(vulns[0].cve_id, "CVE-2024-1086"); // KEV, CVSS 7.8 + assert!(vulns[0].is_cisa_kev); + assert_eq!(vulns[1].cve_id, "CVE-2023-4567"); // KEV, CVSS 5.3 + assert!(vulns[1].is_cisa_kev); + assert_eq!(vulns[2].cve_id, "CVE-2024-9999"); // Non-KEV, CVSS 9.8 (Subordinated to KEV) + assert!(!vulns[2].is_cisa_kev); + assert_eq!(vulns[3].cve_id, "CVE-2022-1234"); // Non-KEV, CVSS 4.3 + assert_eq!(vulns[4].cve_id, "CVE-2021-0001"); // Non-KEV, unscored +} + +#[tokio::test] +async fn test_tier4_s3_dry_run_remediation_workflow() { + let server = MockNvdServer::start(FIXTURE_SINGLE_KEV_CVE_JSON).await; + let patcher = KernelPatcher::with_base_url(&server.endpoint_url); + + // Step 1: Detect host kernel + let host_info = HostKernelInfo::detect_host_kernel().expect("Host detection failed"); + let cpe = host_info.to_cpe23(); + + // Step 2: Scan vulnerabilities using detected CPE + let scan_opts = test_scan_options(Some(&cpe), None, false, None); + let vulns = patcher + .scan_kernel_vulnerabilities(&scan_opts) + .await + .expect("Scan failed"); + assert!(!vulns.is_empty()); + + // Step 3: Trigger safe dry-run orchestration + let plan = patcher + .apply_os_kernel_patch(true) + .await + .expect("Dry run failed"); + + // Invariant: Zero system mutation + assert!(plan.dry_run); + assert!(plan.success); + assert!(!plan.command.is_empty()); + assert!(!plan.args.is_empty()); + assert!(plan.output.contains("[DRY-RUN]")); + + #[cfg(target_os = "windows")] + assert_eq!(plan.command, "UsoClient.exe"); + #[cfg(target_os = "macos")] + assert_eq!(plan.command, "softwareupdate"); +} + +#[tokio::test] +async fn test_tier4_s4_non_elevated_privilege_guard() { + let patcher = KernelPatcher::new(); + + if !is_elevated() { + // Must return InsufficientPrivileges + let result = patcher.apply_os_kernel_patch(false).await; + match result { + Err(PatcherError::InsufficientPrivileges) => { + // Expected fail-closed behavior + } + other => panic!("Expected InsufficientPrivileges, got {:?}", other), + } + } else { + println!("Test runner is running with elevated privileges; skipping non-elevated assert"); + } +} + +#[tokio::test] +async fn test_tier4_s5_live_nvd_integration_query() { + if !is_live_nvd_reachable().await { + println!("NIST NVD 2.0 API is unreachable or rate limited; skipping live network test"); + return; + } + + let patcher = KernelPatcher::new(); + let api_key = std::env::var("NVD_API_KEY").ok(); + + // Query for a widely known Linux kernel CPE + let query_cpe = "cpe:2.3:o:linux:linux_kernel:5.15.0:*:*:*:*:*:*:*"; + let options = test_scan_options(Some(query_cpe), None, false, api_key.as_deref()); + + let res = patcher.scan_kernel_vulnerabilities(&options).await; + match res { + Ok(vulns) => { + println!( + "Successfully queried live NIST NVD 2.0! Received {} vulnerabilities", + vulns.len() + ); + if !vulns.is_empty() { + assert_vulnerability_ranking(&vulns); + } + } + Err(PatcherError::RateLimited) => { + println!("NIST NVD returned 429 Rate Limited; gracefully tolerated"); + } + Err(PatcherError::Network(e)) => { + println!( + "Transient network error contacting NIST: {}; skipping gracefully", + e + ); + } + Err(other) => { + panic!("Unexpected error from live NVD endpoint: {:?}", other); + } + } +} diff --git a/crates/killswitch-server/Cargo.toml b/crates/killswitch-server/Cargo.toml index 614a171..784a5ae 100644 --- a/crates/killswitch-server/Cargo.toml +++ b/crates/killswitch-server/Cargo.toml @@ -15,6 +15,7 @@ killswitch-core = { workspace = true } killswitch-adjudication = { workspace = true } killswitch-telemetry = { workspace = true } killswitch-conformal = { workspace = true } +killswitch-kernel-patcher = { workspace = true } # Web framework & async runtime axum = { workspace = true, features = ["macros"] } diff --git a/crates/killswitch-server/src/server.rs b/crates/killswitch-server/src/server.rs index bd8bee5..8afba22 100644 --- a/crates/killswitch-server/src/server.rs +++ b/crates/killswitch-server/src/server.rs @@ -129,6 +129,16 @@ impl Default for CageKeyManifestResolver { } } +/// Summary of the latest background OS kernel vulnerability scan. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct KernelScanSummary { + pub scanned_at: chrono::DateTime, + pub host_kernel: killswitch_kernel_patcher::HostKernelInfo, + pub vulnerability_count: usize, + pub cisa_kev_count: usize, + pub vulnerabilities: Vec, +} + /// Configuration for local Axum HTTP control server. #[derive(Debug, Clone)] pub struct ServerConfig { @@ -137,6 +147,8 @@ pub struct ServerConfig { pub max_body_bytes: usize, pub request_timeout_secs: u64, pub open_browser: bool, + pub kernel_scan_interval_secs: u64, + pub enable_kernel_scan: bool, } impl Default for ServerConfig { @@ -147,6 +159,8 @@ impl Default for ServerConfig { max_body_bytes: 2 * 1024 * 1024, // 2 MB request_timeout_secs: 30, open_browser: false, + kernel_scan_interval_secs: 3600, + enable_kernel_scan: true, } } } @@ -169,6 +183,7 @@ pub struct ServerState { pub active_bound_port: Arc, pub fprime_supervisor: Arc, pub config: ServerConfig, + pub latest_kernel_scan: Arc>>, // --- CAGE Substrate Integration State --- pub signing_key: Arc, @@ -301,6 +316,7 @@ impl ServerState { active_bound_port: Arc::new(std::sync::atomic::AtomicU16::new(3030)), fprime_supervisor: Arc::new(killswitch_core::fprime::FPrimeSupervisor::new()), config: ServerConfig::default(), + latest_kernel_scan: Arc::new(RwLock::new(None)), signing_key, ed25519_kid, @@ -646,6 +662,12 @@ impl KillSwitchServer { } }); + // Spawn periodic OS Kernel Vulnerability & CISA KEV Scanner loop + let patcher_state = Arc::clone(&self.state); + let patcher_handle = tokio::spawn(async move { + run_periodic_kernel_scanner(patcher_state).await; + }); + // Re-enforce unexpired leases from journal fail-closed on startup let _ = self .state @@ -664,6 +686,7 @@ impl KillSwitchServer { .map_err(|e| ServerError::Internal(format!("Server error: {}", e)))?; sentinel_handle.abort(); + patcher_handle.abort(); let _ = std::fs::remove_file("active_port.txt"); if let Ok(exe) = std::env::current_exe() { @@ -728,3 +751,167 @@ pub fn open_browser_cross_platform(url: &str) { } }); } + +/// Executes a single OS kernel vulnerability scan cycle against NVD API 2.0 / CISA KEV. +/// Returns the number of vulnerabilities detected, or PatcherError on failure. +pub async fn run_periodic_kernel_scan_cycle( + state: &ServerState, +) -> Result { + // 1. Detect host platform and kernel release version (offloaded to avoid blocking worker thread) + let host_kernel = + tokio::task::spawn_blocking(killswitch_kernel_patcher::HostKernelInfo::detect_host_kernel) + .await + .map_err(|e| { + killswitch_kernel_patcher::PatcherError::DetectionFailed(e.to_string()) + })??; + + tracing::info!( + "🛡️ [KERNEL-SCANNER] Detected host OS: {} | Kernel: {} | CPE: {}", + host_kernel.os_family, + host_kernel.kernel_release, + host_kernel.cpe23 + ); + + // 2. Resolve NVD_API_KEY strictly from runtime environment variable + // Invariant: Zero leakage into CLI args, process tables, or persistent configs + let api_key = std::env::var("NVD_API_KEY").ok().and_then(|k| { + let trimmed = k.trim().to_string(); + if trimmed.is_empty() { + None + } else { + Some(trimmed) + } + }); + + if api_key.is_some() { + tracing::info!( + "🔑 [KERNEL-SCANNER] Using authenticated NVD API 2.0 key for elevated rate limits" + ); + } else { + tracing::debug!( + "ℹ️ [KERNEL-SCANNER] No NVD_API_KEY detected in environment; using public rate limits" + ); + } + + // 3. Configure ScanOptions + let options = killswitch_kernel_patcher::ScanOptions { + cpe: Some(host_kernel.cpe23.clone()), + min_cvss_score: None, + kev_only: false, + api_key, + timeout_secs: 30, + }; + + // 4. Execute scan via KernelPatcher + let patcher = killswitch_kernel_patcher::KernelPatcher::new(); + let findings = patcher.scan_kernel_vulnerabilities(&options).await?; + + let kev_count = findings.iter().filter(|v| v.is_cisa_kev).count(); + let total_count = findings.len(); + + if total_count == 0 { + tracing::info!( + "🛡️ [KERNEL-SCANNER] Kernel vulnerability scan complete: 0 vulnerabilities found for host CPE {}", + host_kernel.cpe23 + ); + } else { + tracing::warn!( + "⚠️ [KERNEL-SCANNER] Kernel vulnerability scan complete: {} vulnerabilities found ({} CISA KEV) for host CPE {}", + total_count, + kev_count, + host_kernel.cpe23 + ); + + for finding in findings.iter().take(5) { + if finding.is_cisa_kev { + tracing::warn!( + "🚨 [KERNEL-SCANNER] CISA KEV: {} (CVSS {:?}): {}", + finding.cve_id, + finding.cvss_v31_score, + finding.description + ); + } else { + tracing::info!( + "ℹ️ [KERNEL-SCANNER] Vulnerability: {} (CVSS {:?}): {}", + finding.cve_id, + finding.cvss_v31_score, + finding.description + ); + } + } + } + + // 5. Update cached scan summary in ServerState + let summary = KernelScanSummary { + scanned_at: chrono::Utc::now(), + host_kernel, + vulnerability_count: total_count, + cisa_kev_count: kev_count, + vulnerabilities: findings, + }; + *state.latest_kernel_scan.write().await = Some(summary); + + Ok(total_count) +} + +/// Background loop executing periodic kernel vulnerability scans. +pub async fn run_periodic_kernel_scanner(state: Arc) { + let interval_secs = std::env::var("KILLSWITCH_KERNEL_SCAN_INTERVAL_SECS") + .ok() + .and_then(|v| v.parse::().ok()) + .unwrap_or(state.config.kernel_scan_interval_secs) + .max(10); // Minimum clamp 10s + + let enabled = + std::env::var("KILLSWITCH_DISABLE_KERNEL_SCAN").is_err() && state.config.enable_kernel_scan; + + if !enabled { + tracing::info!( + "ℹ️ [KERNEL-SCANNER] Periodic kernel vulnerability scanning disabled by config/env" + ); + return; + } + + tracing::info!( + "🛡️ [KERNEL-SCANNER] Starting periodic kernel vulnerability scanner (interval: {}s)", + interval_secs + ); + + // Initial delay before first scan so server startup completes swiftly without blocking + let initial_delay_secs = std::env::var("KILLSWITCH_KERNEL_SCAN_INITIAL_DELAY_SECS") + .ok() + .and_then(|v| v.parse::().ok()) + .unwrap_or(5); + + tokio::time::sleep(tokio::time::Duration::from_secs(initial_delay_secs)).await; + + let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(interval_secs)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + + loop { + tracing::debug!( + "🛡️ [KERNEL-SCANNER] Initiating periodic kernel vulnerability scan cycle..." + ); + match run_periodic_kernel_scan_cycle(&state).await { + Ok(count) => { + tracing::debug!( + "🛡️ [KERNEL-SCANNER] Scan cycle finished: {} findings", + count + ); + } + Err(killswitch_kernel_patcher::PatcherError::RateLimited) => { + tracing::warn!( + "⚠️ [KERNEL-SCANNER] NVD API rate-limit reached; skipping until next scheduled cycle" + ); + } + Err(e) => { + tracing::warn!( + "⚠️ [KERNEL-SCANNER] Periodic kernel vulnerability scan cycle encountered error: {}", + e + ); + } + } + + interval.tick().await; + } +} diff --git a/crates/killswitch-server/tests/empirical_challenge_sec1_2.rs b/crates/killswitch-server/tests/empirical_challenge_sec1_2.rs index 823d460..1310b44 100644 --- a/crates/killswitch-server/tests/empirical_challenge_sec1_2.rs +++ b/crates/killswitch-server/tests/empirical_challenge_sec1_2.rs @@ -230,6 +230,7 @@ fn test_empirical_linux_proc_net_tcp_and_tcp6_parser_stress() { #[test] fn test_empirical_macos_darwin_socket_structures() { // 1. Verify get_active_darwin_sockets does not crash and returns valid sockets + let _probe_listener = std::net::TcpListener::bind("127.0.0.1:0").ok(); let darwin_res = get_active_darwin_sockets(); assert!(darwin_res.is_ok(), "Darwin socket query must succeed"); let sockets = darwin_res.unwrap(); diff --git a/crates/killswitch-telemetry/src/ring0_driver_loader.rs b/crates/killswitch-telemetry/src/ring0_driver_loader.rs index 811b0bc..340d9ef 100644 --- a/crates/killswitch-telemetry/src/ring0_driver_loader.rs +++ b/crates/killswitch-telemetry/src/ring0_driver_loader.rs @@ -905,6 +905,10 @@ pub fn query_live_host_ring0_inventory() -> HostKernelDriverInventory { sha256_file_if_exists(win_inf); let (linux_ebpf_c_present, linux_ebpf_c_sha256) = sha256_file_if_exists(lin_bpf); + #[cfg_attr( + not(any(target_os = "windows", target_os = "linux")), + allow(unused_mut) + )] let mut detected_host_kernel_filters = Vec::new(); #[cfg(target_os = "windows")]