rsigma-eval 0.28.0

Evaluator for Sigma detection and correlation rules: match rules against events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::collections::VecDeque;
use std::io::{Read as IoRead, Write as IoWrite};
use std::sync::Arc;

use flate2::Compression;
use flate2::read::DeflateDecoder;
use flate2::write::DeflateEncoder;
use serde::Serialize;

use crate::result::EventSource;

// =============================================================================
// Compressed Event Buffer
// =============================================================================

/// Default compression level — fast compression (level 1) for minimal latency.
/// Deflate level 1 still achieves ~2-3x compression on JSON while being very fast.
const COMPRESSION_LEVEL: Compression = Compression::fast();

/// One retained event body: the sequence number the event was processed with,
/// its timestamp, its deflate-compressed JSON, and where it came from.
#[derive(Debug, Clone)]
pub(crate) struct FullEntry {
    pub(crate) seq: u64,
    pub(crate) ts: i64,
    pub(crate) data: Vec<u8>,
    /// Referenced rule the event matched.
    pub(crate) rule: Option<Arc<str>>,
    /// Child correlation that delivered the event to this buffer.
    pub(crate) via: Option<Arc<str>>,
}

impl FullEntry {
    /// Convert this entry to a reference entry, keeping its sequence number
    /// and source.
    pub(crate) fn to_ref(&self) -> Option<RefEntry> {
        let event = decompress_event(&self.data)?;
        Some(RefEntry {
            r: EventRef {
                timestamp: self.ts,
                id: extract_event_id(&event),
            },
            seq: self.seq,
            rule: self.rule.clone(),
            via: self.via.clone(),
        })
    }
}

fn event_source(rule: &Option<Arc<str>>, via: &Option<Arc<str>>) -> EventSource {
    EventSource {
        rule: rule.as_deref().map(str::to_owned),
        via: via.as_deref().map(str::to_owned),
    }
}

/// Compressed event storage for correlation event inclusion.
///
/// Stores event JSON payloads as individually deflate-compressed blobs alongside
/// their timestamps. This enables per-event eviction (matching `WindowState`
/// eviction) while keeping memory usage low.
///
/// # Memory Model
///
/// Each stored event costs approximately `compressed_size + 24` bytes
/// (8 for timestamp, 16 for Vec overhead). Typical JSON events (500B–5KB)
/// compress to 100B–1KB with deflate, giving 3–5x memory savings.
///
/// The buffer enforces a hard cap (`max_events`) so memory is bounded at:
///   `max_events × (avg_compressed_size + 24)` bytes per group key.
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub struct EventBuffer {
    /// (timestamp, deflate-compressed event JSON) pairs, ordered by timestamp.
    #[serde(with = "event_buffer_serde")]
    entries: VecDeque<FullEntry>,
    /// Maximum number of events to retain. When exceeded, the oldest event is
    /// evicted regardless of the time window.
    max_events: usize,
}

/// Custom serde for EventBuffer entries: encodes compressed bytes as base64
/// instead of JSON number arrays, cutting snapshot size ~3x.
mod event_buffer_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::collections::VecDeque;
    use std::sync::Arc;

    use super::FullEntry;

    #[derive(Serialize, Deserialize)]
    struct Entry {
        ts: i64,
        #[serde(with = "base64_bytes")]
        data: Vec<u8>,
        #[serde(default)]
        seq: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        rule: Option<Arc<str>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        via: Option<Arc<str>>,
    }

    mod base64_bytes {
        use base64::Engine as _;
        use base64::engine::general_purpose::STANDARD;
        use serde::{Deserializer, Serializer};

        pub fn serialize<S: Serializer>(bytes: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
            s.serialize_str(&STANDARD.encode(bytes))
        }

        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
            let s: String = serde::Deserialize::deserialize(d)?;
            STANDARD.decode(s).map_err(serde::de::Error::custom)
        }
    }

    pub fn serialize<S: Serializer>(
        entries: &VecDeque<FullEntry>,
        s: S,
    ) -> Result<S::Ok, S::Error> {
        let v: Vec<Entry> = entries
            .iter()
            .map(|e| Entry {
                ts: e.ts,
                data: e.data.clone(),
                seq: e.seq,
                rule: e.rule.clone(),
                via: e.via.clone(),
            })
            .collect();
        v.serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<VecDeque<FullEntry>, D::Error> {
        let v: Vec<Entry> = Vec::deserialize(d)?;
        Ok(v.into_iter()
            .map(|e| FullEntry {
                seq: e.seq,
                ts: e.ts,
                data: e.data,
                rule: e.rule,
                via: e.via,
            })
            .collect())
    }
}

impl EventBuffer {
    /// Create a new event buffer with the given capacity cap.
    pub fn new(max_events: usize) -> Self {
        EventBuffer {
            entries: VecDeque::with_capacity(max_events.min(64)),
            max_events,
        }
    }

    /// Compress and store an event with sequence number 0, meaning unsequenced,
    /// and no source.
    pub fn push(&mut self, ts: i64, event: &serde_json::Value) {
        self.push_seq(0, ts, event, None);
    }

    /// Compress and store an event under its processing sequence number and
    /// the referenced rule it matched. Evicts the oldest entry if at capacity.
    pub(crate) fn push_seq(
        &mut self,
        seq: u64,
        ts: i64,
        event: &serde_json::Value,
        rule: Option<Arc<str>>,
    ) {
        // Compress the event JSON with deflate
        if let Some(compressed) = compress_event(event) {
            if self.entries.len() >= self.max_events {
                self.entries.pop_front();
            }
            self.entries.push_back(FullEntry {
                seq,
                ts,
                data: compressed,
                rule,
                via: None,
            });
        }
    }

    /// Remove all entries older than the cutoff timestamp.
    pub fn evict(&mut self, cutoff: i64) {
        while self.entries.front().is_some_and(|e| e.ts < cutoff) {
            self.entries.pop_front();
        }
    }

    /// Decompress and return all stored events.
    pub fn decompress_all(&self) -> Vec<serde_json::Value> {
        self.entries
            .iter()
            .filter_map(|e| decompress_event(&e.data))
            .collect()
    }

    /// Returns true if there are no stored events.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear all stored events.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Total compressed bytes stored (for monitoring/diagnostics).
    pub fn compressed_bytes(&self) -> usize {
        self.entries.iter().map(|e| e.data.len()).sum()
    }

    /// Number of stored events.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Snapshot of the retained entries, for a parent correlation to merge.
    pub(crate) fn retained(&self) -> Retained {
        Retained::Full(self.entries.iter().cloned().collect())
    }

    /// Merge entries delivered by the firing child correlation `via` into this
    /// buffer.
    ///
    /// Entries are inserted in `(timestamp, seq)` order with `via` as their
    /// source, an entry with a nonzero seq that is already present is skipped
    /// and keeps its existing source, and the oldest entries above the cap are
    /// dropped.
    pub(crate) fn merge(&mut self, entries: &[FullEntry], via: Option<&Arc<str>>) {
        for entry in entries {
            // An event is processed once with one timestamp, so a nonzero seq
            // always comes with the same `ts` and a duplicate sorts right
            // before the insertion point.
            let pos = self
                .entries
                .partition_point(|e| (e.ts, e.seq) <= (entry.ts, entry.seq));
            if entry.seq != 0 && pos > 0 && self.entries[pos - 1].seq == entry.seq {
                continue;
            }
            let mut entry = entry.clone();
            entry.via = via.cloned();
            self.entries.insert(pos, entry);
        }
        while self.entries.len() > self.max_events {
            self.entries.pop_front();
        }
    }

    /// Decompress the newest `n` entries, oldest first, with their sources
    /// index for index.
    pub(crate) fn newest_events(&self, n: usize) -> (Vec<serde_json::Value>, Vec<EventSource>) {
        let start = self.entries.len().saturating_sub(n);
        self.entries
            .iter()
            .skip(start)
            .filter_map(|e| Some((decompress_event(&e.data)?, event_source(&e.rule, &e.via))))
            .unzip()
    }

    /// Convert the newest `n` entries to event references, oldest first, with
    /// their sources index for index.
    pub(crate) fn newest_refs(&self, n: usize) -> (Vec<EventRef>, Vec<EventSource>) {
        let start = self.entries.len().saturating_sub(n);
        self.entries
            .iter()
            .skip(start)
            .filter_map(FullEntry::to_ref)
            .map(|e| {
                let source = event_source(&e.rule, &e.via);
                (e.r, source)
            })
            .unzip()
    }

    /// Highest sequence number currently retained.
    pub(crate) fn max_seq(&self) -> u64 {
        self.entries.iter().map(|e| e.seq).max().unwrap_or(0)
    }

    /// Assign fresh sequence numbers to entries restored without one.
    pub(crate) fn sequence_unsequenced(&mut self, next: &mut u64) {
        for entry in &mut self.entries {
            if entry.seq == 0 {
                entry.seq = *next;
                *next = next.saturating_add(1);
            }
        }
    }
}

/// Compress an event JSON value using deflate.
pub(super) fn compress_event(event: &serde_json::Value) -> Option<Vec<u8>> {
    let json_bytes = serde_json::to_vec(event).ok()?;
    let mut encoder = DeflateEncoder::new(Vec::new(), COMPRESSION_LEVEL);
    encoder.write_all(&json_bytes).ok()?;
    encoder.finish().ok()
}

/// Decompress a deflate-compressed event back to a JSON value.
pub(super) fn decompress_event(compressed: &[u8]) -> Option<serde_json::Value> {
    let mut decoder = DeflateDecoder::new(compressed);
    let mut json_bytes = Vec::new();
    decoder.read_to_end(&mut json_bytes).ok()?;
    serde_json::from_slice(&json_bytes).ok()
}

// =============================================================================
// Event Reference (lightweight mode)
// =============================================================================

/// A lightweight event reference: timestamp plus optional event ID.
///
/// Used in `Refs` mode for memory-efficient correlation event tracking.
/// Each ref costs ~40 bytes (vs. 100–1000+ bytes for compressed events),
/// making this mode suitable for high-volume correlations where only
/// traceability is needed.
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub struct EventRef {
    /// Event timestamp (epoch seconds).
    pub timestamp: i64,
    /// Event ID extracted from common fields (`id`, `_id`, `event_id`, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
}

/// One retained event reference: the reference plus the sequence number the
/// event was processed with and where it came from.
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub(crate) struct RefEntry {
    #[serde(flatten)]
    pub(crate) r: EventRef,
    #[serde(default)]
    pub(crate) seq: u64,
    /// Referenced rule the event matched.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) rule: Option<Arc<str>>,
    /// Child correlation that delivered the event to this buffer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) via: Option<Arc<str>>,
}

/// Lightweight event reference buffer for `Refs` mode.
///
/// Stores only timestamps and optional event IDs — no event payload,
/// no compression. This is the minimal-memory alternative to `EventBuffer`.
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
pub struct EventRefBuffer {
    /// Event references, ordered by timestamp.
    entries: VecDeque<RefEntry>,
    /// Maximum number of refs to retain.
    max_events: usize,
}

impl EventRefBuffer {
    /// Create a new ref buffer with the given capacity cap.
    pub fn new(max_events: usize) -> Self {
        EventRefBuffer {
            entries: VecDeque::with_capacity(max_events.min(64)),
            max_events,
        }
    }

    /// Store a reference to an event with sequence number 0, meaning
    /// unsequenced, and no source.
    pub fn push(&mut self, ts: i64, event: &serde_json::Value) {
        self.push_seq(0, ts, event, None);
    }

    /// Store a reference to an event under its processing sequence number and
    /// the referenced rule it matched. Evicts the oldest ref if at capacity.
    pub(crate) fn push_seq(
        &mut self,
        seq: u64,
        ts: i64,
        event: &serde_json::Value,
        rule: Option<Arc<str>>,
    ) {
        if self.entries.len() >= self.max_events {
            self.entries.pop_front();
        }
        let id = extract_event_id(event);
        self.entries.push_back(RefEntry {
            r: EventRef { timestamp: ts, id },
            seq,
            rule,
            via: None,
        });
    }

    /// Remove all refs older than the cutoff timestamp.
    pub fn evict(&mut self, cutoff: i64) {
        while self.entries.front().is_some_and(|e| e.r.timestamp < cutoff) {
            self.entries.pop_front();
        }
    }

    /// Return cloned refs.
    pub fn refs(&self) -> Vec<EventRef> {
        self.entries.iter().map(|e| e.r.clone()).collect()
    }

    /// Returns true if there are no stored refs.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear all stored refs.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Number of stored refs.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Snapshot of the retained entries, for a parent correlation to merge.
    pub(crate) fn retained(&self) -> Retained {
        Retained::Refs(self.entries.iter().cloned().collect())
    }

    /// Merge entries delivered by the firing child correlation `via` into this
    /// buffer.
    ///
    /// Entries are inserted in `(timestamp, seq)` order with `via` as their
    /// source, an entry with a nonzero seq that is already present is skipped
    /// and keeps its existing source, and the oldest entries above the cap are
    /// dropped.
    pub(crate) fn merge(&mut self, entries: &[RefEntry], via: Option<&Arc<str>>) {
        for entry in entries {
            // See `EventBuffer::merge`: a duplicate sorts right before the
            // insertion point.
            let pos = self
                .entries
                .partition_point(|e| (e.r.timestamp, e.seq) <= (entry.r.timestamp, entry.seq));
            if entry.seq != 0 && pos > 0 && self.entries[pos - 1].seq == entry.seq {
                continue;
            }
            let mut entry = entry.clone();
            entry.via = via.cloned();
            self.entries.insert(pos, entry);
        }
        while self.entries.len() > self.max_events {
            self.entries.pop_front();
        }
    }

    /// Clone the newest `n` entries, oldest first, with their sources index
    /// for index.
    pub(crate) fn newest_refs(&self, n: usize) -> (Vec<EventRef>, Vec<EventSource>) {
        let start = self.entries.len().saturating_sub(n);
        self.entries
            .iter()
            .skip(start)
            .map(|e| (e.r.clone(), event_source(&e.rule, &e.via)))
            .unzip()
    }

    /// Highest sequence number currently retained.
    pub(crate) fn max_seq(&self) -> u64 {
        self.entries.iter().map(|e| e.seq).max().unwrap_or(0)
    }

    /// Assign fresh sequence numbers to entries restored without one.
    pub(crate) fn sequence_unsequenced(&mut self, next: &mut u64) {
        for entry in &mut self.entries {
            if entry.seq == 0 {
                entry.seq = *next;
                *next = next.saturating_add(1);
            }
        }
    }
}

/// Retained entries captured from a correlation that fired.
#[derive(Debug, Clone)]
pub(crate) enum Retained {
    /// Compressed event bodies.
    Full(Vec<FullEntry>),
    /// Lightweight event references.
    Refs(Vec<RefEntry>),
}

/// Try to extract an event ID from common fields.
///
/// Checks (in order): `id`, `_id`, `event_id`, `EventRecordID`, `event.id`.
/// Returns the first found value as a string.
pub(super) fn extract_event_id(event: &serde_json::Value) -> Option<String> {
    const ID_FIELDS: &[&str] = &["id", "_id", "event_id", "EventRecordID", "event.id"];
    for field in ID_FIELDS {
        if let Some(val) = event.get(field) {
            return match val {
                serde_json::Value::String(s) => Some(s.clone()),
                serde_json::Value::Number(n) => Some(n.to_string()),
                _ => None,
            };
        }
    }
    None
}