//! Bounded, local, fixture-only Event Log provider. Only the authorized native //! job worker may call the Windows provider; this module confers no authority. //! //! EvtQuery/EvtRender have no per-call timeout. The monotonic deadline below is //! cooperative between Win32 calls; the eventual executor must also supervise //! its process. This module never starts another worker or advances a bookmark. //! API contracts: https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtquery //! https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtnext //! https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtrender //! https://learn.microsoft.com/en-us/windows/win32/api/winevt/ne-winevt-evt_system_property_id use anyhow::{Result, ensure}; use chrono::{DateTime, SecondsFormat, Utc}; use serde::{Deserialize, Serialize}; use std::sync::atomic::AtomicBool; pub use rmm_domain::jobs::{ WINDOWS_EVENT_LOG_FIXTURE_CHANNEL as CHANNEL, WINDOWS_EVENT_LOG_FIXTURE_PROVIDER as PROVIDER, }; const MAX_BYTES: usize = 256 * 1024; #[cfg(any(windows, test))] const REPORT_RESERVE: usize = 256; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct Query { pub channel: String, pub provider: String, pub start_utc: DateTime, pub end_utc: DateTime, pub max_events: u32, pub max_output_bytes: u32, pub timeout_ms: u32, } impl Query { fn xpath(&self) -> Result { ensure!( self.channel == CHANNEL && self.provider == PROVIDER, "EVENT_LOG_SOURCE_DENIED" ); ensure!( self.start_utc.timestamp() >= 0 && self.end_utc > self.start_utc && self.end_utc - self.start_utc <= chrono::Duration::hours(24), "EVENT_LOG_WINDOW_INVALID" ); ensure!( (1..=1000).contains(&self.max_events) && (1024..=MAX_BYTES as u32).contains(&self.max_output_bytes) && (1..=5000).contains(&self.timeout_ms), "EVENT_LOG_LIMIT_INVALID" ); // Only canonical UTC timestamps enter this fixed expression. Neither a // caller-supplied XPath, a remote session nor a log-file path exists. Ok(format!( "*[System[Provider[@Name='{PROVIDER}'] and TimeCreated[@SystemTime>='{}' and @SystemTime<'{}']]]", self.start_utc.to_rfc3339_opts(SecondsFormat::Nanos, true), self.end_utc.to_rfc3339_opts(SecondsFormat::Nanos, true) )) } } /// Pure job-to-provider binding. Never opens a channel or touches a bookmark. pub fn for_job(job: &rmm_domain::jobs::JobPayload) -> Result { use rmm_domain::jobs::{Action, WINDOWS_EVENT_LOG_FIXTURE_SOURCE}; let Action::QueryLogs { unit, since, until, max_lines, } = &job.action else { anyhow::bail!("EVENT_LOG_ACTION_REQUIRED") }; ensure!( job.execution_identity == "agent_service" && unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE && job.action.validate() && job .action .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes), "EVENT_LOG_JOB_BINDING" ); let q = Query { channel: CHANNEL.into(), provider: PROVIDER.into(), start_utc: *since, end_utc: *until, max_events: *max_lines, max_output_bytes: job.max_output_bytes, timeout_ms: 5000, }; q.xpath()?; Ok(q) } #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Event { pub channel: String, pub provider: String, pub record_id: u64, pub event_id: u16, pub created_utc: DateTime, /// Exact bounded XML from EvtRenderEventXml, including fixture EventData; /// no localized publisher DLL/message formatting is performed. pub xml: String, } #[derive(Debug, Serialize)] pub struct Report { pub channel: String, pub provider: String, pub start_utc: DateTime, pub end_utc: DateTime, pub quality: &'static str, pub completeness: &'static str, pub truncated: bool, pub error_code: Option<&'static str>, pub win32_error: Option, pub events: Vec, pub bookmark_updated: bool, pub deadline_enforcement: &'static str, } #[cfg(any(windows, test))] impl Report { fn new(q: &Query) -> Self { Self { channel: q.channel.clone(), provider: q.provider.clone(), start_utc: q.start_utc, end_utc: q.end_utc, quality: "valid", completeness: "partial", truncated: false, error_code: None, win32_error: None, events: Vec::new(), bookmark_updated: false, deadline_enforcement: "cooperative_between_win32_calls", } } fn stop(&mut self, code: &'static str, win32: Option) { self.truncated = true; self.error_code = Some(code); self.win32_error = win32; self.completeness = if self.events.is_empty() { "unknown" } else { "partial" }; if win32 == Some(5) { self.quality = "permission_denied"; } else if win32.is_some() { self.quality = "error"; } } fn push(&mut self, event: Event, limit: usize) -> Result { self.events.push(event); if serde_json::to_vec(self)?.len() + REPORT_RESERVE > limit { self.events.pop(); self.stop("EVENT_LOG_BYTE_LIMIT", None); return Ok(false); } Ok(true) } } /// Reads only the fixed local fixture source. No persistent state is modified. pub fn query(q: &Query, cancelled: &AtomicBool) -> Result { let xpath = q.xpath()?; #[cfg(windows)] { windows::query(q, &xpath, cancelled) } #[cfg(not(windows))] { let _ = (xpath, cancelled); anyhow::bail!("EVENT_LOG_WINDOWS_ONLY") } } #[cfg(windows)] mod windows { use super::*; use anyhow::Context; use std::{ mem::size_of, ptr, sync::atomic::Ordering, time::{Duration, Instant}, }; use windows_sys::Win32::{ Foundation::{ ERROR_ACCESS_DENIED, ERROR_INSUFFICIENT_BUFFER, ERROR_NO_MORE_ITEMS, ERROR_TIMEOUT, GetLastError, }, System::EventLog::*, }; struct Handle(EVT_HANDLE); impl Drop for Handle { fn drop(&mut self) { if self.0 != 0 { unsafe { EvtClose(self.0); } } } } fn wide(s: &str) -> Vec { s.encode_utf16().chain(Some(0)).collect() } fn stopped(report: &mut Report, cancelled: &AtomicBool, until: Instant) -> bool { if cancelled.load(Ordering::SeqCst) { report.stop("EVENT_LOG_CANCELLED", None); true } else if Instant::now() >= until { report.stop("EVENT_LOG_TIME_LIMIT", None); true } else { false } } fn failure(report: &mut Report, error: u32) { report.stop( if error == ERROR_ACCESS_DENIED { "EVENT_LOG_PERMISSION_DENIED" } else { "EVENT_LOG_API_ERROR" }, Some(error), ); } // u64 storage provides the alignment required by EVT_VARIANT. All returned // pointers are read while this owning allocation remains alive. fn render( context: EVT_HANDLE, event: EVT_HANDLE, flags: u32, cap: usize, until: Instant, cancelled: &AtomicBool, ) -> Result<(Vec, usize, u32)> { ensure!( !cancelled.load(Ordering::SeqCst) && Instant::now() < until, "EVENT_LOG_TIME_OR_CANCELLED" ); let mut used = 0; let mut count = 0; let first = unsafe { EvtRender( context, event, flags, 0, ptr::null_mut(), &mut used, &mut count, ) }; let error = if first == 0 { unsafe { GetLastError() } } else { 0 }; ensure!( !cancelled.load(Ordering::SeqCst) && Instant::now() < until, "EVENT_LOG_TIME_OR_CANCELLED" ); if first == 0 && error != ERROR_INSUFFICIENT_BUFFER { return Err(std::io::Error::from_raw_os_error(error as i32).into()); } ensure!(first == 0 && used > 0, "EVENT_LOG_RENDER_PROBE"); if used as usize > cap { return Err(std::io::Error::from_raw_os_error(ERROR_INSUFFICIENT_BUFFER as i32).into()); } let mut buffer = vec![0u64; (used as usize).div_ceil(8)]; let allocated = buffer.len() * 8; ensure!( !cancelled.load(Ordering::SeqCst) && Instant::now() < until, "EVENT_LOG_TIME_OR_CANCELLED" ); let ok = unsafe { EvtRender( context, event, flags, allocated as u32, buffer.as_mut_ptr().cast(), &mut used, &mut count, ) }; let error = if ok == 0 { unsafe { GetLastError() } } else { 0 }; ensure!( !cancelled.load(Ordering::SeqCst) && Instant::now() < until, "EVENT_LOG_TIME_OR_CANCELLED" ); if ok == 0 { return Err(std::io::Error::from_raw_os_error(error as i32).into()); } ensure!(used as usize <= allocated, "EVENT_LOG_RENDER_SIZE"); Ok((buffer, used as usize, count)) } fn string(value: &EVT_VARIANT, buffer: &[u64], used: usize) -> Result { ensure!( value.Type == EvtVarTypeString as u32, "EVENT_LOG_PROPERTY_TYPE" ); let pointer = unsafe { value.Anonymous.StringVal }; let address = pointer as usize; let base = buffer.as_ptr() as usize; ensure!( address >= base && address < base + used && address.is_multiple_of(2), "EVENT_LOG_PROPERTY_POINTER" ); let length = (base + used - address) / 2; let units = unsafe { std::slice::from_raw_parts(pointer, length) }; let end = units .iter() .position(|x| *x == 0) .context("EVENT_LOG_PROPERTY_TERMINATOR")?; ensure!(end <= 256, "EVENT_LOG_PROPERTY_LIMIT"); Ok(String::from_utf16(&units[..end])?) } fn read_event( context: EVT_HANDLE, event: EVT_HANDLE, q: &Query, until: Instant, cancelled: &AtomicBool, ) -> Result { let (buffer, used, count) = render( context, event, EvtRenderEventValues, 16 * 1024, until, cancelled, )?; ensure!( count == EvtSystemPropertyIdEND as u32 && used >= count as usize * size_of::(), "EVENT_LOG_PROPERTY_COUNT" ); let values = unsafe { std::slice::from_raw_parts(buffer.as_ptr().cast::(), count as usize) }; let provider = string(&values[EvtSystemProviderName as usize], &buffer, used)?; let channel = string(&values[EvtSystemChannel as usize], &buffer, used)?; ensure!( provider == PROVIDER && channel == CHANNEL, "EVENT_LOG_SOURCE_MISMATCH" ); let record = &values[EvtSystemEventRecordId as usize]; let time = &values[EvtSystemTimeCreated as usize]; let id = &values[EvtSystemEventID as usize]; ensure!( record.Type == EvtVarTypeUInt64 as u32 && time.Type == EvtVarTypeFileTime as u32 && id.Type == EvtVarTypeUInt16 as u32, "EVENT_LOG_PROPERTY_TYPE" ); let record_id = unsafe { record.Anonymous.UInt64Val }; let ticks = unsafe { time.Anonymous.FileTimeVal }; let unix_ticks = ticks .checked_sub(116_444_736_000_000_000) .context("EVENT_LOG_TIMESTAMP")?; let created_utc = DateTime::from_timestamp( i64::try_from(unix_ticks / 10_000_000)?, ((unix_ticks % 10_000_000) * 100) as u32, ) .context("EVENT_LOG_TIMESTAMP")?; ensure!( record_id > 0 && created_utc >= q.start_utc && created_utc < q.end_utc, "EVENT_LOG_RECORD_WINDOW" ); let (xml, bytes, _) = render( 0, event, EvtRenderEventXml, (q.max_output_bytes as usize).min(64 * 1024), until, cancelled, )?; ensure!(bytes >= 2 && bytes.is_multiple_of(2), "EVENT_LOG_XML_SIZE"); let units = unsafe { std::slice::from_raw_parts(xml.as_ptr().cast::(), bytes / 2) }; ensure!( units.last() == Some(&0) && !units[..units.len() - 1].contains(&0), "EVENT_LOG_XML_TERMINATOR" ); Ok(Event { channel, provider, record_id, event_id: unsafe { id.Anonymous.UInt16Val }, created_utc, xml: String::from_utf16(&units[..units.len() - 1])?, }) } pub(super) fn query(q: &Query, xpath: &str, cancelled: &AtomicBool) -> Result { let mut report = Report::new(q); let until = Instant::now() + Duration::from_millis(q.timeout_ms as u64); if stopped(&mut report, cancelled, until) { return Ok(report); } let channel = wide(CHANNEL); let expression = wide(xpath); let handle = Handle(unsafe { EvtQuery( 0, channel.as_ptr(), expression.as_ptr(), EvtQueryChannelPath | EvtQueryForwardDirection, ) }); if handle.0 == 0 { failure(&mut report, unsafe { GetLastError() }); return Ok(report); } if stopped(&mut report, cancelled, until) { return Ok(report); } let context = Handle(unsafe { EvtCreateRenderContext(0, ptr::null(), EvtRenderContextSystem) }); if context.0 == 0 { failure(&mut report, unsafe { GetLastError() }); return Ok(report); } loop { if stopped(&mut report, cancelled, until) { break; } if report.events.len() >= q.max_events as usize { report.stop("EVENT_LOG_EVENT_LIMIT", None); break; } let mut event = 0; let mut returned = 0; let timeout = until .saturating_duration_since(Instant::now()) .as_millis() .min(100) as u32; let ok = unsafe { EvtNext(handle.0, 1, &mut event, timeout, 0, &mut returned) }; let error = if ok == 0 { unsafe { GetLastError() } } else { 0 }; let event = Handle(event); if stopped(&mut report, cancelled, until) { break; } if ok == 0 { if error == ERROR_NO_MORE_ITEMS { report.completeness = "complete"; break; } if error == ERROR_TIMEOUT { continue; } failure(&mut report, error); break; } ensure!(returned == 1 && event.0 != 0, "EVENT_LOG_NEXT_COUNT"); let record = read_event(context.0, event.0, q, until, cancelled); if stopped(&mut report, cancelled, until) { break; } match record { Ok(record) => { if !report.push(record, q.max_output_bytes as usize)? { break; } } Err(error) => { if let Some(code) = error .downcast_ref::() .and_then(std::io::Error::raw_os_error) { if code as u32 == ERROR_INSUFFICIENT_BUFFER { report.stop("EVENT_LOG_EVENT_SIZE_LIMIT", None) } else { failure(&mut report, code as u32) } } else { report.quality = "error"; report.stop("EVENT_LOG_RENDER_OR_RECORD_INVALID", None) } break; } } } ensure!( serde_json::to_vec(&report)?.len() <= q.max_output_bytes as usize, "EVENT_LOG_REPORT_LIMIT" ); Ok(report) } } #[cfg(test)] mod tests { use super::*; fn request() -> Query { let start_utc = DateTime::from_timestamp(1_700_000_000, 0).unwrap(); Query { channel: CHANNEL.into(), provider: PROVIDER.into(), start_utc, end_utc: start_utc + chrono::Duration::minutes(5), max_events: 1000, max_output_bytes: 4096, timeout_ms: 1000, } } #[test] fn only_fixed_source_window_and_finite_limits_are_queryable() { let q = request(); let expression = q.xpath().unwrap(); assert!(expression.len() < 512); assert!(expression.contains(PROVIDER)); for case in 0..7 { let mut q = request(); match case { 0 => q.channel = "Security".into(), 1 => q.provider = "' or 1=1".into(), 2 => q.end_utc = q.start_utc, 3 => q.end_utc = q.start_utc + chrono::Duration::hours(25), 4 => q.max_events = 1001, 5 => q.max_output_bytes = MAX_BYTES as u32 + 1, _ => q.timeout_ms = 5001, }; assert!(q.xpath().is_err()); } } #[test] fn job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits() { use rmm_domain::jobs::{Action, JobPayload, WINDOWS_EVENT_LOG_FIXTURE_SOURCE}; let id = uuid::Uuid::new_v4(); let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap(); let mut job = JobPayload { schema_version: 1, tenant_id: id, asset_id: id, agent_id: id, enrollment_generation: 1, assignment_version: 1, job_id: id, attempt_id: id, action: Action::QueryLogs { unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(), since: now, until: now + chrono::Duration::hours(24), max_lines: 1000, }, execution_identity: "agent_service".into(), not_before: now, start_before: now + chrono::Duration::seconds(60), max_runtime_seconds: 10, max_output_bytes: 65536, }; let q = for_job(&job).unwrap(); assert_eq!( (q.channel.as_str(), q.provider.as_str()), (CHANNEL, PROVIDER) ); assert_eq!(q.max_output_bytes, 65536); for identity in ["root", "system"] { job.execution_identity = identity.into(); assert!(for_job(&job).is_err()); } job.execution_identity = "agent_service".into(); for bytes in [1023, 65537] { job.max_output_bytes = bytes; assert!(for_job(&job).is_err()); } job.max_output_bytes = 65536; if let Action::QueryLogs { until, .. } = &mut job.action { *until += chrono::Duration::nanoseconds(1); } assert!(for_job(&job).is_err()); } #[test] fn serialized_byte_budget_includes_xml_escaping_and_metadata() { let q = request(); let mut report = Report::new(&q); assert!( !report .push( Event { channel: CHANNEL.into(), provider: PROVIDER.into(), record_id: 1, event_id: 1, created_utc: q.start_utc, xml: "\"\\".repeat(2048) }, q.max_output_bytes as usize ) .unwrap() ); assert!(report.events.is_empty()); assert!(report.truncated); assert_eq!(report.error_code, Some("EVENT_LOG_BYTE_LIMIT")); assert!(serde_json::to_vec(&report).unwrap().len() <= q.max_output_bytes as usize); assert!(!report.bookmark_updated); } }