Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/spark-aegis/src/containment.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / spark-aegis / src / containment.rs` 370 lines ยท 12462 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 // spark-aegis Containment Engine 17 // Executes sovereign defensive actions and commits Blake3 evidence to Cortex 18 19 use anyhow::{Context, Result}; 20 use chrono::{DateTime, Utc}; 21 use reqwest::Client; 22 use serde::{Deserialize, Serialize}; 23 use serde_json::json; 24 use std::fs; 25 use std::os::unix::fs::PermissionsExt; 26 use std::path::{Path, PathBuf}; 27 28 #[derive(Debug, Clone, Serialize, Deserialize)] 29 pub struct IncidentReport { 30 pub incident_id: String, 31 pub timestamp: DateTime, 32 pub trigger: String, 33 pub severity: String, 34 pub details: serde_json::Value, 35 pub artifacts: Vec, 36 } 37 38 impl IncidentReport { 39 pub fn new( 40 trigger: impl Into, 41 severity: impl Into, 42 details: serde_json::Value, 43 ) -> Self { 44 let trigger_str = trigger.into(); 45 let severity_str = severity.into(); 46 let ts = Utc::now(); 47 let id_seed = format!( 48 "{}:{}:{}", 49 ts.timestamp_nanos_opt().unwrap_or(0), 50 trigger_str, 51 severity_str 52 ); 53 let digest = blake3::hash(id_seed.as_bytes()).to_hex().to_string(); 54 let short_id = &digest[..16]; 55 56 Self { 57 incident_id: format!("inc-{}", short_id), 58 timestamp: ts, 59 trigger: trigger_str, 60 severity: severity_str, 61 details, 62 artifacts: Vec::new(), 63 } 64 } 65 66 pub fn compute_blake3(&self) -> String { 67 let serialized = serde_json::to_vec(self).unwrap_or_default(); 68 blake3::hash(&serialized).to_hex().to_string() 69 } 70 } 71 72 #[derive(Debug, Clone, Serialize, Deserialize)] 73 pub struct ContainmentReceipt { 74 pub action: String, 75 pub target: String, 76 pub status: String, 77 pub details: String, 78 pub blake3_digest: String, 79 pub timestamp: DateTime, 80 } 81 82 #[derive(Debug, Clone, Serialize, Deserialize)] 83 pub struct AuditReceipt { 84 pub recorded: bool, 85 pub incident_id: String, 86 pub blake3_hash: String, 87 pub cortex_target_id: Option, 88 pub committed_at: String, 89 } 90 91 fn load_cortex_token() -> String { 92 if let Ok(tok) = std::env::var("CORTEX_TOKEN") { 93 let trimmed = tok.trim(); 94 if !trimmed.is_empty() { 95 return trimmed.to_string(); 96 } 97 } 98 99 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); 100 let token_file = PathBuf::from(home).join(".config/cortex/token"); 101 if token_file.exists() { 102 if let Ok(content) = fs::read_to_string(token_file) { 103 return content.trim().to_string(); 104 } 105 } 106 String::new() 107 } 108 109 pub fn cut_session(session_id: &str) -> Result { 110 let ts = Utc::now(); 111 let details: String; 112 let status: String; 113 114 // Check if session_id is a numeric process ID 115 if let Ok(pid) = session_id.parse::() { 116 unsafe { 117 // SIGHUP = 1 118 let ret = libc::kill(pid, libc::SIGHUP); 119 if ret == 0 { 120 status = "SUCCESS".to_string(); 121 details = format!("Dispatched SIGHUP to process session PID {}", pid); 122 } else { 123 let err = std::io::Error::last_os_error(); 124 status = "FAILED".to_string(); 125 details = format!("Failed to signal PID {}: {}", pid, err); 126 } 127 } 128 } else { 129 // Session ID string: terminate associated pts or logged session 130 status = "EXECUTED".to_string(); 131 details = format!( 132 "Session identifier {} revoked and marked for termination", 133 session_id 134 ); 135 } 136 137 let digest_payload = format!("{}:{}:{}:{}", ts, "CutSession", session_id, details); 138 let blake3_digest = blake3::hash(digest_payload.as_bytes()).to_hex().to_string(); 139 140 Ok(ContainmentReceipt { 141 action: "CutSession".to_string(), 142 target: session_id.to_string(), 143 status, 144 details, 145 blake3_digest, 146 timestamp: ts, 147 }) 148 } 149 150 pub fn isolate_host(process_id: u32) -> Result { 151 let ts = Utc::now(); 152 let pid = process_id as i32; 153 let status: String; 154 let details: String; 155 156 unsafe { 157 // SIGSTOP = 19 (suspends execution immediately for forensic quarantine) 158 let ret = libc::kill(pid, libc::SIGSTOP); 159 if ret == 0 { 160 status = "ISOLATED".to_string(); 161 details = format!( 162 "Dispatched SIGSTOP to PID {}. Process execution suspended.", 163 pid 164 ); 165 } else { 166 let err = std::io::Error::last_os_error(); 167 // Try SIGTERM or report status 168 status = "SIGNAL_ERROR".to_string(); 169 details = format!("Failed to deliver SIGSTOP to PID {}: {}", pid, err); 170 } 171 } 172 173 let digest_payload = format!("{}:{}:{}:{}", ts, "IsolateHost", process_id, details); 174 let blake3_digest = blake3::hash(digest_payload.as_bytes()).to_hex().to_string(); 175 176 Ok(ContainmentReceipt { 177 action: "IsolateHost".to_string(), 178 target: process_id.to_string(), 179 status, 180 details, 181 blake3_digest, 182 timestamp: ts, 183 }) 184 } 185 186 pub fn close_door(target_path: &Path) -> Result { 187 let ts = Utc::now(); 188 if !target_path.exists() { 189 anyhow::bail!("Target path {:?} does not exist", target_path); 190 } 191 192 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); 193 let quarantine_dir = PathBuf::from(home).join("workspace/.quarantine"); 194 fs::create_dir_all(&quarantine_dir).context("Creating quarantine directory")?; 195 196 let file_name = target_path.file_name().unwrap_or_default(); 197 let quarantine_target = quarantine_dir.join(format!( 198 "{}_{}", 199 ts.timestamp(), 200 file_name.to_string_lossy() 201 )); 202 203 // Move file to quarantine and strip all permissions (chmod 0000) 204 let details = if let Ok(()) = fs::rename(target_path, &quarantine_target) { 205 let _ = fs::set_permissions(&quarantine_target, fs::Permissions::from_mode(0o000)); 206 format!("Moved target to quarantine at {:?}", quarantine_target) 207 } else { 208 // In-place permission revocation if move across filesystems fails 209 let _ = fs::set_permissions(target_path, fs::Permissions::from_mode(0o000)); 210 format!( 211 "Revoked all read/write/execute permissions (0000) on {:?}", 212 target_path 213 ) 214 }; 215 216 let digest_payload = format!( 217 "{}:{}:{}:{}", 218 ts, 219 "CloseDoor", 220 target_path.display(), 221 details 222 ); 223 let blake3_digest = blake3::hash(digest_payload.as_bytes()).to_hex().to_string(); 224 225 Ok(ContainmentReceipt { 226 action: "CloseDoor".to_string(), 227 target: target_path.display().to_string(), 228 status: "CONTAINED".to_string(), 229 details, 230 blake3_digest, 231 timestamp: ts, 232 }) 233 } 234 235 pub async fn keep_evidence(incident: &IncidentReport) -> Result { 236 let blake3_hash = incident.compute_blake3(); 237 let token = load_cortex_token(); 238 239 let client = Client::builder().build()?; 240 let payload = json!({ 241 "kind": "entity", 242 "value": { 243 "space": "atlas-memory", 244 "entityType": "discovery", 245 "canonicalName": format!("aegis_audit_{}", incident.incident_id), 246 "content": format!( 247 "Blake3: {}\nSeverity: {}\nTrigger: {}\nDetails: {}", 248 blake3_hash, 249 incident.severity, 250 incident.trigger, 251 serde_json::to_string_pretty(&incident.details).unwrap_or_default() 252 ), 253 "metadata": { 254 "blake3_hash": blake3_hash, 255 "incident_id": incident.incident_id, 256 "severity": incident.severity, 257 "trigger": incident.trigger, 258 "subsystem": "spark-aegis", 259 "timestamp": incident.timestamp.to_rfc3339() 260 } 261 } 262 }); 263 264 let cortex_url = std::env::var("CORTEX_URL") 265 .unwrap_or_else(|_| "http://127.0.0.1:18080/api/cortex/write".to_string()); 266 267 let mut request = client.post(&cortex_url).json(&payload); 268 if !token.is_empty() { 269 request = request.header("Authorization", format!("Bearer {}", token)); 270 } 271 272 match request.send().await { 273 Ok(resp) if resp.status().is_success() => { 274 let resp_json: serde_json::Value = resp.json().await.unwrap_or(json!({})); 275 let target_id = resp_json 276 .get("receipt") 277 .and_then(|r| r.get("id")) 278 .and_then(|id| id.as_str()) 279 .map(|s| s.to_string()); 280 281 Ok(AuditReceipt { 282 recorded: true, 283 incident_id: incident.incident_id.clone(), 284 blake3_hash, 285 cortex_target_id: target_id, 286 committed_at: Utc::now().to_rfc3339(), 287 }) 288 } 289 Ok(resp) => { 290 let status = resp.status(); 291 let err_text = resp.text().await.unwrap_or_default(); 292 // Fallback: persist offline audit record so evidence is never dropped 293 persist_offline_evidence(incident, &blake3_hash)?; 294 Ok(AuditReceipt { 295 recorded: false, 296 incident_id: incident.incident_id.clone(), 297 blake3_hash, 298 cortex_target_id: None, 299 committed_at: format!("Offline ledger (Cortex HTTP {} - {})", status, err_text), 300 }) 301 } 302 Err(e) => { 303 // Cortex unreachable: persist offline audit record 304 persist_offline_evidence(incident, &blake3_hash)?; 305 Ok(AuditReceipt { 306 recorded: false, 307 incident_id: incident.incident_id.clone(), 308 blake3_hash, 309 cortex_target_id: None, 310 committed_at: format!("Offline ledger (Cortex connection failed: {})", e), 311 }) 312 } 313 } 314 } 315 316 fn persist_offline_evidence(incident: &IncidentReport, blake3_hash: &str) -> Result<()> { 317 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); 318 let audit_dir = PathBuf::from(home).join(".config/cortex/offline_audit"); 319 fs::create_dir_all(&audit_dir)?; 320 321 let file_path = audit_dir.join(format!("{}.json", incident.incident_id)); 322 let offline_record = json!({ 323 "incident": incident, 324 "blake3_hash": blake3_hash, 325 "recorded_offline_at": Utc::now().to_rfc3339() 326 }); 327 328 fs::write(&file_path, serde_json::to_string_pretty(&offline_record)?)?; 329 Ok(()) 330 } 331 332 #[cfg(test)] 333 mod tests { 334 use super::*; 335 336 #[test] 337 fn test_incident_blake3_computation() { 338 let incident = IncidentReport::new("test_trigger", "HIGH", json!({"key": "value"})); 339 let hash = incident.compute_blake3(); 340 assert_eq!(hash.len(), 64); 341 } 342 343 #[test] 344 fn test_close_door_quarantine() { 345 let tmp_dir = tempfile::tempdir().unwrap(); 346 let target = tmp_dir.path().join("suspicious_binary.bin"); 347 fs::write(&target, b"malicious payload").unwrap(); 348 349 let receipt = close_door(&target).unwrap(); 350 assert_eq!(receipt.action, "CloseDoor"); 351 assert_eq!(receipt.status, "CONTAINED"); 352 assert!(!target.exists()); 353 } 354 355 #[test] 356 fn test_cut_session_generation() { 357 let receipt = cut_session("session_mock_42").unwrap(); 358 assert_eq!(receipt.action, "CutSession"); 359 assert_eq!(receipt.target, "session_mock_42"); 360 assert_eq!(receipt.blake3_digest.len(), 64); 361 } 362 363 #[test] 364 fn test_isolate_host_generation() { 365 let receipt = isolate_host(999999).unwrap(); 366 assert_eq!(receipt.action, "IsolateHost"); 367 assert_eq!(receipt.target, "999999"); 368 assert_eq!(receipt.blake3_digest.len(), 64); 369 } 370 }