diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dcd4cea..c1f5b00 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -100,6 +100,7 @@ jobs: run: | npx vitest run tests/docker_roundtrip.test.ts npx vitest run tests/docker_security_hardening.test.ts + npx vitest run tests/evolve_docker.test.ts - name: Dump sandbox diagnostics on failure if: failure() diff --git a/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md b/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md index b5d3191..a61d809 100644 --- a/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md +++ b/plan/STAGE_8_EVOLVE_ADAPTIVE_DECEPTION_RUNTIME.md @@ -153,6 +153,71 @@ sandbox_runtime/ --- +## 6.1. Текущий implementation status + +Рабочая ветка: + +```text +stage-8-evolve-event-core +``` + +Текущее состояние: + +### Phase 8.1 - Event Core + +Реализовано: + +- `SecurityEvent`, `RiskLevel`, `EvolveState`, `EvolveSession`, `EvolveManager`; +- единый daemon event sink; +- event ingestion для canary, sync exec, background execution, browser и HTTP probe; +- route-level `PolicyViolation` events для RoE violations; +- единый `evolve_session_id` на audit scope со стороны Host MCP Bridge; +- canary trigger correlation с текущей behavioral session; +- устранён старый contract mismatch `token_label` / `base_dir`; +- stale canary watcher invalidation при повторном arm; +- manual emergency isolation синхронизирует `EvolveState::Isolate`; +- daemon observability routes для status, events, sessions и trace; +- live Docker Evolve regression scenario добавлен в CI. + +### Phase 8.2 - Behavior Layer + +Реализован baseline: + +- `BehaviorProfiler`; +- ordered `BehaviorTrace`; +- deterministic behavior tags; +- process lineage; +- resource lineage; +- destination lineage; +- deterministic risk score; +- contextual sequence correlation; +- conservative separation между credential interest и confirmed credential access; +- decision layer использует effective contextual risk. + +Текущая политика до появления Deception Fabric: + +```text +LOW -> OBSERVE +MEDIUM -> SUSPECT / enhanced telemetry +HIGH -> existing KillSwitch +CRITICAL -> existing KillSwitch +``` + +Это временный fail-closed режим. После Phase 8.3 безопасный `HIGH` path сможет переходить в `ENGAGE -> DECEIVE`. + +### Validation status + +GitHub Actions для текущего PR создаёт jobs, но runner не назначается: + +```text +runner_id: 0 +steps: [] +``` + +Поэтому CI сейчас завершается до checkout и не выполняет Rust/TypeScript/Docker код. Unit и live regression tests уже добавлены в ветку и должны быть прогнаны до merge при восстановлении runner availability. + +--- + ## 7. Implementation phases ### Phase 8.1 - Event Core diff --git a/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs b/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs new file mode 100644 index 0000000..62ea2d6 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-daemon/src/evolve_events.rs @@ -0,0 +1,62 @@ +use sandbox_kernel::SecurityEvent; +use tokio::sync::mpsc::UnboundedSender; +use tracing::warn; + +#[derive(Clone)] +pub struct EvolveEventSink { + sender: UnboundedSender, +} + +impl EvolveEventSink { + pub fn new(sender: UnboundedSender) -> Self { + Self { sender } + } + + pub fn sender(&self) -> UnboundedSender { + self.sender.clone() + } + + /// Best-effort telemetry delivery. + /// + /// Security enforcement must never depend on this return value. Route-level RoE checks + /// continue to deny locally, while canary has its own fail-closed fallback if the receiver + /// disappears. + pub fn emit(&self, event: SecurityEvent) -> bool { + let event_id = event.event_id.clone(); + if self.sender.send(event).is_ok() { + true + } else { + warn!(event_id = %event_id, "Evolve event receiver is unavailable"); + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use sandbox_kernel::{EventSource, SecurityEventType}; + use tokio::sync::mpsc; + + #[test] + fn sink_delivers_event_to_receiver() { + let (sender, mut receiver) = mpsc::unbounded_channel(); + let sink = EvolveEventSink::new(sender); + let event = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec); + + assert!(sink.emit(event)); + assert!(receiver.try_recv().is_ok()); + } + + #[test] + fn sink_reports_closed_receiver_without_panicking() { + let (sender, receiver) = mpsc::unbounded_channel(); + drop(receiver); + let sink = EvolveEventSink::new(sender); + let event = + SecurityEvent::new(EventSource::System, SecurityEventType::PolicyViolation); + + assert!(!sink.emit(event)); + } +} diff --git a/sandbox_runtime/crates/sandbox-daemon/src/main.rs b/sandbox_runtime/crates/sandbox-daemon/src/main.rs index ba53a5c..0c992b2 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/main.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/main.rs @@ -7,20 +7,23 @@ use serde_json::json; use std::io::{Error as IoError, ErrorKind}; use std::net::SocketAddr; use std::sync::Arc; -use tokio::sync::Mutex; +use tokio::sync::{mpsc, Mutex}; use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; -use tracing::{info, warn}; +use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; mod auth; +mod evolve_events; mod routes; use auth::{ratchet_auth_middleware, RatchetAuthState}; +use evolve_events::EvolveEventSink; use sandbox_kernel::canary::CanaryManager; use sandbox_kernel::{ apply_runtime_containment, audit_identity_conflicts_with_reserved_runtime_uid, - configured_audit_exec_identity, EgressConfig, EgressManager, + configured_audit_exec_identity, EgressConfig, EgressManager, EvolveDecision, EvolveManager, + KillSwitch, }; fn validate_runtime_identity_contract() -> Result<(), Box> { @@ -99,11 +102,65 @@ async fn main() -> Result<(), Box> { ) .expect("Failed to initialize RatchetAuthState"); - let canary_mgr = Arc::new(Mutex::new(CanaryManager::new())); + let evolve_mgr = Arc::new(Mutex::new(EvolveManager::new())); + let (evolve_event_tx, mut evolve_event_rx) = mpsc::unbounded_channel(); + let evolve_event_sink = EvolveEventSink::new(evolve_event_tx); + let canary_mgr = Arc::new(Mutex::new(CanaryManager::with_event_sender( + evolve_event_sink.sender(), + ))); + + // Canary and future sensors publish facts into the Evolve event pipeline. The Evolve manager + // decides the reaction. Until Deception Fabric exists, high-risk events intentionally retain + // the existing fail-closed isolation behavior. + let evolve_event_manager = evolve_mgr.clone(); + tokio::spawn(async move { + while let Some(event) = evolve_event_rx.recv().await { + let event_id = event.event_id.clone(); + let resource = event.resource.clone(); + let decision = { + let mut manager = evolve_event_manager.lock().await; + manager.ingest_event(event) + }; + + match decision { + EvolveDecision::Observe => { + info!(event_id = %event_id, "Evolve recorded low-risk security event"); + } + EvolveDecision::EnhancedTelemetry => { + warn!( + event_id = %event_id, + resource = ?resource, + "Evolve entered suspicious observation state" + ); + } + EvolveDecision::LegacyIsolate | EvolveDecision::Isolate => { + let reason = format!( + "Evolve security event requires isolation: event_id={event_id}, resource={resource:?}" + ); + match KillSwitch::trigger(&reason) { + Ok(()) => { + let mut manager = evolve_event_manager.lock().await; + manager.mark_isolated(); + } + Err(err) => { + // KillSwitch itself is responsible for fail-closed behavior when the + // kernel blackout cannot be installed. Keep a loud daemon-side trace. + error!( + event_id = %event_id, + error = %err, + "Evolve isolation request failed" + ); + } + } + } + } + } + }); let health_router = Router::new() .route("/health", get(handle_health)) - .layer(Extension(canary_mgr.clone())); + .layer(Extension(canary_mgr.clone())) + .layer(Extension(evolve_mgr.clone())); let protected_routes = Router::new() .route("/execute", post(routes::exec::handle_execute)) @@ -132,6 +189,14 @@ async fn main() -> Result<(), Box> { .route("/rotate_tor", post(routes::tor::handle_rotate_tor)) .route("/arm_canary", post(routes::canary::handle_arm_canary)) .route("/canary_status", get(routes::canary::handle_canary_status)) + .route( + "/evolve/enable", + post(routes::evolve::handle_set_enabled), + ) + .route("/evolve/status", get(routes::evolve::handle_status)) + .route("/evolve/sessions", get(routes::evolve::handle_sessions)) + .route("/evolve/trace", get(routes::evolve::handle_trace)) + .route("/evolve/events", get(routes::evolve::handle_events)) .route("/http_probe", post(routes::probe::handle_http_probe)) .route( "/browser_audit", @@ -141,7 +206,9 @@ async fn main() -> Result<(), Box> { auth_state.clone(), ratchet_auth_middleware, )) - .layer(Extension(canary_mgr)); + .layer(Extension(canary_mgr)) + .layer(Extension(evolve_mgr)) + .layer(Extension(evolve_event_sink)); let app = Router::new() .merge(health_router) @@ -159,15 +226,18 @@ async fn main() -> Result<(), Box> { async fn handle_health( Extension(canary_mgr): Extension>>, + Extension(evolve_mgr): Extension>>, ) -> Json { - let mgr = canary_mgr.lock().await; + let canary = canary_mgr.lock().await; + let evolve = evolve_mgr.lock().await; Json(json!({ "status": "ok", "service": "sandbox-daemon", "version": "0.1.0", "isolated": sandbox_kernel::KillSwitch::is_isolated(), - "canary_armed": mgr.is_armed(), - "canary_traps_count": mgr.get_traps().len(), - "canary_triggered_count": mgr.triggered_count() + "canary_armed": canary.is_armed(), + "canary_traps_count": canary.get_traps().len(), + "canary_triggered_count": canary.triggered_count(), + "evolve": evolve.status() })) } diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs index f0174ba..3be35d3 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/background.rs @@ -1,14 +1,17 @@ -use axum::{extract::Query, http::StatusCode, Json}; +use axum::{extract::Query, http::StatusCode, Extension, Json}; use serde::Deserialize; use serde_json::json; use tracing::info; +use crate::evolve_events::EvolveEventSink; use sandbox_kernel::tmux::TmuxManager; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; #[derive(Debug, Deserialize)] pub struct StartBackgroundRequest { pub command: String, pub session: Option, + pub evolve_session_id: Option, } #[derive(Debug, Deserialize)] @@ -17,7 +20,28 @@ pub struct PollLogsQuery { pub last_lines: Option, } +fn emit_background_event( + event_sink: &EvolveEventSink, + session_id: &str, + event_type: SecurityEventType, + command: Option<&str>, + result: &str, +) { + let mut event = SecurityEvent::new(EventSource::Process, event_type) + .with_session_id(session_id.to_string()) + .with_result(result.to_string()) + .with_risk_hint(RiskLevel::Low) + .with_metadata(json!({"execution_mode": "tmux_background"})); + + if let Some(command) = command { + event = event.with_command(command.to_string()); + } + + event_sink.emit(event); +} + pub async fn handle_start_background( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let session = payload.session.unwrap_or_else(|| { @@ -29,6 +53,9 @@ pub async fn handle_start_background( .as_secs() ) }); + let event_session_id = payload + .evolve_session_id + .unwrap_or_else(|| session.clone()); info!( "Starting background task in tmux session '{}': {}", @@ -36,15 +63,33 @@ pub async fn handle_start_background( ); match TmuxManager::start_session(&session, Some(&payload.command)) { - Ok(_) => Ok(Json(json!({ - "status": "started", - "session": session, - "command": payload.command - }))), - Err(e) => Err(( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({"error": format!("Failed to start background task: {}", e)})), - )), + Ok(_) => { + emit_background_event( + &event_sink, + &event_session_id, + SecurityEventType::ProcessExec, + Some(&payload.command), + "started", + ); + Ok(Json(json!({ + "status": "started", + "session": session, + "command": payload.command + }))) + } + Err(e) => { + emit_background_event( + &event_sink, + &event_session_id, + SecurityEventType::ProcessExit, + Some(&payload.command), + "spawn_error", + ); + Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": format!("Failed to start background task: {}", e)})), + )) + } } } @@ -70,6 +115,7 @@ pub async fn handle_poll_logs( } pub async fn handle_kill_background( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let session = payload @@ -78,7 +124,16 @@ pub async fn handle_kill_background( .unwrap_or("audit_session"); match TmuxManager::kill_session(session) { - Ok(_) => Ok(Json(json!({"status": "killed", "session": session}))), + Ok(_) => { + emit_background_event( + &event_sink, + session, + SecurityEventType::ProcessExit, + None, + "killed", + ); + Ok(Json(json!({"status": "killed", "session": session}))) + } Err(e) => Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("Failed to kill session: {}", e)})), diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs index 20380d8..f5e2ded 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/browser.rs @@ -1,4 +1,4 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use serde_json::Value; use std::process::Stdio; use std::time::Duration; @@ -6,7 +6,9 @@ use tokio::io::AsyncWriteExt; use tokio::process::Command; use tracing::{error, info}; +use crate::evolve_events::EvolveEventSink; use sandbox_kernel::browser_exec_identity; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; const SAFE_CHILD_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; const TOR_BROWSER_PROXY: &str = "socks5://127.0.0.1:9050"; @@ -44,6 +46,55 @@ fn has_forbidden_authority_header(config: &Value) -> bool { }) } +fn evolve_session_id(config: &Value) -> Option<&str> { + config.get("evolve_session_id").and_then(Value::as_str) +} + +fn requested_url(config: &Value) -> Option<&str> { + config.get("url").and_then(Value::as_str) +} + +fn emit_browser_event( + event_sink: &EvolveEventSink, + config: &Value, + event_type: SecurityEventType, + risk: RiskLevel, + result: &str, +) { + let mut event = SecurityEvent::new(EventSource::Browser, event_type) + .with_result(result.to_string()) + .with_risk_hint(risk); + + if let Some(session_id) = evolve_session_id(config) { + event = event.with_session_id(session_id.to_string()); + } + if let Some(url) = requested_url(config) { + event = event.with_destination(url.to_string()); + } + + event_sink.emit(event); +} + +fn emit_browser_policy_violation( + event_sink: &EvolveEventSink, + config: &Value, + reason: &str, +) { + let mut event = SecurityEvent::new(EventSource::Policy, SecurityEventType::PolicyViolation) + .with_resource("browser_audit") + .with_result(reason.to_string()) + .with_risk_hint(RiskLevel::Medium); + + if let Some(session_id) = evolve_session_id(config) { + event = event.with_session_id(session_id.to_string()); + } + if let Some(url) = requested_url(config) { + event = event.with_destination(url.to_string()); + } + + event_sink.emit(event); +} + fn proxy_is_managed_tor(config: &Value) -> bool { config .get("proxy") @@ -55,9 +106,15 @@ fn proxy_is_managed_tor(config: &Value) -> bool { } pub async fn handle_browser_audit( + Extension(event_sink): Extension, Json(config): Json, ) -> Result, (StatusCode, Json)> { if !has_scope_hosts(&config) { + emit_browser_policy_violation( + &event_sink, + &config, + "browser request missing explicit RoE host allowlist", + ); return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -66,6 +123,11 @@ pub async fn handle_browser_audit( )); } if has_proxy(&config) && !proxy_is_managed_tor(&config) { + emit_browser_policy_violation( + &event_sink, + &config, + "browser attempted unmanaged proxy transport", + ); return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -74,6 +136,11 @@ pub async fn handle_browser_audit( )); } if has_forbidden_authority_header(&config) { + emit_browser_policy_violation( + &event_sink, + &config, + "browser attempted Host/:authority override", + ); return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -82,6 +149,14 @@ pub async fn handle_browser_audit( )); } + emit_browser_event( + &event_sink, + &config, + SecurityEventType::BrowserNavigation, + RiskLevel::Low, + "started", + ); + let config_bytes = serde_json::to_vec(&config).map_err(|e| { ( StatusCode::BAD_REQUEST, @@ -162,6 +237,13 @@ pub async fn handle_browser_audit( ) })?; + emit_browser_event( + &event_sink, + &config, + SecurityEventType::BrowserNavigation, + RiskLevel::Low, + "completed", + ); info!("Browser audit completed successfully"); Ok(Json(report)) } diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs index edc44ed..89f6d21 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/canary.rs @@ -11,6 +11,7 @@ use sandbox_kernel::canary::CanaryManager; #[derive(Debug, Deserialize)] pub struct ArmCanaryRequest { pub base_dir: Option, + pub evolve_session_id: Option, } pub async fn handle_arm_canary( @@ -24,7 +25,10 @@ pub async fn handle_arm_canary( ); let mut mgr = canary_mgr.lock().await; - match mgr.arm_canaries(&base_path).await { + match mgr + .arm_canaries_for_session(&base_path, payload.evolve_session_id) + .await + { Ok(traps) => { let traps_summary: Vec<_> = traps .iter() diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs index b7fd85b..b9caaf2 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/egress.rs @@ -1,12 +1,19 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use serde::Deserialize; use serde_json::json; +use std::sync::Arc; +use tokio::sync::Mutex; use tracing::{error, info, warn}; +use crate::evolve_events::EvolveEventSink; + use sandbox_kernel::containment::apply_runtime_containment_with_agent_allowlist; use sandbox_kernel::egress::{is_valid_ip_or_cidr, EgressConfig, EgressError, EgressManager}; use sandbox_kernel::panic::KillSwitch; use sandbox_kernel::stop_tor_best_effort; +use sandbox_kernel::{ + EventSource, EvolveManager, RiskLevel, SecurityEvent, SecurityEventType, +}; #[derive(Debug, Deserialize)] pub struct EmergencyIsolateRequest { @@ -21,6 +28,15 @@ pub struct ProvisionEgressRequest { pub agent_allowed_cidrs: Vec, } +fn emit_egress_policy_violation(event_sink: &EvolveEventSink, reason: &str) { + event_sink.emit( + SecurityEvent::new(EventSource::Policy, SecurityEventType::PolicyViolation) + .with_resource("egress_scope") + .with_result(reason.to_string()) + .with_risk_hint(RiskLevel::Medium), + ); +} + fn bad_request(message: impl Into) -> (StatusCode, Json) { ( StatusCode::BAD_REQUEST, @@ -53,6 +69,7 @@ fn validate_agent_allowlist( } pub async fn handle_provision_egress( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let ProvisionEgressRequest { @@ -63,24 +80,31 @@ pub async fn handle_provision_egress( info!("Provisioning egress rules for mode: {:?}", config.mode); if config.proxy_enabled || config.proxy_target.is_some() { - return Err(bad_request( - "External upstream proxy containment is not implemented safely; only managed Tor is supported", - )); + let reason = + "External upstream proxy containment is not implemented safely; only managed Tor is supported"; + emit_egress_policy_violation(&event_sink, reason); + return Err(bad_request(reason)); } if config.tor_enabled && config.targets.is_empty() { - return Err(bad_request( - "Tor egress requires at least one explicit target; transport alone is not audit scope", - )); + let reason = + "Tor egress requires at least one explicit target; transport alone is not audit scope"; + emit_egress_policy_violation(&event_sink, reason); + return Err(bad_request(reason)); } if let Err(message) = validate_agent_allowlist(&config, &agent_allowed_cidrs) { + emit_egress_policy_violation(&event_sink, &message); return Err(bad_request(message)); } let manager = EgressManager::new(); if let Err(e) = manager.apply_rules(&config) { error!("Failed to apply egress rules: {}", e); - let status = match e { + let status = match &e { EgressError::InvalidAddress(_) | EgressError::InvalidPolicy(_) => { + emit_egress_policy_violation( + &event_sink, + &format!("Rejected invalid egress policy: {e}"), + ); StatusCode::BAD_REQUEST } _ => StatusCode::INTERNAL_SERVER_ERROR, @@ -116,6 +140,7 @@ pub async fn handle_provision_egress( } pub async fn handle_emergency_isolate( + Extension(evolve_mgr): Extension>>, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let reason = payload @@ -124,11 +149,15 @@ pub async fn handle_emergency_isolate( warn!("Emergency isolation request received: {}", reason); match KillSwitch::trigger(&reason) { - Ok(_) => Ok(Json(json!({ - "status": "isolated", - "reason": reason, - "is_isolated": true - }))), + Ok(_) => { + let mut manager = evolve_mgr.lock().await; + manager.mark_isolated(); + Ok(Json(json!({ + "status": "isolated", + "reason": reason, + "is_isolated": true + }))) + } Err(e) => Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("Failed to trigger kill switch: {}", e)})), diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs new file mode 100644 index 0000000..ba676de --- /dev/null +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/evolve.rs @@ -0,0 +1,80 @@ +use axum::{extract::Query, http::StatusCode, Extension, Json}; +use serde::Deserialize; +use serde_json::json; +use std::sync::Arc; +use tokio::sync::Mutex; + +use sandbox_kernel::EvolveManager; + +#[derive(Debug, Deserialize)] +pub struct SetEvolveEnabledRequest { + pub enabled: bool, +} + +#[derive(Debug, Deserialize)] +pub struct EventsQuery { + pub limit: Option, +} + +#[derive(Debug, Deserialize)] +pub struct TraceQuery { + pub session_id: String, +} + +pub async fn handle_set_enabled( + Extension(evolve_mgr): Extension>>, + Json(payload): Json, +) -> Result, (StatusCode, Json)> { + if payload.enabled && sandbox_kernel::KillSwitch::is_isolated() { + return Err(( + StatusCode::CONFLICT, + Json(json!({ + "error": "cannot enable Evolve while the runtime is isolated; recreate or reset the sandbox first" + })), + )); + } + + let mut manager = evolve_mgr.lock().await; + manager.set_enabled(payload.enabled); + Ok(Json(json!(manager.status()))) +} + +pub async fn handle_status( + Extension(evolve_mgr): Extension>>, +) -> Json { + let manager = evolve_mgr.lock().await; + Json(json!(manager.status())) +} + +pub async fn handle_sessions( + Extension(evolve_mgr): Extension>>, +) -> Json { + let manager = evolve_mgr.lock().await; + Json(json!({"sessions": manager.sessions()})) +} + +pub async fn handle_trace( + Extension(evolve_mgr): Extension>>, + Query(query): Query, +) -> Result, (StatusCode, Json)> { + let manager = evolve_mgr.lock().await; + match manager.behavior_trace(&query.session_id) { + Some(trace) => Ok(Json(json!(trace))), + None => Err(( + StatusCode::NOT_FOUND, + Json(json!({"error": "Evolve behavior trace not found"})), + )), + } +} + +pub async fn handle_events( + Extension(evolve_mgr): Extension>>, + Query(query): Query, +) -> Json { + let limit = query.limit.unwrap_or(100).min(1000); + let manager = evolve_mgr.lock().await; + Json(json!({ + "events": manager.recent_events(limit), + "limit": limit + })) +} diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs index c8cdff3..3c46b02 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/exec.rs @@ -1,4 +1,4 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use serde::{Deserialize, Serialize}; use serde_json::json; #[cfg(unix)] @@ -9,10 +9,12 @@ use tokio::process::Command; use tokio::time::timeout; use tracing::{error, info, warn}; +use crate::evolve_events::EvolveEventSink; #[cfg(not(target_os = "windows"))] use sandbox_kernel::audit_exec_identity; use sandbox_kernel::tmux::TmuxManager; use sandbox_kernel::watchdog::{process_command_output, WatchdogResult}; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; const SAFE_CHILD_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; @@ -21,6 +23,7 @@ pub struct ExecRequest { pub command: String, pub timeout_secs: Option, pub work_dir: Option, + pub evolve_session_id: Option, } #[derive(Debug, Serialize)] @@ -38,11 +41,44 @@ pub struct InteractiveTmuxRequest { pub input: String, } +fn emit_exec_event( + event_sink: &EvolveEventSink, + session_id: Option<&str>, + event_type: SecurityEventType, + command: &str, + work_dir: &str, + result: Option, + process_id: Option, + metadata: serde_json::Value, +) { + let mut event = SecurityEvent::new(EventSource::Process, event_type) + .with_command(command.to_string()) + .with_resource(work_dir.to_string()) + .with_risk_hint(RiskLevel::Low) + .with_metadata(metadata); + + if let Some(session_id) = session_id { + event = event.with_session_id(session_id.to_string()); + } + if let Some(result) = result { + event = event.with_result(result); + } + if let Some(process_id) = process_id { + event = event.with_process(process_id, Some(std::process::id())); + } + + event_sink.emit(event); +} + pub async fn handle_execute( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { - let timeout_duration = Duration::from_secs(payload.timeout_secs.unwrap_or(60)); + let timeout_secs = payload.timeout_secs.unwrap_or(60); + let timeout_duration = Duration::from_secs(timeout_secs); let work_dir = payload.work_dir.unwrap_or_else(|| "/workspace".to_string()); + let command_text = payload.command; + let evolve_session_id = payload.evolve_session_id; let cmd_id = format!( "exec_{}", std::time::SystemTime::now() @@ -51,27 +87,39 @@ pub async fn handle_execute( .as_millis() ); + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessSpawn, + &command_text, + &work_dir, + Some("requested".to_string()), + None, + json!({ + "execution_mode": "sync", + "timeout_secs": timeout_secs, + "command_id": cmd_id + }), + ); + info!("Executing unprivileged audit command in '{}'", work_dir); #[cfg(target_os = "windows")] let mut cmd = { let mut c = Command::new("powershell"); - c.args(["-NoProfile", "-Command", &payload.command]); + c.args(["-NoProfile", "-Command", &command_text]); c }; #[cfg(not(target_os = "windows"))] let mut cmd = { let mut c = Command::new("/bin/sh"); - c.args(["-c", &payload.command]); + c.args(["-c", &command_text]); let (uid, gid) = audit_exec_identity(); #[cfg(unix)] { c.as_std_mut().uid(uid).gid(gid); } - // The daemon carries control-plane trust material in its environment. Agent-controlled - // children must receive a clean environment so BRIDGE_SESSION_KEY_HEX/HOST_PUBKEY_HEX and - // future daemon secrets can never be recovered with `env` or /proc/self/environ. c.env_clear(); c.env("HOME", "/tmp"); c.env("PATH", SAFE_CHILD_PATH); @@ -82,23 +130,81 @@ pub async fn handle_execute( if std::path::Path::new(&work_dir).exists() { cmd.current_dir(&work_dir); } + cmd.kill_on_drop(true); - let output = match timeout(timeout_duration, cmd.output()).await { - Ok(Ok(output)) => output, - Ok(Err(e)) => { + let child = match cmd.spawn() { + Ok(child) => child, + Err(e) => { + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some("spawn_error".to_string()), + None, + json!({"command_id": cmd_id}), + ); error!("Command execution failed: {}", e); return Err(( StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("Command spawn failed: {}", e)})), )); } + }; + + let process_id = child.id(); + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExec, + &command_text, + &work_dir, + Some("started".to_string()), + process_id, + json!({ + "execution_mode": "sync", + "command_id": cmd_id + }), + ); + + let output = match timeout(timeout_duration, child.wait_with_output()).await { + Ok(Ok(output)) => output, + Ok(Err(e)) => { + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some("wait_error".to_string()), + process_id, + json!({"command_id": cmd_id}), + ); + error!("Command wait failed: {}", e); + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": format!("Command wait failed: {}", e)})), + )); + } Err(_) => { + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some("timeout".to_string()), + process_id, + json!({ + "command_id": cmd_id, + "timeout_secs": timeout_secs + }), + ); warn!("Command execution timed out after {:?}", timeout_duration); return Err(( StatusCode::GATEWAY_TIMEOUT, - Json( - json!({"error": format!("Command timed out after {}s", timeout_duration.as_secs())}), - ), + Json(json!({"error": format!("Command timed out after {}s", timeout_secs)})), )); } }; @@ -122,6 +228,22 @@ pub async fn handle_execute( log_file_path: None, }); + emit_exec_event( + &event_sink, + evolve_session_id.as_deref(), + SecurityEventType::ProcessExit, + &command_text, + &work_dir, + Some(format!("exit_code={exit_code}")), + process_id, + json!({ + "command_id": cmd_id, + "is_truncated": watchdog_res.is_truncated, + "total_chars": watchdog_res.total_chars, + "log_file_path": watchdog_res.log_file_path + }), + ); + Ok(Json(ExecResponse { output: watchdog_res.output, exit_code, @@ -139,6 +261,9 @@ pub async fn handle_interactive_tmux( .unwrap_or_else(|| "audit_session".to_string()); info!("Sending interactive input to tmux session '{}'", session); + // Interactive input is intentionally not copied into Evolve telemetry because it may contain + // passwords, tokens or other secrets. Process-level tmux lifecycle remains observable through + // background session events. match TmuxManager::send_input(&session, &payload.input) { Ok(_) => Ok(Json(json!({"status": "success", "session": session}))), Err(e) => Err(( diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs index 29ba0c3..c712568 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/mod.rs @@ -2,6 +2,7 @@ pub mod background; pub mod browser; pub mod canary; pub mod egress; +pub mod evolve; pub mod exec; pub mod probe; pub mod tor; diff --git a/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs b/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs index 45821f1..d67981d 100644 --- a/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs +++ b/sandbox_runtime/crates/sandbox-daemon/src/routes/probe.rs @@ -1,4 +1,4 @@ -use axum::{http::StatusCode, Json}; +use axum::{http::StatusCode, Extension, Json}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -7,6 +7,9 @@ use std::io::{Error as IoError, ErrorKind}; use std::time::{Duration, Instant}; use tracing::{error, info}; +use crate::evolve_events::EvolveEventSink; +use sandbox_kernel::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; + const TOR_BROWSER_PROXY: &str = "socks5://127.0.0.1:9050"; const TOR_HTTP_PROXY: &str = "socks5h://127.0.0.1:9050"; @@ -19,6 +22,7 @@ pub struct ProbeRequest { pub proxy: Option, pub timeout_secs: Option, pub allowed_hosts: Option>, + pub evolve_session_id: Option, } #[derive(Debug, Serialize)] @@ -73,11 +77,50 @@ fn has_forbidden_authority_header(headers: Option<&HashMap>) -> }) } +fn emit_probe_event( + event_sink: &EvolveEventSink, + payload: &ProbeRequest, + event_type: SecurityEventType, + source: EventSource, + risk: RiskLevel, + result: &str, +) { + let mut event = SecurityEvent::new(source, event_type) + .with_destination(payload.url.clone()) + .with_result(result.to_string()) + .with_risk_hint(risk) + .with_metadata(json!({ + "method": payload.method.as_deref().unwrap_or("GET").to_uppercase() + })); + + if let Some(session_id) = payload.evolve_session_id.as_deref() { + event = event.with_session_id(session_id.to_string()); + } + + event_sink.emit(event); +} + +fn emit_probe_policy_violation( + event_sink: &EvolveEventSink, + payload: &ProbeRequest, + reason: &str, +) { + emit_probe_event( + event_sink, + payload, + SecurityEventType::PolicyViolation, + EventSource::Policy, + RiskLevel::Medium, + reason, + ); +} + fn proxy_is_managed_tor(proxy: &str) -> bool { matches!(proxy.trim(), TOR_BROWSER_PROXY | TOR_HTTP_PROXY) } pub async fn handle_http_probe( + Extension(event_sink): Extension, Json(payload): Json, ) -> Result, (StatusCode, Json)> { let method_str = payload.method.as_deref().unwrap_or("GET").to_uppercase(); @@ -85,6 +128,11 @@ pub async fn handle_http_probe( let allowed_hosts = normalize_allowed_hosts(payload.allowed_hosts.clone()); if allowed_hosts.is_empty() { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe missing explicit RoE host allowlist", + ); return Err(( StatusCode::BAD_REQUEST, Json(json!({ @@ -93,6 +141,11 @@ pub async fn handle_http_probe( )); } if has_forbidden_authority_header(payload.headers.as_ref()) { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe attempted Host/:authority override", + ); return Err(( StatusCode::BAD_REQUEST, Json(json!({ @@ -102,6 +155,11 @@ pub async fn handle_http_probe( } if let Some(proxy) = payload.proxy.as_deref() { if !proxy_is_managed_tor(proxy) { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe attempted unmanaged proxy transport", + ); return Err(( StatusCode::BAD_REQUEST, Json(json!({ @@ -118,12 +176,26 @@ pub async fn handle_http_probe( ) })?; if !url_matches_scope(&parsed_target, &allowed_hosts) { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe URL is outside active RoE host scope", + ); return Err(( StatusCode::FORBIDDEN, Json(json!({"error": "Probe URL is outside the active RoE host scope"})), )); } + emit_probe_event( + &event_sink, + &payload, + SecurityEventType::HttpRequest, + EventSource::HttpProbe, + RiskLevel::Low, + "started", + ); + info!( "Sending HTTP probe: {} {} (proxy: {:?}, scope_hosts: {})", method_str, @@ -203,12 +275,12 @@ pub async fn handle_http_probe( } }; - if let Some(headers_map) = payload.headers { + if let Some(headers_map) = payload.headers.as_ref() { let mut header_map = HeaderMap::new(); for (k, v) in headers_map { if let (Ok(h_name), Ok(h_val)) = ( HeaderName::from_bytes(k.as_bytes()), - HeaderValue::from_str(&v), + HeaderValue::from_str(v), ) { header_map.insert(h_name, h_val); } @@ -216,14 +288,29 @@ pub async fn handle_http_probe( req_builder = req_builder.headers(header_map); } - if let Some(body_content) = payload.body { - req_builder = req_builder.body(body_content); + if let Some(body_content) = payload.body.as_ref() { + req_builder = req_builder.body(body_content.clone()); } let start_time = Instant::now(); let response = match req_builder.send().await { Ok(resp) => resp, Err(e) => { + if e.to_string().contains("outside active RoE scope") { + emit_probe_policy_violation( + &event_sink, + &payload, + "HTTP probe redirect attempted to leave active RoE host scope", + ); + } + emit_probe_event( + &event_sink, + &payload, + SecurityEventType::HttpRequest, + EventSource::HttpProbe, + RiskLevel::Low, + "request_failed", + ); error!("HTTP probe failed for {}: {}", payload.url, e); return Err(( StatusCode::BAD_GATEWAY, @@ -274,6 +361,15 @@ pub async fn handle_http_probe( _ => false, }; + emit_probe_event( + &event_sink, + &payload, + SecurityEventType::HttpRequest, + EventSource::HttpProbe, + RiskLevel::Low, + &format!("status={status}"), + ); + Ok(Json(ProbeResponse { status, headers: resp_headers, diff --git a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs index 5e748f3..cee28a0 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/canary.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/canary.rs @@ -1,11 +1,13 @@ use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use thiserror::Error; use tokio::fs; +use tokio::sync::mpsc::UnboundedSender; use tracing::{error, info}; +use crate::evolve::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; use crate::panic::KillSwitch; #[derive(Error, Debug)] @@ -27,6 +29,8 @@ pub struct CanaryManager { traps: Vec, is_armed: Arc, triggered_count: Arc, + watch_generation: Arc, + event_sender: Option>, } impl Default for CanaryManager { @@ -41,11 +45,32 @@ impl CanaryManager { traps: Vec::new(), is_armed: Arc::new(AtomicBool::new(false)), triggered_count: Arc::new(AtomicUsize::new(0)), + watch_generation: Arc::new(AtomicU64::new(0)), + event_sender: None, } } - /// Plants deceptive honeytoken files into the target filesystem + /// Creates a canary manager whose trip events are delegated to the Evolve event pipeline. + /// + /// If the receiver disappears, canary handling fails closed and falls back to KillSwitch. + pub fn with_event_sender(event_sender: UnboundedSender) -> Self { + Self { + event_sender: Some(event_sender), + ..Self::new() + } + } + + /// Plants deceptive honeytoken files into the target filesystem. pub async fn arm_canaries(&mut self, base_dir: &Path) -> Result, CanaryError> { + self.arm_canaries_for_session(base_dir, None).await + } + + /// Plants canaries and associates future trigger events with a behavioral Evolve session. + pub async fn arm_canaries_for_session( + &mut self, + base_dir: &Path, + session_id: Option, + ) -> Result, CanaryError> { let mut planted = Vec::new(); // 1. AWS Credentials Honeypot @@ -143,35 +168,53 @@ users: self.traps = planted.clone(); self.is_armed.store(true, Ordering::SeqCst); + let generation = self.watch_generation.fetch_add(1, Ordering::SeqCst) + 1; - // Spawn background file access monitor - self.spawn_watcher(planted.clone()); + self.spawn_watcher(planted.clone(), session_id, generation); info!("Armed {} canary honeytoken tripwires.", planted.len()); Ok(planted) } - fn spawn_watcher(&self, traps: Vec) { + fn spawn_watcher( + &self, + traps: Vec, + session_id: Option, + generation: u64, + ) { let is_armed = self.is_armed.clone(); let triggered_count = self.triggered_count.clone(); + let watch_generation = self.watch_generation.clone(); + let event_sender = self.event_sender.clone(); tokio::spawn(async move { - info!("Canary inotify/access watcher loop started."); + info!("Canary metadata watcher loop started."); - // Record initial metadata timestamps and size - let mut initial_meta: Vec<(PathBuf, u64, Option)> = Vec::new(); + // Phase 8.1 keeps the existing metadata polling source and decouples its reaction. + // EVENT_MODEL.md tracks the later migration to fanotify/inotify. + let mut initial_meta: Vec<( + PathBuf, + String, + u64, + Option, + )> = Vec::new(); for trap in &traps { if let Ok(meta) = std::fs::metadata(&trap.file_path) { - let len = meta.len(); - let accessed = meta.accessed().ok(); - initial_meta.push((trap.file_path.clone(), len, accessed)); + initial_meta.push(( + trap.file_path.clone(), + trap.trap_type.clone(), + meta.len(), + meta.accessed().ok(), + )); } } - while is_armed.load(Ordering::SeqCst) { + while is_armed.load(Ordering::SeqCst) + && watch_generation.load(Ordering::SeqCst) == generation + { tokio::time::sleep(Duration::from_millis(500)).await; - for (path, orig_len, orig_accessed) in &initial_meta { + for (path, trap_type, orig_len, orig_accessed) in &initial_meta { if let Ok(meta) = std::fs::metadata(path) { let current_len = meta.len(); let current_accessed = meta.accessed().ok(); @@ -183,11 +226,16 @@ users: }; if modified || accessed { - triggered_count.fetch_add(1, Ordering::SeqCst); - error!("TRIPWIRE TRIGGERED! Unauthorized access or modification on canary: {:?}", path); - let _ = - KillSwitch::trigger(&format!("Canary trap triggered: {:?}", path)); - is_armed.store(false, Ordering::SeqCst); + handle_canary_trigger( + event_sender.as_ref(), + triggered_count.as_ref(), + path, + trap_type, + session_id.as_deref(), + ); + if watch_generation.load(Ordering::SeqCst) == generation { + is_armed.store(false, Ordering::SeqCst); + } return; } } @@ -207,12 +255,54 @@ users: pub fn get_traps(&self) -> &[CanaryTrap] { &self.traps } + + pub fn watch_generation(&self) -> u64 { + self.watch_generation.load(Ordering::SeqCst) + } +} + +fn handle_canary_trigger( + event_sender: Option<&UnboundedSender>, + triggered_count: &AtomicUsize, + path: &Path, + trap_type: &str, + session_id: Option<&str>, +) { + triggered_count.fetch_add(1, Ordering::SeqCst); + error!( + "TRIPWIRE TRIGGERED! Unauthorized access or modification on canary: {:?}", + path + ); + + let mut event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + .with_resource(path.to_string_lossy().into_owned()) + .with_risk_hint(RiskLevel::High) + .with_metadata(serde_json::json!({ + "trap_type": trap_type, + "legacy_reaction": "isolate" + })); + if let Some(session_id) = session_id { + event = event.with_session_id(session_id.to_string()); + } + + if let Some(sender) = event_sender { + if sender.send(event).is_ok() { + return; + } + + error!("Evolve event receiver unavailable; falling back to emergency isolation."); + } + + // Compatibility/failure fallback. The daemon uses the event-driven path, but a standalone + // CanaryManager without an Evolve receiver must preserve the old fail-closed behavior. + let _ = KillSwitch::trigger(&format!("Canary trap triggered: {:?}", path)); } #[cfg(test)] mod tests { use super::*; use tempfile::TempDir; + use tokio::sync::mpsc; #[tokio::test] async fn test_arm_canaries() { @@ -228,4 +318,40 @@ mod tests { assert!(trap.file_path.exists()); } } + + #[tokio::test] + async fn rearm_advances_watcher_generation() { + let temp_dir = TempDir::new().unwrap(); + let mut manager = CanaryManager::new(); + + manager.arm_canaries(temp_dir.path()).await.unwrap(); + let first_generation = manager.watch_generation(); + manager.arm_canaries(temp_dir.path()).await.unwrap(); + let second_generation = manager.watch_generation(); + + assert!(second_generation > first_generation); + } + + #[tokio::test] + async fn trigger_emits_evolve_event_when_receiver_exists() { + let (sender, mut receiver) = mpsc::unbounded_channel(); + let triggered_count = AtomicUsize::new(0); + let path = Path::new("/workspace/.env.decoy"); + + handle_canary_trigger( + Some(&sender), + &triggered_count, + path, + "env_secrets", + Some("audit-session-1"), + ); + + let event = receiver.recv().await.expect("expected canary event"); + assert_eq!(triggered_count.load(Ordering::SeqCst), 1); + assert_eq!(event.source, EventSource::Canary); + assert_eq!(event.event_type, SecurityEventType::CanaryAccess); + assert_eq!(event.resource.as_deref(), Some("/workspace/.env.decoy")); + assert_eq!(event.session_id.as_deref(), Some("audit-session-1")); + assert_eq!(event.risk_hint, Some(RiskLevel::High)); + } } diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs new file mode 100644 index 0000000..9432732 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/behavior.rs @@ -0,0 +1,422 @@ +use super::{RiskLevel, SecurityEvent, SecurityEventType}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; + +const DEFAULT_TRACE_EVENT_CAPACITY: usize = 256; +const DEFAULT_SESSION_ID: &str = "runtime-default"; + +fn default_trace_event_capacity() -> usize { + DEFAULT_TRACE_EVENT_CAPACITY +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BehaviorTag { + Execution, + Discovery, + CredentialInterest, + CredentialAccess, + NetworkActivity, + BrowserActivity, + PolicyBoundary, + PrivilegeActivity, + PersistenceActivity, + LateralMovement, + CanaryInteraction, + EscapeActivity, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BehaviorAssessment { + pub risk_level: RiskLevel, + pub risk_score: u8, + pub tags: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BehaviorTrace { + pub session_id: String, + pub started_at_ms: u64, + pub last_event_at_ms: u64, + pub risk_level: RiskLevel, + pub risk_score: u8, + pub tags: BTreeSet, + pub process_lineage: BTreeMap>, + pub resources: BTreeSet, + pub destinations: BTreeSet, + pub events: VecDeque, + #[serde(skip, default = "default_trace_event_capacity")] + event_capacity: usize, +} + +impl BehaviorTrace { + fn new(session_id: impl Into, first_timestamp_ms: u64, event_capacity: usize) -> Self { + Self { + session_id: session_id.into(), + started_at_ms: first_timestamp_ms, + last_event_at_ms: first_timestamp_ms, + risk_level: RiskLevel::Low, + risk_score: risk_score(RiskLevel::Low), + tags: BTreeSet::new(), + process_lineage: BTreeMap::new(), + resources: BTreeSet::new(), + destinations: BTreeSet::new(), + events: VecDeque::with_capacity(event_capacity), + event_capacity, + } + } + + fn push_event(&mut self, event: SecurityEvent) { + self.last_event_at_ms = event.timestamp_ms; + if self.events.len() >= self.event_capacity { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + +pub struct BehaviorProfiler { + traces: HashMap, + event_capacity: usize, +} + +impl Default for BehaviorProfiler { + fn default() -> Self { + Self::new() + } +} + +impl BehaviorProfiler { + pub fn new() -> Self { + Self { + traces: HashMap::new(), + event_capacity: DEFAULT_TRACE_EVENT_CAPACITY, + } + } + + pub fn observe(&mut self, event: &SecurityEvent) -> BehaviorAssessment { + let session_id = event + .session_id + .as_deref() + .unwrap_or(DEFAULT_SESSION_ID) + .to_string(); + let mut tags = classify_event(event); + let base_risk = deterministic_event_risk(event); + + let event_capacity = self.event_capacity; + let trace = self.traces.entry(session_id.clone()).or_insert_with(|| { + BehaviorTrace::new(session_id, event.timestamp_ms, event_capacity) + }); + + let sequence_risk = sequence_risk(trace, event, &tags); + let effective_risk = max_risk(base_risk, sequence_risk); + + for tag in &tags { + trace.tags.insert(*tag); + } + if effective_risk.rank() > trace.risk_level.rank() { + trace.risk_level = effective_risk; + trace.risk_score = risk_score(effective_risk); + } + + if let Some(process_id) = event.process_id { + trace + .process_lineage + .insert(process_id, event.parent_process_id); + } + if let Some(resource) = event.resource.as_ref() { + trace.resources.insert(resource.clone()); + } + if let Some(destination) = event.destination.as_ref() { + trace.destinations.insert(destination.clone()); + } + + let mut normalized_event = event.clone(); + normalized_event.risk_hint = Some(effective_risk); + trace.push_event(normalized_event); + + tags.sort(); + tags.dedup(); + + BehaviorAssessment { + risk_level: effective_risk, + risk_score: risk_score(effective_risk), + tags, + } + } + + pub fn trace(&self, session_id: &str) -> Option<&BehaviorTrace> { + self.traces.get(session_id) + } + + pub fn trace_count(&self) -> usize { + self.traces.len() + } + + pub fn traces(&self) -> Vec { + let mut traces: Vec<_> = self.traces.values().cloned().collect(); + traces.sort_by(|left, right| left.started_at_ms.cmp(&right.started_at_ms)); + traces + } +} + +fn risk_score(level: RiskLevel) -> u8 { + match level { + RiskLevel::Low => 10, + RiskLevel::Medium => 45, + RiskLevel::High => 80, + RiskLevel::Critical => 100, + } +} + +fn max_risk(left: RiskLevel, right: RiskLevel) -> RiskLevel { + if left.rank() >= right.rank() { + left + } else { + right + } +} + +fn deterministic_event_risk(event: &SecurityEvent) -> RiskLevel { + let hinted = event.risk_hint.unwrap_or(RiskLevel::Low); + let structural = match event.event_type { + SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess => { + RiskLevel::Critical + } + SecurityEventType::CanaryAccess + | SecurityEventType::CredentialAccess + | SecurityEventType::PrivilegeAttempt + | SecurityEventType::PersistenceAttempt + | SecurityEventType::LateralMovementAttempt => RiskLevel::High, + SecurityEventType::PolicyViolation => RiskLevel::Medium, + _ => RiskLevel::Low, + }; + + max_risk(hinted, structural) +} + +fn classify_event(event: &SecurityEvent) -> Vec { + let mut tags = Vec::new(); + + match event.event_type { + SecurityEventType::ProcessSpawn + | SecurityEventType::ProcessExec + | SecurityEventType::ProcessExit => tags.push(BehaviorTag::Execution), + SecurityEventType::Discovery => tags.push(BehaviorTag::Discovery), + SecurityEventType::CredentialAccess => { + tags.push(BehaviorTag::CredentialInterest); + tags.push(BehaviorTag::CredentialAccess); + }, + SecurityEventType::NetworkConnect + | SecurityEventType::NetworkListen + | SecurityEventType::DnsAttempt + | SecurityEventType::HttpRequest => tags.push(BehaviorTag::NetworkActivity), + SecurityEventType::BrowserNavigation => tags.push(BehaviorTag::BrowserActivity), + SecurityEventType::PolicyViolation => tags.push(BehaviorTag::PolicyBoundary), + SecurityEventType::PrivilegeAttempt => tags.push(BehaviorTag::PrivilegeActivity), + SecurityEventType::PersistenceAttempt => tags.push(BehaviorTag::PersistenceActivity), + SecurityEventType::LateralMovementAttempt => tags.push(BehaviorTag::LateralMovement), + SecurityEventType::CanaryAccess => { + tags.push(BehaviorTag::CanaryInteraction); + tags.push(BehaviorTag::CredentialInterest); + tags.push(BehaviorTag::CredentialAccess); + } + SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess => { + tags.push(BehaviorTag::EscapeActivity); + } + _ => {} + } + + if let Some(command) = event.command.as_deref() { + classify_command(command, &mut tags); + } + + tags +} + +fn classify_command(command: &str, tags: &mut Vec) { + let normalized = command.trim().to_ascii_lowercase(); + let first = normalized.split_whitespace().next().unwrap_or_default(); + + if matches!( + first, + "whoami" + | "id" + | "uname" + | "hostname" + | "ip" + | "ifconfig" + | "netstat" + | "ss" + | "ps" + | "env" + | "printenv" + | "mount" + | "df" + ) { + tags.push(BehaviorTag::Discovery); + } + + if matches!(first, "curl" | "wget" | "nc" | "ncat" | "ssh") { + tags.push(BehaviorTag::NetworkActivity); + } + + if normalized.contains(".ssh/") + || normalized.contains(".aws/credentials") + || normalized.contains(".kube/config") + || normalized.contains(".env") + { + tags.push(BehaviorTag::CredentialInterest); + } +} + +fn sequence_risk( + trace: &BehaviorTrace, + event: &SecurityEvent, + current_tags: &[BehaviorTag], +) -> RiskLevel { + if matches!( + event.event_type, + SecurityEventType::EscapeAttempt | SecurityEventType::ControlPlaneAccess + ) { + return RiskLevel::Critical; + } + + let previous_tags = &trace.tags; + let discovery_then_network = previous_tags.contains(&BehaviorTag::Discovery) + && current_tags.contains(&BehaviorTag::NetworkActivity); + let credential_access_then_network = previous_tags.contains(&BehaviorTag::CredentialAccess) + && current_tags.contains(&BehaviorTag::NetworkActivity); + let credential_interest_then_network = + previous_tags.contains(&BehaviorTag::CredentialInterest) + && current_tags.contains(&BehaviorTag::NetworkActivity); + let repeated_policy_boundary = previous_tags.contains(&BehaviorTag::PolicyBoundary) + && current_tags.contains(&BehaviorTag::PolicyBoundary); + + if credential_access_then_network { + return RiskLevel::High; + } + + if discovery_then_network + || credential_interest_then_network + || repeated_policy_boundary + { + return RiskLevel::Medium; + } + + RiskLevel::Low +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evolve::{EventSource, SecurityEventType}; + + #[test] + fn discovery_followed_by_network_activity_raises_medium_risk() { + let mut profiler = BehaviorProfiler::new(); + + let discovery = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("whoami"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + assert_eq!(profiler.observe(&discovery).risk_level, RiskLevel::Low); + assert_eq!(profiler.observe(&network).risk_level, RiskLevel::Medium); + + let trace = profiler.trace("session-a").expect("trace should exist"); + assert!(trace.tags.contains(&BehaviorTag::Discovery)); + assert!(trace.tags.contains(&BehaviorTag::NetworkActivity)); + assert_eq!(trace.events.len(), 2); + } + + #[test] + fn credential_interest_followed_by_network_activity_is_medium_risk() { + let mut profiler = BehaviorProfiler::new(); + + let credential = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("cat ~/.ssh/id_rsa"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + profiler.observe(&credential); + assert_eq!(profiler.observe(&network).risk_level, RiskLevel::Medium); + } + + #[test] + fn confirmed_credential_access_followed_by_network_activity_is_high_risk() { + let mut profiler = BehaviorProfiler::new(); + + let credential = + SecurityEvent::new(EventSource::Filesystem, SecurityEventType::CredentialAccess) + .with_session_id("session-a") + .with_resource("/workspace/secret"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + profiler.observe(&credential); + assert_eq!(profiler.observe(&network).risk_level, RiskLevel::High); + } + + #[test] + fn trace_collects_process_resource_and_destination_lineage() { + let mut profiler = BehaviorProfiler::new(); + let event = SecurityEvent::new(EventSource::Network, SecurityEventType::NetworkConnect) + .with_session_id("session-a") + .with_process(42, Some(7)) + .with_resource("/workspace/tool.sh") + .with_destination("203.0.113.7:443"); + + profiler.observe(&event); + + let trace = profiler.trace("session-a").expect("trace should exist"); + assert_eq!(trace.process_lineage.get(&42), Some(&Some(7))); + assert!(trace.resources.contains("/workspace/tool.sh")); + assert!(trace.destinations.contains("203.0.113.7:443")); + } + + #[test] + fn control_plane_access_is_always_critical() { + let mut profiler = BehaviorProfiler::new(); + let event = + SecurityEvent::new(EventSource::Policy, SecurityEventType::ControlPlaneAccess) + .with_session_id("session-a"); + + let assessment = profiler.observe(&event); + assert_eq!(assessment.risk_level, RiskLevel::Critical); + assert_eq!(assessment.risk_score, 100); + } + + #[test] + fn trace_buffer_is_bounded() { + let mut profiler = BehaviorProfiler::new(); + profiler.event_capacity = 2; + + for index in 0..3 { + let event = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command(format!("echo {index}")); + profiler.observe(&event); + } + + assert_eq!( + profiler + .trace("session-a") + .expect("trace should exist") + .events + .len(), + 2 + ); + } +} diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs new file mode 100644 index 0000000..9c889d6 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/event.rs @@ -0,0 +1,187 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +static EVENT_SEQUENCE: AtomicU64 = AtomicU64::new(1); + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u64::MAX as u128) as u64 +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EventSource { + Canary, + Filesystem, + Process, + Network, + Browser, + HttpProbe, + Policy, + System, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SecurityEventType { + FileOpen, + FileRead, + FileWrite, + FileDelete, + ProcessSpawn, + ProcessExec, + ProcessExit, + NetworkConnect, + NetworkListen, + DnsAttempt, + CredentialAccess, + CanaryAccess, + Discovery, + PrivilegeAttempt, + PersistenceAttempt, + LateralMovementAttempt, + BrowserNavigation, + HttpRequest, + PolicyViolation, + EscapeAttempt, + ControlPlaneAccess, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum RiskLevel { + Low, + Medium, + High, + Critical, +} + +impl RiskLevel { + pub fn rank(self) -> u8 { + match self { + Self::Low => 0, + Self::Medium => 1, + Self::High => 2, + Self::Critical => 3, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SecurityEvent { + pub event_id: String, + pub session_id: Option, + pub timestamp_ms: u64, + pub source: EventSource, + pub event_type: SecurityEventType, + pub process_id: Option, + pub parent_process_id: Option, + pub uid: Option, + pub resource: Option, + pub destination: Option, + pub command: Option, + pub arguments: Vec, + pub result: Option, + pub risk_hint: Option, + pub metadata: Value, +} + +impl SecurityEvent { + pub fn new(source: EventSource, event_type: SecurityEventType) -> Self { + let timestamp_ms = now_ms(); + let sequence = EVENT_SEQUENCE.fetch_add(1, Ordering::Relaxed); + + Self { + event_id: format!("evt-{timestamp_ms}-{sequence}"), + session_id: None, + timestamp_ms, + source, + event_type, + process_id: None, + parent_process_id: None, + uid: None, + resource: None, + destination: None, + command: None, + arguments: Vec::new(), + result: None, + risk_hint: None, + metadata: Value::Object(Default::default()), + } + } + + pub fn with_session_id(mut self, session_id: impl Into) -> Self { + self.session_id = Some(session_id.into()); + self + } + + pub fn with_resource(mut self, resource: impl Into) -> Self { + self.resource = Some(resource.into()); + self + } + + pub fn with_destination(mut self, destination: impl Into) -> Self { + self.destination = Some(destination.into()); + self + } + + pub fn with_command(mut self, command: impl Into) -> Self { + self.command = Some(command.into()); + self + } + + pub fn with_arguments(mut self, arguments: Vec) -> Self { + self.arguments = arguments; + self + } + + pub fn with_result(mut self, result: impl Into) -> Self { + self.result = Some(result.into()); + self + } + + pub fn with_process(mut self, process_id: u32, parent_process_id: Option) -> Self { + self.process_id = Some(process_id); + self.parent_process_id = parent_process_id; + self + } + + pub fn with_uid(mut self, uid: u32) -> Self { + self.uid = Some(uid); + self + } + + pub fn with_risk_hint(mut self, risk: RiskLevel) -> Self { + self.risk_hint = Some(risk); + self + } + + pub fn with_metadata(mut self, metadata: Value) -> Self { + self.metadata = metadata; + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn event_ids_are_unique() { + let first = SecurityEvent::new(EventSource::System, SecurityEventType::PolicyViolation); + let second = SecurityEvent::new(EventSource::System, SecurityEventType::PolicyViolation); + assert_ne!(first.event_id, second.event_id); + } + + #[test] + fn risk_rank_is_monotonic() { + assert!(RiskLevel::Critical.rank() > RiskLevel::High.rank()); + assert!(RiskLevel::High.rank() > RiskLevel::Medium.rank()); + assert!(RiskLevel::Medium.rank() > RiskLevel::Low.rank()); + } +} diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs new file mode 100644 index 0000000..e5ec9ca --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/manager.rs @@ -0,0 +1,291 @@ +use super::{ + BehaviorProfiler, BehaviorTrace, EvolveSession, EvolveState, RiskLevel, SecurityEvent, + StateTransitionError, +}; +use serde::Serialize; +use std::collections::{HashMap, VecDeque}; + +const DEFAULT_EVENT_CAPACITY: usize = 1024; +const DEFAULT_SESSION_ID: &str = "runtime-default"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum EvolveDecision { + LegacyIsolate, + Observe, + EnhancedTelemetry, + Isolate, +} + +#[derive(Debug, Clone, Serialize)] +pub struct EvolveStatus { + pub enabled: bool, + pub state: EvolveState, + pub events_buffered: usize, + pub sessions: usize, + pub behavior_traces: usize, +} + +pub struct EvolveManager { + enabled: bool, + state: EvolveState, + events: VecDeque, + sessions: HashMap, + behavior: BehaviorProfiler, + event_capacity: usize, +} + +impl Default for EvolveManager { + fn default() -> Self { + Self::new() + } +} + +impl EvolveManager { + pub fn new() -> Self { + let mut sessions = HashMap::new(); + sessions.insert( + DEFAULT_SESSION_ID.to_string(), + EvolveSession::new(DEFAULT_SESSION_ID), + ); + + Self { + enabled: false, + state: EvolveState::Observe, + events: VecDeque::with_capacity(DEFAULT_EVENT_CAPACITY), + sessions, + behavior: BehaviorProfiler::new(), + event_capacity: DEFAULT_EVENT_CAPACITY, + } + } + + pub fn is_enabled(&self) -> bool { + self.enabled + } + + pub fn set_enabled(&mut self, enabled: bool) { + self.enabled = enabled; + } + + pub fn state(&self) -> EvolveState { + self.state + } + + pub fn status(&self) -> EvolveStatus { + EvolveStatus { + enabled: self.enabled, + state: self.state, + events_buffered: self.events.len(), + sessions: self.sessions.len(), + behavior_traces: self.behavior.trace_count(), + } + } + + pub fn sessions(&self) -> Vec { + let mut sessions: Vec<_> = self.sessions.values().cloned().collect(); + sessions.sort_by(|left, right| left.created_at_ms.cmp(&right.created_at_ms)); + sessions + } + + pub fn behavior_trace(&self, session_id: &str) -> Option { + self.behavior.trace(session_id).cloned() + } + + pub fn recent_events(&self, limit: usize) -> Vec { + let limit = limit.min(self.events.len()); + self.events + .iter() + .rev() + .take(limit) + .cloned() + .collect::>() + .into_iter() + .rev() + .collect() + } + + pub fn transition(&mut self, next: EvolveState) -> Result<(), StateTransitionError> { + if !self.state.can_transition_to(next) { + return Err(StateTransitionError::InvalidTransition { + from: self.state, + to: next, + }); + } + + self.state = next; + Ok(()) + } + + pub fn mark_isolated(&mut self) { + if self.state != EvolveState::Isolate { + self.state = EvolveState::Isolate; + } + + for session in self.sessions.values_mut() { + session.state = EvolveState::Isolate; + } + } + + pub fn ingest_event(&mut self, mut event: SecurityEvent) -> EvolveDecision { + let session_id = event + .session_id + .clone() + .unwrap_or_else(|| DEFAULT_SESSION_ID.to_string()); + event.session_id = Some(session_id.clone()); + + let assessment = self.behavior.observe(&event); + event.risk_hint = Some(assessment.risk_level); + + let session = self + .sessions + .entry(session_id.clone()) + .or_insert_with(|| EvolveSession::new(session_id.clone())); + session.record_event(&event); + + let risk = assessment.risk_level; + let event_type = event.event_type; + self.push_event(event); + + if !self.enabled { + return match event_type { + super::SecurityEventType::CanaryAccess => EvolveDecision::LegacyIsolate, + super::SecurityEventType::EscapeAttempt + | super::SecurityEventType::ControlPlaneAccess => EvolveDecision::Isolate, + _ => EvolveDecision::Observe, + }; + } + + match risk { + RiskLevel::Low => EvolveDecision::Observe, + RiskLevel::Medium => { + self.enter_suspect_state(&session_id); + EvolveDecision::EnhancedTelemetry + } + RiskLevel::High | RiskLevel::Critical => { + self.enter_suspect_state(&session_id); + + // Phase 8.1 intentionally fails closed here. The event pipeline is active, but + // Deception Fabric is not implemented yet, so high-risk behavior cannot safely be + // redirected and must still escalate to existing isolation. + EvolveDecision::Isolate + } + } + } + + fn enter_suspect_state(&mut self, session_id: &str) { + if self.state == EvolveState::Observe { + let _ = self.transition(EvolveState::Suspect); + } + + if let Some(session) = self.sessions.get_mut(session_id) + && session.state == EvolveState::Observe + { + session.state = EvolveState::Suspect; + } + } + + fn push_event(&mut self, event: SecurityEvent) { + if self.events.len() >= self.event_capacity { + self.events.pop_front(); + } + self.events.push_back(event); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evolve::{EventSource, SecurityEventType}; + + #[test] + fn disabled_manager_preserves_canary_legacy_isolation_decision() { + let mut manager = EvolveManager::new(); + let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + .with_risk_hint(RiskLevel::High); + + assert_eq!( + manager.ingest_event(event), + EvolveDecision::LegacyIsolate + ); + assert_eq!(manager.recent_events(10).len(), 1); + } + + #[test] + fn disabled_manager_does_not_isolate_on_ordinary_telemetry() { + let mut manager = EvolveManager::new(); + let event = SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_risk_hint(RiskLevel::Low); + + assert_eq!(manager.ingest_event(event), EvolveDecision::Observe); + } + + #[test] + fn enabled_medium_risk_enters_suspect_without_isolation() { + let mut manager = EvolveManager::new(); + manager.set_enabled(true); + + let event = SecurityEvent::new(EventSource::Policy, SecurityEventType::PolicyViolation) + .with_risk_hint(RiskLevel::Medium); + + assert_eq!( + manager.ingest_event(event), + EvolveDecision::EnhancedTelemetry + ); + assert_eq!(manager.state(), EvolveState::Suspect); + } + + #[test] + fn enabled_high_risk_fails_closed_until_deception_exists() { + let mut manager = EvolveManager::new(); + manager.set_enabled(true); + + let event = SecurityEvent::new(EventSource::Canary, SecurityEventType::CanaryAccess) + .with_risk_hint(RiskLevel::High); + + assert_eq!(manager.ingest_event(event), EvolveDecision::Isolate); + assert_eq!(manager.state(), EvolveState::Suspect); + } + + #[test] + fn behavior_sequence_can_raise_manager_risk() { + let mut manager = EvolveManager::new(); + manager.set_enabled(true); + + let discovery = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("whoami"); + let network = + SecurityEvent::new(EventSource::Process, SecurityEventType::ProcessExec) + .with_session_id("session-a") + .with_command("curl https://example.com"); + + assert_eq!(manager.ingest_event(discovery), EvolveDecision::Observe); + assert_eq!( + manager.ingest_event(network), + EvolveDecision::EnhancedTelemetry + ); + assert_eq!(manager.state(), EvolveState::Suspect); + + let trace = manager + .behavior_trace("session-a") + .expect("behavior trace should exist"); + assert_eq!(trace.events.len(), 2); + assert_eq!(trace.risk_level, RiskLevel::Medium); + } + + #[test] + fn event_buffer_is_bounded() { + let mut manager = EvolveManager::new(); + manager.event_capacity = 2; + + for _ in 0..3 { + manager.ingest_event(SecurityEvent::new( + EventSource::System, + SecurityEventType::PolicyViolation, + )); + } + + assert_eq!(manager.recent_events(10).len(), 2); + } +} diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs new file mode 100644 index 0000000..8fea327 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/mod.rs @@ -0,0 +1,11 @@ +pub mod behavior; +pub mod event; +pub mod manager; +pub mod session; +pub mod state; + +pub use behavior::{BehaviorAssessment, BehaviorProfiler, BehaviorTag, BehaviorTrace}; +pub use event::{EventSource, RiskLevel, SecurityEvent, SecurityEventType}; +pub use manager::{EvolveDecision, EvolveManager, EvolveStatus}; +pub use session::EvolveSession; +pub use state::{EvolveState, StateTransitionError}; diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs new file mode 100644 index 0000000..8635abb --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/session.rs @@ -0,0 +1,60 @@ +use super::{EvolveState, RiskLevel, SecurityEvent}; +use serde::{Deserialize, Serialize}; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u64::MAX as u128) as u64 +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EvolveSession { + pub session_id: String, + pub created_at_ms: u64, + pub last_event_at_ms: u64, + pub state: EvolveState, + pub risk_level: RiskLevel, + pub event_refs: Vec, + pub process_roots: Vec, + pub active_deception_profile: Option, + pub shadow_path_id: Option, + pub attack_trace_id: Option, +} + +impl EvolveSession { + pub fn new(session_id: impl Into) -> Self { + let now = now_ms(); + Self { + session_id: session_id.into(), + created_at_ms: now, + last_event_at_ms: now, + state: EvolveState::Observe, + risk_level: RiskLevel::Low, + event_refs: Vec::new(), + process_roots: Vec::new(), + active_deception_profile: None, + shadow_path_id: None, + attack_trace_id: None, + } + } + + pub fn record_event(&mut self, event: &SecurityEvent) { + self.last_event_at_ms = event.timestamp_ms; + self.event_refs.push(event.event_id.clone()); + + if let Some(pid) = event.process_id { + if !self.process_roots.contains(&pid) { + self.process_roots.push(pid); + } + } + + if let Some(risk) = event.risk_hint { + if risk.rank() > self.risk_level.rank() { + self.risk_level = risk; + } + } + } +} diff --git a/sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs b/sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs new file mode 100644 index 0000000..092de37 --- /dev/null +++ b/sandbox_runtime/crates/sandbox-kernel/src/evolve/state.rs @@ -0,0 +1,82 @@ +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum EvolveState { + Observe, + Suspect, + Engage, + Deceive, + Learn, + Adapt, + Isolate, +} + +impl Default for EvolveState { + fn default() -> Self { + Self::Observe + } +} + +impl EvolveState { + pub fn can_transition_to(self, next: Self) -> bool { + if next == Self::Isolate && self != Self::Isolate { + return true; + } + + matches!( + (self, next), + (Self::Observe, Self::Suspect) + | (Self::Suspect, Self::Observe) + | (Self::Suspect, Self::Engage) + | (Self::Engage, Self::Suspect) + | (Self::Engage, Self::Deceive) + | (Self::Deceive, Self::Learn) + | (Self::Learn, Self::Adapt) + | (Self::Adapt, Self::Observe) + ) + } +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum StateTransitionError { + #[error("invalid Evolve state transition: {from:?} -> {to:?}")] + InvalidTransition { from: EvolveState, to: EvolveState }, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expected_pipeline_transitions_are_allowed() { + assert!(EvolveState::Observe.can_transition_to(EvolveState::Suspect)); + assert!(EvolveState::Suspect.can_transition_to(EvolveState::Engage)); + assert!(EvolveState::Engage.can_transition_to(EvolveState::Deceive)); + assert!(EvolveState::Deceive.can_transition_to(EvolveState::Learn)); + assert!(EvolveState::Learn.can_transition_to(EvolveState::Adapt)); + assert!(EvolveState::Adapt.can_transition_to(EvolveState::Observe)); + } + + #[test] + fn every_active_state_can_isolate() { + for state in [ + EvolveState::Observe, + EvolveState::Suspect, + EvolveState::Engage, + EvolveState::Deceive, + EvolveState::Learn, + EvolveState::Adapt, + ] { + assert!(state.can_transition_to(EvolveState::Isolate)); + } + } + + #[test] + fn unsafe_skip_is_rejected() { + assert!(!EvolveState::Observe.can_transition_to(EvolveState::Deceive)); + assert!(!EvolveState::Observe.can_transition_to(EvolveState::Adapt)); + assert!(!EvolveState::Isolate.can_transition_to(EvolveState::Observe)); + } +} diff --git a/sandbox_runtime/crates/sandbox-kernel/src/lib.rs b/sandbox_runtime/crates/sandbox-kernel/src/lib.rs index df18f6f..9232faa 100644 --- a/sandbox_runtime/crates/sandbox-kernel/src/lib.rs +++ b/sandbox_runtime/crates/sandbox-kernel/src/lib.rs @@ -1,6 +1,7 @@ pub mod canary; pub mod containment; pub mod egress; +pub mod evolve; pub mod panic; pub mod privilege; pub mod tmux; @@ -9,6 +10,11 @@ pub mod watchdog; pub use canary::{CanaryManager, CanaryTrap}; pub use containment::{apply_runtime_containment, stop_tor_best_effort, ContainmentError}; pub use egress::{AuditMode, EgressConfig, EgressManager}; +pub use evolve::{ + BehaviorAssessment, BehaviorProfiler, BehaviorTag, BehaviorTrace, EventSource, EvolveDecision, + EvolveManager, EvolveSession, EvolveState, EvolveStatus, RiskLevel, SecurityEvent, + SecurityEventType, StateTransitionError, +}; pub use panic::KillSwitch; pub use privilege::{ audit_exec_identity, audit_identity_conflicts_with_reserved_runtime_uid, browser_exec_identity, diff --git a/src/mcp/bridge.ts b/src/mcp/bridge.ts index b8f5406..32afada 100644 --- a/src/mcp/bridge.ts +++ b/src/mcp/bridge.ts @@ -1,6 +1,7 @@ import * as http from 'node:http'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { randomUUID } from 'node:crypto'; import { RatchetBridge } from './security/ratchet_bridge.js'; import { JailGuard } from './security/jail.js'; import { @@ -93,6 +94,7 @@ export class SandboxBridge { targetHosts: [], proxy: null, }; + private activeEvolveSessionId: string = randomUUID(); constructor(options?: { workspaceRoot?: string; @@ -262,6 +264,7 @@ export class SandboxBridge { }; const egressRes = await this.request('POST', '/provision_egress', payload); + this.activeEvolveSessionId = randomUUID(); this.activeNetworkScope = { mode: options.mode, targetHosts, @@ -308,10 +311,36 @@ export class SandboxBridge { return this.request('POST', '/rotate_tor', {}); } + public async setEvolveEnabled(enabled: boolean): Promise { + return this.request('POST', '/evolve/enable', { enabled }); + } + + public async getEvolveStatus(): Promise { + return this.request('GET', '/evolve/status'); + } + + public async getEvolveEvents(limit: number = 100): Promise { + const normalizedLimit = Number.isFinite(limit) ? Math.trunc(limit) : 100; + const boundedLimit = Math.max(1, Math.min(1000, normalizedLimit)); + return this.request('GET', `/evolve/events?limit=${boundedLimit}`); + } + + public async getEvolveSessions(): Promise { + return this.request('GET', '/evolve/sessions'); + } + + public async getEvolveTrace(sessionId: string = this.activeEvolveSessionId): Promise { + return this.request( + 'GET', + `/evolve/trace?session_id=${encodeURIComponent(sessionId)}` + ); + } + public async exec(command: string, timeoutSecs: number = 60): Promise { const raw = await this.request('POST', '/execute', { command, timeout_secs: timeoutSecs, + evolve_session_id: this.activeEvolveSessionId, }); return { exit_code: raw.exit_code, @@ -333,7 +362,11 @@ export class SandboxBridge { command: string, session: string = 'background_scan' ): Promise<{ status: string; session: string; message: string }> { - return this.request('POST', '/start_background', { command, session }); + return this.request('POST', '/start_background', { + command, + session, + evolve_session_id: this.activeEvolveSessionId, + }); } public async pollLogs( @@ -361,6 +394,7 @@ export class SandboxBridge { ...options, proxy: networkPolicy.useTor ? TOR_BROWSER_PROXY : null, allowed_hosts: networkPolicy.allowedHosts, + evolve_session_id: this.activeEvolveSessionId, }); } @@ -374,6 +408,7 @@ export class SandboxBridge { body: options.body || '', proxy: networkPolicy.useTor ? TOR_HTTP_PROXY : null, allowed_hosts: networkPolicy.allowedHosts, + evolve_session_id: this.activeEvolveSessionId, }); } @@ -391,8 +426,11 @@ export class SandboxBridge { } } - public async armCanary(tokenLabel: string = 'default_audit_canary'): Promise { - return this.request('POST', '/arm_canary', { token_label: tokenLabel }); + public async armCanary(baseDir: string = '/workspace'): Promise { + return this.request('POST', '/arm_canary', { + base_dir: baseDir, + evolve_session_id: this.activeEvolveSessionId, + }); } public fsRead(relPath: string): { path: string; content: string } { @@ -422,6 +460,7 @@ export class SandboxBridge { await this.killSwitch('Reset called'); } this.activeNetworkScope = { mode: 'local', targetHosts: [], proxy: null }; + this.activeEvolveSessionId = randomUUID(); return { status: 'ok', message: 'Sandbox instance cleanly reset' }; } } diff --git a/tests/evolve_bridge.test.ts b/tests/evolve_bridge.test.ts new file mode 100644 index 0000000..444153d --- /dev/null +++ b/tests/evolve_bridge.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SandboxBridge } from '../src/mcp/bridge.js'; + +function mockedBridge() { + const bridge = new SandboxBridge({ workspaceRoot: process.cwd(), hostPort: 19997 }); + const request = vi.spyOn(bridge as any, 'request').mockResolvedValue({ status: 'success' }); + return { bridge, request }; +} + +function bodyFor( + request: any, + path: string +): Record { + const call = request.mock.calls.find((entry) => entry[1] === path); + if (!call) throw new Error(`Expected request to ${path}`); + return (call[2] || {}) as Record; +} + +describe('SandboxBridge Evolve correlation', () => { + it('propagates one behavioral session across a scoped audit surface', async () => { + const { bridge, request } = mockedBridge(); + + await bridge.setScope({ + mode: 'remote', + targets: ['203.0.113.7'], + arm_canaries: true, + }); + + const canaryBody = bodyFor(request, '/arm_canary'); + const sessionId = canaryBody.evolve_session_id; + expect(typeof sessionId).toBe('string'); + expect(canaryBody).toEqual( + expect.objectContaining({ + base_dir: '/workspace', + evolve_session_id: sessionId, + }) + ); + expect(canaryBody).not.toHaveProperty('token_label'); + + request.mockClear(); + + await bridge.exec('whoami'); + await bridge.startBackground('printf TEST', 'evolve_bg'); + await bridge.browserAudit({ url: 'https://203.0.113.7/path' }); + await bridge.httpProbe({ url: 'https://203.0.113.7/api' }); + + expect(bodyFor(request, '/execute').evolve_session_id).toBe(sessionId); + expect(bodyFor(request, '/start_background').evolve_session_id).toBe(sessionId); + expect(bodyFor(request, '/browser_audit').evolve_session_id).toBe(sessionId); + expect(bodyFor(request, '/http_probe').evolve_session_id).toBe(sessionId); + }); + + it('rotates the behavioral session when a new scope is provisioned', async () => { + const { bridge, request } = mockedBridge(); + + await bridge.setScope({ mode: 'local', arm_canaries: true }); + const firstSession = bodyFor(request, '/arm_canary').evolve_session_id; + + request.mockClear(); + await bridge.setScope({ mode: 'local', arm_canaries: true }); + const secondSession = bodyFor(request, '/arm_canary').evolve_session_id; + + expect(secondSession).not.toBe(firstSession); + }); + + it('exposes authenticated host helpers for Evolve observability', async () => { + const { bridge, request } = mockedBridge(); + + await bridge.setEvolveEnabled(true); + await bridge.getEvolveStatus(); + await bridge.getEvolveEvents(5000); + await bridge.getEvolveSessions(); + await bridge.getEvolveTrace('session/test'); + + expect(request).toHaveBeenCalledWith('POST', '/evolve/enable', { enabled: true }); + expect(request).toHaveBeenCalledWith('GET', '/evolve/status'); + expect(request).toHaveBeenCalledWith('GET', '/evolve/events?limit=1000'); + expect(request).toHaveBeenCalledWith('GET', '/evolve/sessions'); + expect(request).toHaveBeenCalledWith( + 'GET', + '/evolve/trace?session_id=session%2Ftest' + ); + }); +}); diff --git a/tests/evolve_docker.test.ts b/tests/evolve_docker.test.ts new file mode 100644 index 0000000..d5efab1 --- /dev/null +++ b/tests/evolve_docker.test.ts @@ -0,0 +1,76 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { SandboxBridge } from '../src/mcp/bridge.js'; + +const enabled = process.env.SECURITY_AUDIT_DOCKER_E2E === '1'; +const describeDocker = enabled ? describe : describe.skip; + +describeDocker('Evolve live Docker behavior pipeline', () => { + let bridge: SandboxBridge; + let workspace: string; + const port = 19109; + + beforeAll(async () => { + workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'security-audit-evolve-e2e-')); + bridge = new SandboxBridge({ workspaceRoot: workspace, hostPort: port }); + await bridge.ensureRuntime(); + await bridge.setScope({ mode: 'local', arm_canaries: false }); + await bridge.setEvolveEnabled(true); + }, 60_000); + + afterAll(() => { + try { + bridge?.getDocker().stop(); + } finally { + if (workspace) fs.rmSync(workspace, { recursive: true, force: true }); + } + }); + + it('correlates real exec telemetry into a medium-risk behavior trace', async () => { + const discovery = await bridge.exec('whoami'); + expect(discovery.exit_code).toBe(0); + + // Local mode is intentionally fail-closed for outbound networking. The command itself is still + // observable, so BehaviorProfiler can correlate discovery -> network intent without allowing + // the connection to escape the sandbox. + const network = await bridge.exec( + 'curl -fsS --connect-timeout 1 --max-time 2 https://example.com >/dev/null' + ); + expect(network.exit_code).not.toBe(0); + + const status = await bridge.getEvolveStatus(); + expect(status.enabled).toBe(true); + expect(status.state).toBe('SUSPECT'); + expect(status.behavior_traces).toBeGreaterThan(0); + + const sessions = await bridge.getEvolveSessions(); + const activeSession = sessions.sessions.find( + (session: any) => session.session_id !== 'runtime-default' && session.event_refs.length > 0 + ); + expect(activeSession).toBeTruthy(); + + const trace = await bridge.getEvolveTrace(activeSession.session_id); + expect(trace.risk_level).toBe('MEDIUM'); + expect(trace.risk_score).toBe(45); + expect(trace.tags).toEqual( + expect.arrayContaining(['execution', 'discovery', 'network_activity']) + ); + expect(trace.events.length).toBeGreaterThanOrEqual(4); + expect(Object.keys(trace.process_lineage).length).toBeGreaterThan(0); + }, 15_000); + + it('keeps the runtime network boundary intact while Evolve observes behavior', async () => { + const isolation = await bridge.request<{ is_isolated: boolean }>( + 'GET', + '/isolation_status' + ); + expect(isolation.is_isolated).toBe(false); + + const blocked = await bridge.exec( + 'curl -fsS --connect-timeout 1 --max-time 2 http://1.1.1.1 >/dev/null' + ); + expect(blocked.exit_code).not.toBe(0); + }, 10_000); +});