1mod introspect;
16#[cfg(test)]
17mod tests;
18mod types;
19
20pub use introspect::{CorrelationInfo, CorrelationStateSnapshot, GroupKeyPart, GroupStateInfo};
21pub use types::*;
22
23use std::borrow::Cow;
24use std::collections::HashMap;
25
26use chrono::Utc;
27
28use rsigma_parser::{CorrelationRule, CorrelationType, SigmaCollection, SigmaRule, WindowMode};
29
30use crate::correlation::{
31 CompiledCorrelation, EventBuffer, EventRefBuffer, GroupKey, WindowDecision, WindowState,
32 apply_window_open, compile_correlation,
33};
34use crate::engine::{Engine, IdentifiedEvaluation};
35use crate::error::{EvalError, Result};
36use crate::event::{Event, EventValue};
37use crate::logsource::{ExtractLogSource, LogSourceExtractor};
38use crate::pipeline::{Pipeline, apply_pipelines, apply_pipelines_to_correlation};
39use crate::result::{CorrelationBody, EvaluationResult, ResultBody, RuleHeader};
40use crate::rule_metadata::{RuleBundleMetadata, RuleMetadataLookup};
41use crate::timestamp::{epoch_seconds_from_float, epoch_seconds_from_int, parse_timestamp_str};
42
43type RuleIdentity = (Option<String>, Option<String>);
44
45const SNAPSHOT_VERSION: u32 = 1;
51
52const MAX_CHAIN_DEPTH: usize = 10;
58
59const LONG_WINDOW_WARN_SECS: u64 = 3600;
63
64pub struct CorrelationEngine<L = LogSourceExtractor> {
72 engine: Engine<L>,
74 correlations: Vec<CompiledCorrelation>,
76 rule_index: HashMap<String, Vec<usize>>,
79 rule_ids: Vec<(Option<String>, Option<String>, String)>,
82 state: HashMap<(usize, GroupKey), WindowState>,
84 last_alert: HashMap<(usize, GroupKey), i64>,
86 event_buffers: HashMap<(usize, GroupKey), EventBuffer>,
88 event_ref_buffers: HashMap<(usize, GroupKey), EventRefBuffer>,
90 correlation_only_rules: std::collections::HashSet<String>,
94 generated_rules: std::collections::HashSet<String>,
97 config: CorrelationConfig,
99 pipelines: Vec<Pipeline>,
101}
102
103impl CorrelationEngine {
104 pub fn new(config: CorrelationConfig) -> Self {
106 Self::with_engine(config, Engine::new())
107 }
108}
109
110impl<L> CorrelationEngine<L> {
111 pub fn with_logsource_extractor(config: CorrelationConfig, extractor: L) -> Self {
114 Self::with_engine(config, Engine::with_logsource_extractor(extractor))
115 }
116
117 fn with_engine(config: CorrelationConfig, engine: Engine<L>) -> Self {
118 CorrelationEngine {
119 engine,
120 correlations: Vec::new(),
121 rule_index: HashMap::new(),
122 rule_ids: Vec::new(),
123 state: HashMap::new(),
124 last_alert: HashMap::new(),
125 event_buffers: HashMap::new(),
126 event_ref_buffers: HashMap::new(),
127 correlation_only_rules: std::collections::HashSet::new(),
128 generated_rules: std::collections::HashSet::new(),
129 config,
130 pipelines: Vec::new(),
131 }
132 }
133
134 pub fn add_pipeline(&mut self, pipeline: Pipeline) {
138 self.pipelines.push(pipeline);
139 self.pipelines.sort_by_key(|p| p.priority);
140 }
141
142 pub fn set_include_event(&mut self, include: bool) {
144 self.engine.set_include_event(include);
145 }
146
147 pub fn set_match_detail(&mut self, level: crate::result::MatchDetailLevel) {
150 self.engine.set_match_detail(level);
151 }
152
153 pub fn set_bloom_prefilter(&mut self, enabled: bool) {
157 self.engine.set_bloom_prefilter(enabled);
158 }
159
160 pub fn set_logsource_extractor(&mut self, extractor: Option<L>) {
164 self.engine.set_logsource_extractor(extractor);
165 }
166
167 pub fn logsource_pruned_total(&self) -> u64 {
169 self.engine.logsource_pruned_total()
170 }
171
172 pub fn logsource_absent_total(&self) -> u64 {
174 self.engine.logsource_absent_total()
175 }
176
177 pub fn set_bloom_max_bytes(&mut self, max_bytes: usize) {
180 self.engine.set_bloom_max_bytes(max_bytes);
181 }
182
183 #[cfg(feature = "daachorse-index")]
187 pub fn set_cross_rule_ac(&mut self, enabled: bool) {
188 self.engine.set_cross_rule_ac(enabled);
189 }
190
191 pub fn set_correlation_event_mode(&mut self, mode: CorrelationEventMode) {
197 self.config.correlation_event_mode = mode;
198 }
199
200 pub fn set_max_correlation_events(&mut self, max: usize) {
203 self.config.max_correlation_events = max;
204 }
205
206 pub fn add_rule(&mut self, rule: &SigmaRule) -> Result<()> {
212 if self.pipelines.is_empty() {
213 self.apply_custom_attributes(&rule.custom_attributes);
214 self.rule_ids
215 .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
216 self.engine.add_rule(rule)?;
217 } else {
218 let mut transformed = rule.clone();
219 apply_pipelines(&self.pipelines, &mut transformed)?;
220 self.apply_custom_attributes(&transformed.custom_attributes);
221 self.rule_ids.push((
222 transformed.id.clone(),
223 transformed.name.clone(),
224 transformed.title.clone(),
225 ));
226 let compiled = crate::compiler::compile_rule(&transformed)?;
228 self.engine.add_compiled_rule(compiled);
229 }
230 Ok(())
231 }
232
233 fn apply_custom_attributes(
247 &mut self,
248 attrs: &std::collections::HashMap<String, yaml_serde::Value>,
249 ) {
250 if let Some(field) = attrs.get("rsigma.timestamp_field").and_then(|v| v.as_str())
252 && !self.config.timestamp_fields.iter().any(|f| f == field)
253 {
254 self.config.timestamp_fields.insert(0, field.to_string());
255 }
256
257 if let Some(val) = attrs.get("rsigma.suppress").and_then(|v| v.as_str())
259 && self.config.suppress.is_none()
260 && let Ok(ts) = rsigma_parser::Timespan::parse(val)
261 {
262 self.config.suppress = Some(ts.seconds);
263 }
264
265 if let Some(val) = attrs.get("rsigma.action").and_then(|v| v.as_str())
267 && self.config.action_on_match == CorrelationAction::Alert
268 && let Ok(a) = val.parse::<CorrelationAction>()
269 {
270 self.config.action_on_match = a;
271 }
272 }
273
274 pub fn add_correlation(&mut self, corr: &CorrelationRule) -> Result<()> {
276 let owned;
277 let effective = if self.pipelines.is_empty() {
278 corr
279 } else {
280 owned = {
281 let mut c = corr.clone();
282 apply_pipelines_to_correlation(&self.pipelines, &mut c)?;
283 c
284 };
285 &owned
286 };
287
288 self.apply_custom_attributes(&effective.custom_attributes);
291
292 let compiled = compile_correlation(effective)?;
293 if self.has_unbounded_long_window(&compiled) {
294 log::warn!(
295 "Correlation '{}' has a {}s timespan and no per-group entry cap; \
296 a busy group retains timespan x event rate entries. \
297 Set max_group_entries (--max-group-entries) or the rsigma.max_group_entries attribute to bound it.",
298 compiled.id.as_deref().unwrap_or(&compiled.title),
299 compiled.timespan_secs
300 );
301 }
302 let idx = self.correlations.len();
303
304 for rule_ref in &compiled.rule_refs {
306 self.rule_index
307 .entry(rule_ref.clone())
308 .or_default()
309 .push(idx);
310 }
311
312 for rule_ref in &compiled.rule_refs {
315 if compiled.generate {
316 self.generated_rules.insert(rule_ref.clone());
317 self.correlation_only_rules.remove(rule_ref);
318 } else if !self.generated_rules.contains(rule_ref) {
319 self.correlation_only_rules.insert(rule_ref.clone());
320 }
321 }
322
323 self.correlations.push(compiled);
324 Ok(())
325 }
326
327 fn has_unbounded_long_window(&self, corr: &CompiledCorrelation) -> bool {
330 corr.timespan_secs > LONG_WINDOW_WARN_SECS
331 && corr
332 .max_group_entries
333 .or(self.config.max_group_entries)
334 .is_none()
335 }
336
337 pub fn add_collection(&mut self, collection: &SigmaCollection) -> Result<()> {
346 let mut compiled_batch = Vec::with_capacity(collection.rules.len());
347 if self.pipelines.is_empty() {
348 for rule in &collection.rules {
349 self.apply_custom_attributes(&rule.custom_attributes);
350 self.rule_ids
351 .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
352 compiled_batch.push(crate::compiler::compile_rule(rule)?);
353 }
354 } else {
355 for rule in &collection.rules {
356 let mut transformed = rule.clone();
357 apply_pipelines(&self.pipelines, &mut transformed)?;
358 self.apply_custom_attributes(&transformed.custom_attributes);
359 self.rule_ids.push((
360 transformed.id.clone(),
361 transformed.name.clone(),
362 transformed.title.clone(),
363 ));
364 compiled_batch.push(crate::compiler::compile_rule(&transformed)?);
366 }
367 }
368 self.engine.extend_compiled_rules(compiled_batch);
369 for filter in &collection.filters {
371 self.engine.apply_filter(filter)?;
372 }
373 for corr in &collection.correlations {
374 self.add_correlation(corr)?;
375 }
376 self.validate_rule_refs()?;
377 self.detect_correlation_cycles()?;
378 Ok(())
379 }
380
381 fn validate_rule_refs(&self) -> Result<()> {
384 let mut known: std::collections::HashSet<&str> = std::collections::HashSet::new();
385
386 for (id, name, _) in &self.rule_ids {
387 if let Some(id) = id {
388 known.insert(id.as_str());
389 }
390 if let Some(name) = name {
391 known.insert(name.as_str());
392 }
393 }
394 for corr in &self.correlations {
395 if let Some(ref id) = corr.id {
396 known.insert(id.as_str());
397 }
398 if let Some(ref name) = corr.name {
399 known.insert(name.as_str());
400 }
401 }
402
403 for corr in &self.correlations {
404 for rule_ref in &corr.rule_refs {
405 if !known.contains(rule_ref.as_str()) {
406 return Err(EvalError::UnknownRuleRef(rule_ref.clone()));
407 }
408 }
409 }
410 Ok(())
411 }
412
413 fn detect_correlation_cycles(&self) -> Result<()> {
421 let mut corr_identifiers: HashMap<&str, usize> = HashMap::new();
423 for (idx, corr) in self.correlations.iter().enumerate() {
424 if let Some(ref id) = corr.id {
425 corr_identifiers.insert(id.as_str(), idx);
426 }
427 if let Some(ref name) = corr.name {
428 corr_identifiers.insert(name.as_str(), idx);
429 }
430 }
431
432 let mut adj: Vec<Vec<usize>> = vec![Vec::new(); self.correlations.len()];
434 for (idx, corr) in self.correlations.iter().enumerate() {
435 for rule_ref in &corr.rule_refs {
436 if let Some(&target_idx) = corr_identifiers.get(rule_ref.as_str()) {
437 adj[idx].push(target_idx);
438 }
439 }
440 }
441
442 let mut state = vec![0u8; self.correlations.len()]; let mut path: Vec<usize> = Vec::new();
445
446 for start in 0..self.correlations.len() {
447 if state[start] == 0
448 && let Some(cycle) = Self::dfs_find_cycle(start, &adj, &mut state, &mut path)
449 {
450 let names: Vec<String> = cycle
451 .iter()
452 .map(|&i| {
453 self.correlations[i]
454 .id
455 .as_deref()
456 .or(self.correlations[i].name.as_deref())
457 .unwrap_or(&self.correlations[i].title)
458 .to_string()
459 })
460 .collect();
461 return Err(crate::error::EvalError::CorrelationCycle(
462 names.join(" -> "),
463 ));
464 }
465 }
466 Ok(())
467 }
468
469 fn dfs_find_cycle(
471 node: usize,
472 adj: &[Vec<usize>],
473 state: &mut [u8],
474 path: &mut Vec<usize>,
475 ) -> Option<Vec<usize>> {
476 state[node] = 1; path.push(node);
478
479 for &next in &adj[node] {
480 if state[next] == 1 {
481 if let Some(pos) = path.iter().position(|&n| n == next) {
483 let mut cycle = path[pos..].to_vec();
484 cycle.push(next); return Some(cycle);
486 }
487 }
488 if state[next] == 0
489 && let Some(cycle) = Self::dfs_find_cycle(next, adj, state, path)
490 {
491 return Some(cycle);
492 }
493 }
494
495 path.pop();
496 state[node] = 2; None
498 }
499
500 pub fn process_event<E: Event>(&mut self, event: &E) -> ProcessResult
506 where
507 L: ExtractLogSource<E>,
508 {
509 let detections = self.engine.evaluate_identified(event);
510 self.correlate_identified_detections(event, detections)
511 }
512
513 pub fn correlate_detections(
523 &mut self,
524 event: &impl Event,
525 all_detections: Vec<EvaluationResult>,
526 ) -> ProcessResult {
527 let identities = all_detections
528 .iter()
529 .map(|detection| self.find_rule_identity(detection))
530 .collect();
531 self.correlate_with_identities(event, all_detections, identities)
532 }
533
534 pub(crate) fn correlate_identified_detections(
535 &mut self,
536 event: &impl Event,
537 detections: Vec<IdentifiedEvaluation>,
538 ) -> ProcessResult {
539 let (all_detections, identities) = split_identified(detections);
540 self.correlate_with_identities(event, all_detections, identities)
541 }
542
543 fn correlate_with_identities(
544 &mut self,
545 event: &impl Event,
546 all_detections: Vec<EvaluationResult>,
547 identities: Vec<RuleIdentity>,
548 ) -> ProcessResult {
549 let ts = match self.extract_event_timestamp(event) {
550 Some(ts) => ts,
551 None => match self.config.timestamp_fallback {
552 TimestampFallback::WallClock => Utc::now().timestamp(),
553 TimestampFallback::Skip => {
554 return self.filter_detections(all_detections, identities);
556 }
557 },
558 };
559 self.process_with_detection_identities(event, all_detections, identities, ts)
560 }
561
562 pub fn process_event_at<E: Event>(&mut self, event: &E, timestamp_secs: i64) -> ProcessResult
567 where
568 L: ExtractLogSource<E>,
569 {
570 let detections = self.engine.evaluate_identified(event);
571 let (all_detections, identities) = split_identified(detections);
572 self.process_with_detection_identities(event, all_detections, identities, timestamp_secs)
573 }
574
575 pub fn process_with_detections(
587 &mut self,
588 event: &impl Event,
589 all_detections: Vec<EvaluationResult>,
590 timestamp_secs: i64,
591 ) -> ProcessResult {
592 let identities = all_detections
593 .iter()
594 .map(|detection| self.find_rule_identity(detection))
595 .collect();
596 self.process_with_detection_identities(event, all_detections, identities, timestamp_secs)
597 }
598
599 fn process_with_detection_identities(
600 &mut self,
601 event: &impl Event,
602 all_detections: Vec<EvaluationResult>,
603 identities: Vec<RuleIdentity>,
604 timestamp_secs: i64,
605 ) -> ProcessResult {
606 let timestamp_secs = timestamp_secs.clamp(0, i64::MAX / 2);
607
608 if self.state.len() >= self.config.max_state_entries {
610 self.evict_all(timestamp_secs);
611 }
612
613 let mut correlations: Vec<EvaluationResult> = Vec::new();
615 let mut fired_indices = Vec::new();
616 self.feed_detections(
617 event,
618 &identities,
619 timestamp_secs,
620 &mut correlations,
621 &mut fired_indices,
622 );
623
624 let mut chained = Vec::new();
627 let mut chained_indices = Vec::new();
628 self.chain_correlations(
629 &correlations,
630 &fired_indices,
631 timestamp_secs,
632 &mut chained,
633 &mut chained_indices,
634 );
635 correlations.extend(chained);
636 fired_indices.extend(chained_indices);
637
638 let mut out = self.filter_detections(all_detections, identities);
641 out.extend(
642 correlations
643 .into_iter()
644 .zip(fired_indices)
645 .filter(|(_, idx)| {
646 let corr = &self.correlations[*idx];
647 let identities = corr.id.as_deref().into_iter().chain(corr.name.as_deref());
648 !self.is_correlation_only(identities)
649 })
650 .map(|(result, _)| result),
651 );
652 out
653 }
654
655 pub fn evaluate<E: Event>(&self, event: &E) -> Vec<EvaluationResult>
662 where
663 L: ExtractLogSource<E>,
664 {
665 self.engine.evaluate(event)
666 }
667
668 pub fn process_batch<E: Event + Sync>(&mut self, events: &[&E]) -> Vec<ProcessResult>
676 where
677 L: ExtractLogSource<E> + Sync,
678 {
679 let engine = &self.engine;
682 let ts_fields = &self.config.timestamp_fields;
683
684 let batch_results: Vec<(Vec<IdentifiedEvaluation>, Option<i64>)> = {
685 #[cfg(feature = "parallel")]
686 {
687 use rayon::prelude::*;
688 events
689 .par_iter()
690 .map(|e| {
691 let detections = engine.evaluate_identified(e);
692 let ts = extract_event_ts(e, ts_fields);
693 (detections, ts)
694 })
695 .collect()
696 }
697 #[cfg(not(feature = "parallel"))]
698 {
699 events
700 .iter()
701 .map(|e| {
702 let detections = engine.evaluate_identified(e);
703 let ts = extract_event_ts(e, ts_fields);
704 (detections, ts)
705 })
706 .collect()
707 }
708 };
709
710 let mut results = Vec::with_capacity(events.len());
712 for ((identified, ts_opt), event) in batch_results.into_iter().zip(events) {
713 let (detections, identities) = split_identified(identified);
714 let ts = match ts_opt {
715 Some(ts) => ts,
716 None => match self.config.timestamp_fallback {
717 TimestampFallback::WallClock => Utc::now().timestamp(),
718 TimestampFallback::Skip => {
719 results.push(self.filter_detections(detections, identities));
721 continue;
722 }
723 },
724 };
725 results.push(self.process_with_detection_identities(event, detections, identities, ts));
726 }
727 results
728 }
729
730 fn filter_detections(
735 &self,
736 all_detections: Vec<EvaluationResult>,
737 identities: Vec<RuleIdentity>,
738 ) -> Vec<EvaluationResult> {
739 if !self.config.emit_detections && !self.correlation_only_rules.is_empty() {
740 all_detections
741 .into_iter()
742 .zip(identities)
743 .filter_map(|(detection, (id, name))| {
744 let identities = id.as_deref().into_iter().chain(name.as_deref());
745 (!self.is_correlation_only(identities)).then_some(detection)
746 })
747 .collect()
748 } else {
749 all_detections
750 }
751 }
752
753 fn is_correlation_only<'a>(
757 &self,
758 mut identities: impl Iterator<Item = &'a str> + Clone,
759 ) -> bool {
760 !self.config.emit_detections
761 && identities
762 .clone()
763 .any(|identity| self.correlation_only_rules.contains(identity))
764 && !identities.any(|identity| self.generated_rules.contains(identity))
765 }
766
767 fn feed_detections(
769 &mut self,
770 event: &impl Event,
771 identities: &[RuleIdentity],
772 ts: i64,
773 out: &mut Vec<EvaluationResult>,
774 fired_indices: &mut Vec<usize>,
775 ) {
776 let mut work: Vec<(usize, Option<String>, Option<String>)> = Vec::new();
779
780 for (rule_id, rule_name) in identities {
781 let mut corr_indices = Vec::new();
783 if let Some(id) = rule_id
784 && let Some(indices) = self.rule_index.get(id)
785 {
786 corr_indices.extend(indices);
787 }
788 if let Some(name) = rule_name
789 && let Some(indices) = self.rule_index.get(name)
790 {
791 corr_indices.extend(indices);
792 }
793
794 corr_indices.sort_unstable();
795 corr_indices.dedup();
796
797 for &corr_idx in &corr_indices {
798 work.push((corr_idx, rule_id.clone(), rule_name.clone()));
799 }
800 }
801
802 for (corr_idx, rule_id, rule_name) in work {
803 let before = out.len();
804 self.update_correlation(corr_idx, event, ts, &rule_id, &rule_name, out);
805 if out.len() > before {
806 fired_indices.push(corr_idx);
807 }
808 }
809 }
810
811 fn find_rule_identity(&self, det: &EvaluationResult) -> RuleIdentity {
813 if let Some(ref match_id) = det.header.rule_id {
815 for (id, name, _) in &self.rule_ids {
816 if id.as_deref() == Some(match_id.as_str()) {
817 return (id.clone(), name.clone());
818 }
819 }
820 }
821
822 let mut title_matches = self
826 .rule_ids
827 .iter()
828 .filter(|(_, _, title)| title == &det.header.rule_title);
829 if let Some((id, name, _)) = title_matches.next()
830 && title_matches.next().is_none()
831 {
832 return (id.clone(), name.clone());
833 }
834
835 (det.header.rule_id.clone(), None)
836 }
837
838 fn resolve_event_mode(&self, corr_idx: usize) -> CorrelationEventMode {
840 let corr = &self.correlations[corr_idx];
841 corr.event_mode
842 .unwrap_or(self.config.correlation_event_mode)
843 }
844
845 fn resolve_max_events(&self, corr_idx: usize) -> usize {
847 let corr = &self.correlations[corr_idx];
848 corr.max_events
849 .unwrap_or(self.config.max_correlation_events)
850 }
851
852 fn resolve_max_group_entries(&self, corr_idx: usize) -> Option<usize> {
855 let corr = &self.correlations[corr_idx];
856 corr.max_group_entries.or(self.config.max_group_entries)
857 }
858
859 fn update_correlation(
861 &mut self,
862 corr_idx: usize,
863 event: &impl Event,
864 ts: i64,
865 rule_id: &Option<String>,
866 rule_name: &Option<String>,
867 out: &mut Vec<EvaluationResult>,
868 ) {
869 let corr = &self.correlations[corr_idx];
873 let corr_type = corr.correlation_type;
874 let timespan = corr.timespan_secs;
875 let window_mode = corr.window_mode;
876 let gap_secs = corr.gap_secs;
877 let level = corr.level;
878 let suppress_secs = corr.suppress_secs.or(self.config.suppress);
879 let action = corr.action.unwrap_or(self.config.action_on_match);
880 let event_mode = self.resolve_event_mode(corr_idx);
881 let max_events = self.resolve_max_events(corr_idx);
882 let max_group_entries = self.resolve_max_group_entries(corr_idx);
883
884 let mut ref_strs: Vec<&str> = Vec::new();
886 if let Some(id) = rule_id.as_deref() {
887 ref_strs.push(id);
888 }
889 if let Some(name) = rule_name.as_deref() {
890 ref_strs.push(name);
891 }
892 let rule_ref = ref_strs
893 .iter()
894 .copied()
895 .find(|identity| corr.rule_refs.iter().any(|rule_ref| rule_ref == identity))
896 .unwrap_or("");
897
898 let Some(group_key) = GroupKey::extract(event, &corr.group_by, &ref_strs) else {
901 return;
902 };
903
904 let state_key = (corr_idx, group_key.clone());
906 let state = self
907 .state
908 .entry(state_key.clone())
909 .or_insert_with(|| WindowState::new_for(corr_type));
910
911 let cutoff = ts - timespan as i64;
917 let decision = apply_window_open(state, ts, timespan, window_mode, gap_secs);
918 if decision == WindowDecision::Discard {
919 return;
920 }
921 let reset = decision == WindowDecision::Reset;
922
923 match corr_type {
925 CorrelationType::EventCount => {
926 state.push_event_count(ts);
927 }
928 CorrelationType::ValueCount => {
929 if let Some(ref fields) = corr.condition.field
930 && let Some(key) = composite_value_count_key(event, fields)
931 {
932 state.push_value_count(ts, key);
933 }
934 }
935 CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
936 state.push_temporal(ts, rule_ref);
937 }
938 CorrelationType::ValueSum
939 | CorrelationType::ValueAvg
940 | CorrelationType::ValuePercentile
941 | CorrelationType::ValueMedian => {
942 if let Some(ref fields) = corr.condition.field
943 && let Some(field_name) = fields.first()
944 && let Some(val) = event.get_field(field_name)
945 && let Some(n) = value_to_f64_ev(&val)
946 {
947 state.push_numeric(ts, n);
948 }
949 }
950 }
951
952 if let Some(cap) = max_group_entries {
956 state.truncate_oldest(cap, window_mode == WindowMode::Session);
957 }
958
959 match event_mode {
963 CorrelationEventMode::Full => {
964 let buf = self
965 .event_buffers
966 .entry(state_key.clone())
967 .or_insert_with(|| EventBuffer::new(max_events));
968 if window_mode == rsigma_parser::WindowMode::Sliding {
969 buf.evict(cutoff);
970 } else if reset {
971 buf.clear();
972 }
973 let json = event.to_json();
974 buf.push(ts, &json);
975 }
976 CorrelationEventMode::Refs => {
977 let buf = self
978 .event_ref_buffers
979 .entry(state_key.clone())
980 .or_insert_with(|| EventRefBuffer::new(max_events));
981 if window_mode == rsigma_parser::WindowMode::Sliding {
982 buf.evict(cutoff);
983 } else if reset {
984 buf.clear();
985 }
986 let json = event.to_json();
987 buf.push(ts, &json);
988 }
989 CorrelationEventMode::None => {}
990 }
991
992 let fired = state.check_condition(
994 &corr.condition,
995 corr_type,
996 &corr.rule_refs,
997 corr.extended_expr.as_ref(),
998 );
999
1000 if let Some(agg_value) = fired {
1001 let alert_key = (corr_idx, group_key.clone());
1002
1003 let suppressed = if let Some(suppress) = suppress_secs {
1005 if let Some(&last_ts) = self.last_alert.get(&alert_key) {
1006 (ts - last_ts) < suppress as i64
1007 } else {
1008 false
1009 }
1010 } else {
1011 false
1012 };
1013
1014 if !suppressed {
1015 let (events, event_refs) = match event_mode {
1017 CorrelationEventMode::Full => {
1018 let stored = self
1019 .event_buffers
1020 .get(&alert_key)
1021 .map(|buf| buf.decompress_all())
1022 .unwrap_or_default();
1023 (Some(stored), None)
1024 }
1025 CorrelationEventMode::Refs => {
1026 let stored = self
1027 .event_ref_buffers
1028 .get(&alert_key)
1029 .map(|buf| buf.refs())
1030 .unwrap_or_default();
1031 (None, Some(stored))
1032 }
1033 CorrelationEventMode::None => (None, None),
1034 };
1035
1036 let corr = &self.correlations[corr_idx];
1038 let result = EvaluationResult {
1039 header: RuleHeader {
1040 rule_title: corr.title.clone(),
1041 rule_id: corr.id.clone(),
1042 level,
1043 tags: corr.tags.clone(),
1044 custom_attributes: corr.custom_attributes.clone(),
1045 enrichments: None,
1046 },
1047 body: ResultBody::Correlation(CorrelationBody {
1048 correlation_type: corr_type,
1049 group_key: group_key.to_pairs(&corr.group_by),
1050 aggregated_value: agg_value,
1051 timespan_secs: timespan,
1052 events,
1053 event_refs,
1054 }),
1055 };
1056 out.push(result);
1057
1058 self.last_alert.insert(alert_key.clone(), ts);
1060
1061 if action == CorrelationAction::Reset {
1063 if let Some(state) = self.state.get_mut(&alert_key) {
1064 state.clear();
1065 }
1066 if let Some(buf) = self.event_buffers.get_mut(&alert_key) {
1067 buf.clear();
1068 }
1069 if let Some(buf) = self.event_ref_buffers.get_mut(&alert_key) {
1070 buf.clear();
1071 }
1072 }
1073 }
1074 }
1075 }
1076
1077 fn chain_lookup_keys(&self, corr_idx: usize) -> Vec<String> {
1083 let corr = &self.correlations[corr_idx];
1084 let mut keys = Vec::with_capacity(2);
1085 keys.extend(corr.id.iter().cloned());
1086 if corr.name.as_ref() != corr.id.as_ref() {
1087 keys.extend(corr.name.iter().cloned());
1088 }
1089 keys
1090 }
1091
1092 fn chain_correlations(
1099 &mut self,
1100 fired: &[EvaluationResult],
1101 fired_indices: &[usize],
1102 ts: i64,
1103 out: &mut Vec<EvaluationResult>,
1104 out_indices: &mut Vec<usize>,
1105 ) {
1106 debug_assert_eq!(fired.len(), fired_indices.len());
1107 let mut pending: Vec<(usize, Vec<(String, String)>)> = fired_indices
1111 .iter()
1112 .zip(fired)
1113 .filter_map(|(&idx, result)| Some((idx, result.as_correlation()?.group_key.clone())))
1114 .collect();
1115 let mut depth = 0;
1116
1117 while !pending.is_empty() && depth < MAX_CHAIN_DEPTH {
1118 depth += 1;
1119
1120 #[allow(clippy::type_complexity)]
1122 let mut work: Vec<(usize, Vec<(String, String)>, String)> = Vec::new();
1123 let mut seen = std::collections::HashSet::<(usize, String)>::new();
1124 for (source_idx, group_key) in &pending {
1125 for key in self.chain_lookup_keys(*source_idx) {
1126 if let Some(indices) = self.rule_index.get(&key) {
1127 for &corr_idx in indices {
1128 if seen.insert((corr_idx, key.clone())) {
1129 work.push((corr_idx, group_key.clone(), key.clone()));
1130 }
1131 }
1132 }
1133 }
1134 }
1135
1136 let mut next_pending = Vec::new();
1137 for (corr_idx, group_key_pairs, fired_ref) in work {
1138 let corr = &self.correlations[corr_idx];
1139 let corr_type = corr.correlation_type;
1140 let timespan = corr.timespan_secs;
1141 let window_mode = corr.window_mode;
1142 let gap_secs = corr.gap_secs;
1143 let level = corr.level;
1144 let suppress_secs = corr.suppress_secs.or(self.config.suppress);
1145 let action = corr.action.unwrap_or(self.config.action_on_match);
1146
1147 let Some(group_key) = GroupKey::from_pairs(&group_key_pairs, &corr.group_by) else {
1148 continue;
1149 };
1150 let state_key = (corr_idx, group_key.clone());
1151 let state = self
1152 .state
1153 .entry(state_key.clone())
1154 .or_insert_with(|| WindowState::new_for(corr_type));
1155
1156 if apply_window_open(state, ts, timespan, window_mode, gap_secs)
1160 == WindowDecision::Discard
1161 {
1162 continue;
1163 }
1164
1165 match corr_type {
1166 CorrelationType::EventCount => {
1167 state.push_event_count(ts);
1168 }
1169 CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
1170 state.push_temporal(ts, &fired_ref);
1171 }
1172 _ => {
1173 state.push_event_count(ts);
1174 }
1175 }
1176
1177 if let Some(cap) = corr.max_group_entries.or(self.config.max_group_entries) {
1180 state.truncate_oldest(cap, window_mode == WindowMode::Session);
1181 }
1182
1183 let fired = state.check_condition(
1184 &corr.condition,
1185 corr_type,
1186 &corr.rule_refs,
1187 corr.extended_expr.as_ref(),
1188 );
1189
1190 if let Some(agg_value) = fired {
1191 let alert_key = state_key;
1192 let suppressed = if let Some(suppress) = suppress_secs {
1193 self.last_alert
1194 .get(&alert_key)
1195 .is_some_and(|&last_ts| (ts - last_ts) < suppress as i64)
1196 } else {
1197 false
1198 };
1199 if suppressed {
1200 continue;
1201 }
1202
1203 let corr = &self.correlations[corr_idx];
1204 let fired_group_key = group_key.to_pairs(&corr.group_by);
1205 let result = EvaluationResult {
1206 header: RuleHeader {
1207 rule_title: corr.title.clone(),
1208 rule_id: corr.id.clone(),
1209 level,
1210 tags: corr.tags.clone(),
1211 custom_attributes: corr.custom_attributes.clone(),
1212 enrichments: None,
1213 },
1214 body: ResultBody::Correlation(CorrelationBody {
1215 correlation_type: corr_type,
1216 group_key: fired_group_key.clone(),
1217 aggregated_value: agg_value,
1218 timespan_secs: timespan,
1219 events: None,
1223 event_refs: None,
1224 }),
1225 };
1226 next_pending.push((corr_idx, fired_group_key));
1227 out.push(result);
1228 out_indices.push(corr_idx);
1229 self.last_alert.insert(alert_key.clone(), ts);
1230
1231 if action == CorrelationAction::Reset
1232 && let Some(state) = self.state.get_mut(&alert_key)
1233 {
1234 state.clear();
1235 }
1236 }
1237 }
1238
1239 pending = next_pending;
1240 }
1241
1242 if !pending.is_empty() {
1243 log::warn!(
1244 "Correlation chain depth limit reached ({MAX_CHAIN_DEPTH}); \
1245 {} pending result(s) were not propagated further. \
1246 This may indicate a cycle in correlation references.",
1247 pending.len()
1248 );
1249 }
1250 }
1251
1252 fn extract_event_timestamp(&self, event: &impl Event) -> Option<i64> {
1265 for field_name in &self.config.timestamp_fields {
1266 if let Some(val) = event.get_field(field_name)
1267 && let Some(ts) = parse_timestamp_value(&val)
1268 {
1269 return Some(ts);
1270 }
1271 }
1272 None
1273 }
1274
1275 pub fn evict_expired(&mut self, now_secs: i64) {
1281 self.evict_all(now_secs);
1282 }
1283
1284 fn evict_all(&mut self, now_secs: i64) {
1286 let specs: Vec<(u64, WindowMode, Option<u64>)> = self
1297 .correlations
1298 .iter()
1299 .map(|c| (c.timespan_secs, c.window_mode, c.gap_secs))
1300 .collect();
1301
1302 self.state.retain(|&(corr_idx, _), state| {
1303 if let Some(&(timespan, mode, gap)) = specs.get(corr_idx) {
1304 match mode {
1305 WindowMode::Sliding => {
1306 state.evict(now_secs - timespan as i64);
1307 }
1308 WindowMode::Tumbling | WindowMode::Session => {
1309 let staleness = if mode == WindowMode::Session {
1310 gap.unwrap_or(timespan)
1311 } else {
1312 timespan
1313 } as i64;
1314 if state
1315 .latest_timestamp()
1316 .is_some_and(|last| now_secs - last > staleness)
1317 {
1318 state.clear();
1319 }
1320 }
1321 }
1322 }
1323 !state.is_empty()
1324 });
1325
1326 let state = &self.state;
1330 self.event_buffers.retain(|key, buf| {
1331 if let Some(&(timespan, mode, _)) = specs.get(key.0) {
1332 match mode {
1333 WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
1334 WindowMode::Tumbling | WindowMode::Session => {
1335 if !state.contains_key(key) {
1336 return false;
1337 }
1338 }
1339 }
1340 }
1341 !buf.is_empty()
1342 });
1343 self.event_ref_buffers.retain(|key, buf| {
1344 if let Some(&(timespan, mode, _)) = specs.get(key.0) {
1345 match mode {
1346 WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
1347 WindowMode::Tumbling | WindowMode::Session => {
1348 if !state.contains_key(key) {
1349 return false;
1350 }
1351 }
1352 }
1353 }
1354 !buf.is_empty()
1355 });
1356
1357 if self.state.len() >= self.config.max_state_entries {
1361 let target = self.config.max_state_entries * 9 / 10;
1362 let excess = self.state.len() - target;
1363
1364 log::warn!(
1365 "Correlation state hard cap reached ({} entries, max {}); \
1366 evicting {} stalest entries to {} (90% capacity). \
1367 This indicates high-cardinality traffic; consider raising \
1368 max_state_entries or shortening correlation windows.",
1369 self.state.len(),
1370 self.config.max_state_entries,
1371 excess,
1372 target,
1373 );
1374
1375 let mut by_staleness: Vec<_> = self
1378 .state
1379 .iter()
1380 .map(|(k, v)| (k, v.latest_timestamp().unwrap_or(i64::MIN)))
1381 .collect();
1382 if excess < by_staleness.len() {
1383 by_staleness.select_nth_unstable_by_key(excess, |&(_, ts)| ts);
1384 }
1385 let stalest: Vec<_> = by_staleness
1386 .iter()
1387 .take(excess)
1388 .map(|&(k, _)| k.clone())
1389 .collect();
1390
1391 for key in stalest {
1393 self.state.remove(&key);
1394 self.last_alert.remove(&key);
1395 self.event_buffers.remove(&key);
1396 self.event_ref_buffers.remove(&key);
1397 }
1398 }
1399
1400 self.last_alert.retain(|key, &mut alert_ts| {
1403 let suppress = if key.0 < self.correlations.len() {
1404 self.correlations[key.0]
1405 .suppress_secs
1406 .or(self.config.suppress)
1407 .unwrap_or(0)
1408 } else {
1409 0
1410 };
1411 (now_secs - alert_ts) < suppress as i64
1412 });
1413 }
1414
1415 pub fn state_count(&self) -> usize {
1417 self.state.len()
1418 }
1419
1420 pub fn detection_rule_count(&self) -> usize {
1422 self.engine.rule_count()
1423 }
1424
1425 pub fn correlation_rule_count(&self) -> usize {
1427 self.correlations.len()
1428 }
1429
1430 pub fn event_buffer_count(&self) -> usize {
1432 self.event_buffers.len()
1433 }
1434
1435 pub fn event_buffer_bytes(&self) -> usize {
1437 self.event_buffers
1438 .values()
1439 .map(|b| b.compressed_bytes())
1440 .sum()
1441 }
1442
1443 pub fn event_ref_buffer_count(&self) -> usize {
1445 self.event_ref_buffers.len()
1446 }
1447
1448 pub fn engine(&self) -> &Engine<L> {
1450 &self.engine
1451 }
1452
1453 pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
1457 let mut variants = Vec::new();
1458 self.collect_rule_metadata(key, &mut variants);
1459 RuleMetadataLookup::from_variants(variants)
1460 }
1461
1462 pub(crate) fn collect_rule_metadata(&self, key: &str, out: &mut Vec<RuleBundleMetadata>) {
1463 self.engine.collect_rule_metadata(key, out);
1464 crate::rule_metadata::matching_correlations(&self.correlations, key, out);
1465 }
1466
1467 pub fn export_state(&self) -> CorrelationSnapshot {
1473 let mut windows: HashMap<String, Vec<(GroupKey, WindowState)>> = HashMap::new();
1474 for ((idx, gk), ws) in &self.state {
1475 let corr_id = self.correlation_stable_id(*idx);
1476 windows
1477 .entry(corr_id)
1478 .or_default()
1479 .push((gk.clone(), ws.clone()));
1480 }
1481
1482 let mut last_alert: HashMap<String, Vec<(GroupKey, i64)>> = HashMap::new();
1483 for ((idx, gk), ts) in &self.last_alert {
1484 let corr_id = self.correlation_stable_id(*idx);
1485 last_alert
1486 .entry(corr_id)
1487 .or_default()
1488 .push((gk.clone(), *ts));
1489 }
1490
1491 let mut event_buffers: HashMap<String, Vec<(GroupKey, EventBuffer)>> = HashMap::new();
1492 for ((idx, gk), buf) in &self.event_buffers {
1493 let corr_id = self.correlation_stable_id(*idx);
1494 event_buffers
1495 .entry(corr_id)
1496 .or_default()
1497 .push((gk.clone(), buf.clone()));
1498 }
1499
1500 let mut event_ref_buffers: HashMap<String, Vec<(GroupKey, EventRefBuffer)>> =
1501 HashMap::new();
1502 for ((idx, gk), buf) in &self.event_ref_buffers {
1503 let corr_id = self.correlation_stable_id(*idx);
1504 event_ref_buffers
1505 .entry(corr_id)
1506 .or_default()
1507 .push((gk.clone(), buf.clone()));
1508 }
1509
1510 CorrelationSnapshot {
1511 version: SNAPSHOT_VERSION,
1512 windows,
1513 last_alert,
1514 event_buffers,
1515 event_ref_buffers,
1516 }
1517 }
1518
1519 pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
1526 if snapshot.version != SNAPSHOT_VERSION {
1527 return false;
1528 }
1529 let id_to_idx = self.build_id_to_index_map();
1530
1531 for (corr_id, groups) in snapshot.windows {
1532 if let Some(&idx) = id_to_idx.get(&corr_id) {
1533 for (gk, ws) in groups {
1534 self.state.insert((idx, gk), ws);
1535 }
1536 }
1537 }
1538
1539 for (corr_id, groups) in snapshot.last_alert {
1540 if let Some(&idx) = id_to_idx.get(&corr_id) {
1541 for (gk, ts) in groups {
1542 self.last_alert.insert((idx, gk), ts);
1543 }
1544 }
1545 }
1546
1547 for (corr_id, groups) in snapshot.event_buffers {
1548 if let Some(&idx) = id_to_idx.get(&corr_id) {
1549 for (gk, buf) in groups {
1550 self.event_buffers.insert((idx, gk), buf);
1551 }
1552 }
1553 }
1554
1555 for (corr_id, groups) in snapshot.event_ref_buffers {
1556 if let Some(&idx) = id_to_idx.get(&corr_id) {
1557 for (gk, buf) in groups {
1558 self.event_ref_buffers.insert((idx, gk), buf);
1559 }
1560 }
1561 }
1562
1563 true
1564 }
1565
1566 fn correlation_stable_id(&self, idx: usize) -> String {
1568 let corr = &self.correlations[idx];
1569 corr.id
1570 .clone()
1571 .or_else(|| corr.name.clone())
1572 .unwrap_or_else(|| corr.title.clone())
1573 }
1574
1575 fn build_id_to_index_map(&self) -> HashMap<String, usize> {
1577 self.correlations
1578 .iter()
1579 .enumerate()
1580 .map(|(idx, _)| (self.correlation_stable_id(idx), idx))
1581 .collect()
1582 }
1583}
1584
1585impl Default for CorrelationEngine {
1586 fn default() -> Self {
1587 Self::new(CorrelationConfig::default())
1588 }
1589}
1590
1591fn split_identified(
1592 identified: Vec<IdentifiedEvaluation>,
1593) -> (Vec<EvaluationResult>, Vec<RuleIdentity>) {
1594 identified
1595 .into_iter()
1596 .map(|identified| {
1597 (
1598 identified.result,
1599 (identified.rule_id, identified.rule_name),
1600 )
1601 })
1602 .unzip()
1603}
1604
1605fn extract_event_ts(event: &impl Event, timestamp_fields: &[String]) -> Option<i64> {
1614 for field_name in timestamp_fields {
1615 if let Some(val) = event.get_field(field_name)
1616 && let Some(ts) = parse_timestamp_value(&val)
1617 {
1618 return Some(ts);
1619 }
1620 }
1621 None
1622}
1623
1624fn parse_timestamp_value(val: &EventValue) -> Option<i64> {
1629 match val {
1630 EventValue::Int(i) => epoch_seconds_from_int(*i),
1631 EventValue::Float(f) => epoch_seconds_from_float(*f),
1632 EventValue::Str(s) => parse_timestamp_str(s)
1633 .map(|dt| dt.timestamp())
1634 .filter(|ts| *ts >= 0),
1635 _ => None,
1636 }
1637}
1638
1639fn value_to_string_for_count(v: &EventValue) -> Option<String> {
1642 match v {
1643 EventValue::Null => Some("null".to_string()),
1644 v => v.as_str().map(Cow::into_owned),
1645 }
1646}
1647
1648fn composite_value_count_key(event: &impl Event, fields: &[String]) -> Option<String> {
1657 if let [field_name] = fields {
1659 let val = event.get_field(field_name)?;
1660 return value_to_string_for_count(&val);
1661 }
1662
1663 let mut parts = Vec::with_capacity(fields.len());
1664 for field_name in fields {
1665 let val = event.get_field(field_name)?;
1666 let rendered = value_to_string_for_count(&val)?;
1667 parts.push(rendered);
1668 }
1669 Some(parts.join("\u{1f}"))
1670}
1671
1672fn value_to_f64_ev(v: &EventValue) -> Option<f64> {
1674 v.as_f64()
1675}