rsigma-eval 0.15.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
//! Unified result type for rule evaluation and correlation.
//!
//! `EvaluationResult` is the single output type produced by both detection
//! and correlation. Fields shared across kinds (rule metadata, custom
//! attributes, optional enrichments) live in [`RuleHeader`]; kind-specific
//! fields live in [`ResultBody`]. Both are merged into one flat top-level
//! JSON object via `#[serde(flatten)]` on the struct and `#[serde(untagged)]`
//! on the body enum.
//!
//! Downstream JSON consumers distinguish detection from correlation by the
//! presence of `correlation_type` (correlation-only) and `matched_fields`
//! (detection-only). The field set, values, and `skip_serializing_if`
//! behavior match the pre-unification `MatchResult` / `CorrelationResult`
//! layout; the only visible difference is that a non-empty
//! `custom_attributes` map is now emitted between header and body fields
//! rather than at the end of the line, which is invisible to compliant
//! JSON consumers (objects are unordered per spec). The wire-shape golden
//! tests under `crates/rsigma-eval/tests/wire_shape_golden.rs` pin the
//! new ordering for both kinds.

use std::collections::HashMap;
use std::sync::Arc;

use rsigma_parser::{CorrelationType, Level};
use serde::Serialize;

use crate::correlation::EventRef;

/// A single evaluation result.
///
/// Wraps a detection match ([`ResultBody::Detection`]) or a correlation
/// firing ([`ResultBody::Correlation`]) behind one shared [`RuleHeader`].
/// Serialize emits a single flat JSON object combining header and body
/// fields.
#[derive(Debug, Clone, Serialize)]
pub struct EvaluationResult {
    #[serde(flatten)]
    pub header: RuleHeader,
    #[serde(flatten)]
    pub body: ResultBody,
}

impl EvaluationResult {
    /// True when this result was produced by detection rule matching.
    pub fn is_detection(&self) -> bool {
        matches!(self.body, ResultBody::Detection(_))
    }

    /// True when this result was produced by a correlation firing.
    pub fn is_correlation(&self) -> bool {
        matches!(self.body, ResultBody::Correlation(_))
    }

    /// Read the detection-specific body, if this result is a detection.
    pub fn as_detection(&self) -> Option<&DetectionBody> {
        match &self.body {
            ResultBody::Detection(d) => Some(d),
            ResultBody::Correlation(_) => None,
        }
    }

    /// Read the correlation-specific body, if this result is a correlation.
    pub fn as_correlation(&self) -> Option<&CorrelationBody> {
        match &self.body {
            ResultBody::Correlation(c) => Some(c),
            ResultBody::Detection(_) => None,
        }
    }

    /// Mutable accessor for the detection-specific body.
    pub fn as_detection_mut(&mut self) -> Option<&mut DetectionBody> {
        match &mut self.body {
            ResultBody::Detection(d) => Some(d),
            ResultBody::Correlation(_) => None,
        }
    }

    /// Mutable accessor for the correlation-specific body.
    pub fn as_correlation_mut(&mut self) -> Option<&mut CorrelationBody> {
        match &mut self.body {
            ResultBody::Correlation(c) => Some(c),
            ResultBody::Detection(_) => None,
        }
    }
}

/// Fields shared between detection and correlation results.
///
/// The optional `enrichments` map is `None` for results emitted directly
/// by the engine; downstream middleware can populate it with arbitrary
/// JSON values to ride along with each result.
#[derive(Debug, Clone, Serialize)]
pub struct RuleHeader {
    /// Title of the matched rule.
    pub rule_title: String,
    /// ID of the matched rule (if present).
    pub rule_id: Option<String>,
    /// Severity level.
    pub level: Option<Level>,
    /// Tags from the matched rule.
    pub tags: Vec<String>,
    /// Custom attributes from the rule (merged with pipeline overrides).
    ///
    /// Wrapped in `Arc` so per-match cloning is a pointer bump.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub custom_attributes: Arc<HashMap<String, serde_json::Value>>,
    /// Optional map of arbitrary enrichment values, written by downstream
    /// middleware. `None` for engine-emitted results; skipped on serialize.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enrichments: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Kind-specific payload of an [`EvaluationResult`].
///
/// Serialized as an untagged enum so the variant fields flatten directly
/// into the parent JSON object. Downstream consumers disambiguate variants
/// by the kind-unique fields each variant carries (`matched_fields` for
/// detection, `correlation_type` for correlation).
///
/// Invariant: each variant must keep at least one required, kind-unique
/// field. This is what lets the untagged enum disambiguate on a future
/// `Deserialize` and keeps the `correlation_type`-presence rule reliable
/// for existing consumers.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ResultBody {
    /// Detection rule match (stateless, immediate).
    Detection(DetectionBody),
    /// Correlation rule firing (stateful, time-windowed).
    Correlation(CorrelationBody),
}

/// Detection-specific result fields.
#[derive(Debug, Clone, Serialize)]
pub struct DetectionBody {
    /// Which named detections (selections) matched.
    pub matched_selections: Vec<String>,
    /// Specific field matches that triggered the detection.
    pub matched_fields: Vec<FieldMatch>,
    /// The full event that triggered the match, included when the rule
    /// sets `rsigma.include_event: "true"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event: Option<serde_json::Value>,
}

/// Correlation-specific result fields.
#[derive(Debug, Clone, Serialize)]
pub struct CorrelationBody {
    /// Type of correlation.
    pub correlation_type: CorrelationType,
    /// Group-by field names and their values for this match.
    pub group_key: Vec<(String, String)>,
    /// The aggregated value that triggered the condition (count, sum, avg, ...).
    pub aggregated_value: f64,
    /// The time window in seconds.
    pub timespan_secs: u64,
    /// Full event bodies, included when `correlation_event_mode` is `Full`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<serde_json::Value>>,
    /// Lightweight event references, included when `correlation_event_mode` is `Refs`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_refs: Option<Vec<EventRef>>,
}

/// Verbosity of the match detail attached to detection results.
///
/// Gates how much is recorded in each [`FieldMatch`]. `Off` is the default
/// and produces the historical `{ field, value }` shape with no extra keys,
/// so existing wire consumers are unaffected unless they opt in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MatchDetailLevel {
    /// Historical behavior: only field-present matches, recorded as
    /// `{ field, value }`. Keyword and absence matches are not reported.
    #[default]
    Off,
    /// Adds the originating `selection`, the `matcher` kind, and
    /// `case_sensitive`, and reports previously dropped keyword and
    /// absence matches.
    Summary,
    /// Everything in `Summary` plus the `pattern` that fired.
    Full,
}

impl MatchDetailLevel {
    /// Lowercase wire name (`off` / `summary` / `full`).
    pub fn as_str(self) -> &'static str {
        match self {
            MatchDetailLevel::Off => "off",
            MatchDetailLevel::Summary => "summary",
            MatchDetailLevel::Full => "full",
        }
    }
}

impl std::str::FromStr for MatchDetailLevel {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "off" => Ok(MatchDetailLevel::Off),
            "summary" => Ok(MatchDetailLevel::Summary),
            "full" => Ok(MatchDetailLevel::Full),
            other => Err(format!(
                "invalid match-detail level: {other:?} (expected off, summary, or full)"
            )),
        }
    }
}

/// The kind of matcher that produced a [`FieldMatch`].
///
/// Serialized lowercase. Composite and multi-pattern matchers
/// (`AnyOf` / `AllOf` / Aho-Corasick / regex sets) collapse to `one_of`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MatcherKind {
    Exact,
    Contains,
    StartsWith,
    EndsWith,
    Regex,
    #[serde(rename = "one_of")]
    OneOf,
    Cidr,
    Numeric,
    Exists,
    FieldRef,
    Null,
    Bool,
    Expand,
    Timestamp,
    Keyword,
}

/// Serde helper: skip a `bool` field when it is `false`.
#[inline]
fn is_false(b: &bool) -> bool {
    !*b
}

/// A specific field match within a detection.
///
/// The `field` and `value` keys are always present and preserve the
/// historical wire shape. The remaining keys are populated only when the
/// engine runs above [`MatchDetailLevel::Off`] and are skipped on
/// serialization when empty, so the default output is byte-identical to
/// pre-enrichment releases.
#[derive(Debug, Clone, Default, Serialize)]
pub struct FieldMatch {
    /// The field name that matched (`"keyword"` for keyword matches).
    pub field: String,
    /// The event value that triggered the match (`null` for absence matches).
    pub value: serde_json::Value,
    /// The selection (named detection) the match came from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selection: Option<String>,
    /// The matcher kind that fired.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matcher: Option<MatcherKind>,
    /// The pattern the matcher tested against (Full level only, truncated).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    /// Whether the match was case-sensitive, when meaningful for the matcher.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub case_sensitive: Option<bool>,
    /// Whether the matcher was negated (`|not` / inverted).
    #[serde(skip_serializing_if = "is_false", default)]
    pub negated: bool,
}

impl FieldMatch {
    /// Construct a bare match with only `field` and `value` set, matching
    /// the historical (`MatchDetailLevel::Off`) shape.
    pub fn new(field: impl Into<String>, value: serde_json::Value) -> Self {
        FieldMatch {
            field: field.into(),
            value,
            ..Default::default()
        }
    }
}

/// Convenience iterators over a slice of [`EvaluationResult`].
///
/// `ProcessResult` is a flat `Vec<EvaluationResult>` (detections then
/// correlations, in evaluation order); this trait exposes by-kind views
/// without forcing every caller to write `.iter().filter(|r| r.is_*())`.
/// Implemented on `[EvaluationResult]` so it works for `Vec`, slices, and
/// boxed slices alike.
pub trait ProcessResultExt {
    /// Iterate over detection results.
    fn detections(&self) -> impl Iterator<Item = &EvaluationResult>;
    /// Iterate over correlation results.
    fn correlations(&self) -> impl Iterator<Item = &EvaluationResult>;
    /// Number of detection results.
    fn detection_count(&self) -> usize {
        self.detections().count()
    }
    /// Number of correlation results.
    fn correlation_count(&self) -> usize {
        self.correlations().count()
    }
}

impl ProcessResultExt for [EvaluationResult] {
    fn detections(&self) -> impl Iterator<Item = &EvaluationResult> {
        self.iter().filter(|r| r.is_detection())
    }
    fn correlations(&self) -> impl Iterator<Item = &EvaluationResult> {
        self.iter().filter(|r| r.is_correlation())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header(title: &str) -> RuleHeader {
        RuleHeader {
            rule_title: title.to_string(),
            rule_id: Some(format!("{title}-id")),
            level: Some(Level::High),
            tags: vec!["attack.t1059".to_string()],
            custom_attributes: Arc::new(HashMap::new()),
            enrichments: None,
        }
    }

    /// Wire-shape snapshot: a detection serializes to a flat JSON object
    /// with detection-only fields and no `correlation_type` key.
    #[test]
    fn detection_wire_shape_is_flat() {
        let result = EvaluationResult {
            header: header("Suspicious PowerShell"),
            body: ResultBody::Detection(DetectionBody {
                matched_selections: vec!["selection".to_string()],
                matched_fields: vec![FieldMatch::new(
                    "CommandLine",
                    serde_json::json!("powershell -enc ..."),
                )],
                event: None,
            }),
        };

        let json = serde_json::to_string(&result).unwrap();
        assert_eq!(
            json,
            r#"{"rule_title":"Suspicious PowerShell","rule_id":"Suspicious PowerShell-id","level":"high","tags":["attack.t1059"],"matched_selections":["selection"],"matched_fields":[{"field":"CommandLine","value":"powershell -enc ..."}]}"#
        );

        // Downstream-disambiguation contract: detections must not carry
        // a `correlation_type` key.
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.get("correlation_type").is_none());
        assert!(parsed.get("matched_fields").is_some());
    }

    /// Wire-shape snapshot: a correlation serializes to a flat JSON object
    /// with correlation-only fields and no `matched_fields` key.
    #[test]
    fn correlation_wire_shape_is_flat() {
        let result = EvaluationResult {
            header: header("SSH brute force"),
            body: ResultBody::Correlation(CorrelationBody {
                correlation_type: CorrelationType::EventCount,
                group_key: vec![("SourceIP".to_string(), "203.0.113.4".to_string())],
                aggregated_value: 73.0,
                timespan_secs: 300,
                events: None,
                event_refs: None,
            }),
        };

        let json = serde_json::to_string(&result).unwrap();
        assert_eq!(
            json,
            r#"{"rule_title":"SSH brute force","rule_id":"SSH brute force-id","level":"high","tags":["attack.t1059"],"correlation_type":"event_count","group_key":[["SourceIP","203.0.113.4"]],"aggregated_value":73.0,"timespan_secs":300}"#
        );

        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.get("matched_fields").is_none());
        assert!(parsed.get("correlation_type").is_some());
    }

    #[test]
    fn accessors_dispatch_on_body_variant() {
        let det = EvaluationResult {
            header: header("Det"),
            body: ResultBody::Detection(DetectionBody {
                matched_selections: vec![],
                matched_fields: vec![],
                event: None,
            }),
        };
        assert!(det.is_detection());
        assert!(!det.is_correlation());
        assert!(det.as_detection().is_some());
        assert!(det.as_correlation().is_none());

        let corr = EvaluationResult {
            header: header("Corr"),
            body: ResultBody::Correlation(CorrelationBody {
                correlation_type: CorrelationType::EventCount,
                group_key: vec![],
                aggregated_value: 0.0,
                timespan_secs: 0,
                events: None,
                event_refs: None,
            }),
        };
        assert!(corr.is_correlation());
        assert!(!corr.is_detection());
        assert!(corr.as_correlation().is_some());
        assert!(corr.as_detection().is_none());
    }
}