rsigma-eval 0.14.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
use std::borrow::Cow;

use serde_json::Value;

use super::{Event, EventValue};

/// Maximum nesting depth for recursive JSON traversal.
const MAX_NESTING_DEPTH: usize = 64;

/// Zero-copy event backed by `serde_json::Value`.
///
/// Supports both borrowed (`&Value`) and owned (`Value`) backing via `Cow`.
/// This is the primary implementation for JSON/NDJSON input.
///
/// Flat keys are checked first: `"actor.id"` as a single key takes precedence
/// over `{"actor": {"id": ...}}` nested traversal.
#[derive(Debug)]
pub struct JsonEvent<'a> {
    inner: Cow<'a, Value>,
}

impl<'a> JsonEvent<'a> {
    /// Wrap a borrowed JSON value as an event.
    pub fn borrow(v: &'a Value) -> Self {
        Self {
            inner: Cow::Borrowed(v),
        }
    }

    /// Wrap an owned JSON value as an event.
    pub fn owned(v: Value) -> Self {
        Self {
            inner: Cow::Owned(v),
        }
    }
}

impl<'a> From<&'a Value> for JsonEvent<'a> {
    fn from(v: &'a Value) -> Self {
        Self::borrow(v)
    }
}

impl From<Value> for JsonEvent<'static> {
    fn from(v: Value) -> Self {
        Self::owned(v)
    }
}

impl<'a> Event for JsonEvent<'a> {
    /// Get a field value by name, supporting dot-notation for nested access.
    ///
    /// Checks for a flat key first (exact match), then falls back to
    /// dot-separated traversal. When a path segment yields an array,
    /// each element is tried and the first match is returned (OR semantics).
    fn get_field(&self, path: &str) -> Option<EventValue<'_>> {
        let value: &Value = &self.inner;

        if let Some(obj) = value.as_object()
            && let Some(v) = obj.get(path)
        {
            return Some(EventValue::from(v));
        }

        if path.contains('.') {
            return traverse_json(value, path).map(EventValue::from);
        }

        None
    }

    /// Check if any string value in the event satisfies a predicate.
    ///
    /// Short-circuits on the first match, avoiding the allocation of
    /// collecting all string values into a `Vec`.
    fn any_string_value(&self, pred: &dyn Fn(&str) -> bool) -> bool {
        any_string_value_json(&self.inner, pred, MAX_NESTING_DEPTH)
    }

    /// Iterate over all string values in the event (for keyword detection).
    ///
    /// Recursively walks the entire event object and yields every string
    /// value found, including inside nested objects and arrays. Traversal
    /// is capped at 64 levels of nesting to prevent stack overflow.
    fn all_string_values(&self) -> Vec<Cow<'_, str>> {
        let mut values = Vec::new();
        collect_string_values_json(&self.inner, &mut values, MAX_NESTING_DEPTH);
        values
    }

    fn to_json(&self) -> Value {
        self.inner.as_ref().clone()
    }

    /// Walk every leaf field in the event and yield dot-joined paths.
    /// Intermediate object names (`actor` for `{"actor":{"id":"x"}}`)
    /// are NOT emitted; only the leaves (`actor.id`) appear. This
    /// matches typical Sigma rules, which reference nested values via
    /// dot-notation; emitting the intermediate name would falsely flag
    /// every parent object as "unknown" in the gap signal even when
    /// the rule references a child path. Top-level scalar fields
    /// (`{"actor":"alice"}`) emit `actor` because they ARE leaves.
    /// Arrays contribute their parent path once; per-index suffixes
    /// are not emitted.
    fn field_keys(&self) -> Vec<Cow<'_, str>> {
        let mut out = Vec::new();
        collect_field_keys(&self.inner, "", &mut out, MAX_NESTING_DEPTH);
        out
    }
}

/// Recursively traverse a JSON value following dot-notation path segments.
///
/// `path` is the remaining dot-joined path (e.g. `"actor.id.value"`); the
/// function splits the leading segment on each recursion via
/// [`str::split_once`] so no `Vec<&str>` is allocated. Each lookup was a
/// hot path under `get_field`, called once per detection item per event;
/// the previous `path.split('.').collect::<Vec<_>>()` allocated on every
/// nested lookup.
///
/// When a segment resolves to an array, each element is tried with the
/// same (unconsumed) `path`, matching the OR semantics of the prior
/// implementation: the array does not consume a path segment.
fn traverse_json<'a>(current: &'a Value, path: &str) -> Option<&'a Value> {
    match current {
        Value::Object(map) => {
            // `split_once` consumes a single segment per recursion; the
            // `has_more` flag distinguishes "the last segment, return the
            // looked-up value" from "more segments to walk into". Treating
            // an `is_empty()` path as terminal would change the
            // pathological "trailing dot" case (`"a.b."`) from a miss to
            // a hit, because consuming `b` would leave an empty rest that
            // the old `Vec<&str>` walker tried to apply to the leaf
            // value and bailed on; preserve that miss semantics here.
            let (head, rest, has_more) = match path.split_once('.') {
                Some((h, r)) => (h, r, true),
                None => (path, "", false),
            };
            let next = map.get(head)?;
            if has_more {
                traverse_json(next, rest)
            } else {
                Some(next)
            }
        }
        Value::Array(arr) => {
            // Arrays do not consume a path segment; each element is
            // tried with the full remaining path, matching the OR
            // semantics of the prior `traverse_json(item, parts)` call.
            for item in arr {
                if let Some(v) = traverse_json(item, path) {
                    return Some(v);
                }
            }
            None
        }
        _ => None,
    }
}

fn any_string_value_json(v: &Value, pred: &dyn Fn(&str) -> bool, depth: usize) -> bool {
    if depth == 0 {
        return false;
    }
    match v {
        Value::String(s) => pred(s.as_str()),
        Value::Object(map) => map
            .values()
            .any(|val| any_string_value_json(val, pred, depth - 1)),
        Value::Array(arr) => arr
            .iter()
            .any(|val| any_string_value_json(val, pred, depth - 1)),
        _ => false,
    }
}

fn collect_field_keys<'a>(v: &'a Value, prefix: &str, out: &mut Vec<Cow<'a, str>>, depth: usize) {
    if depth == 0 {
        return;
    }
    if let Value::Object(map) = v {
        for (k, child) in map {
            let path = if prefix.is_empty() {
                k.clone()
            } else {
                format!("{prefix}.{k}")
            };
            match child {
                // Recurse into nested objects but do NOT emit the
                // intermediate path; only the leaf descendants count.
                // Sigma rules normally reference leaves via
                // dot-notation, so emitting `actor` alongside
                // `actor.id` would falsely flag the parent as
                // "unknown" in the gap signal.
                Value::Object(_) => collect_field_keys(child, &path, out, depth - 1),
                _ => out.push(Cow::Owned(path)),
            }
        }
    }
}

fn collect_string_values_json<'a>(v: &'a Value, out: &mut Vec<Cow<'a, str>>, depth: usize) {
    if depth == 0 {
        return;
    }
    match v {
        Value::String(s) => out.push(Cow::Borrowed(s.as_str())),
        Value::Object(map) => {
            for val in map.values() {
                collect_string_values_json(val, out, depth - 1);
            }
        }
        Value::Array(arr) => {
            for val in arr {
                collect_string_values_json(val, out, depth - 1);
            }
        }
        _ => {}
    }
}

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

    #[test]
    fn json_flat_field() {
        let v = json!({"CommandLine": "whoami", "User": "admin"});
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("CommandLine"),
            Some(EventValue::Str(Cow::Borrowed("whoami")))
        );
    }

    #[test]
    fn json_nested_field() {
        let v = json!({"actor": {"id": "user123", "type": "User"}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("actor.id"),
            Some(EventValue::Str(Cow::Borrowed("user123")))
        );
    }

    #[test]
    fn json_flat_key_precedence() {
        let v = json!({"actor.id": "flat_value", "actor": {"id": "nested_value"}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("actor.id"),
            Some(EventValue::Str(Cow::Borrowed("flat_value")))
        );
    }

    #[test]
    fn json_missing_field() {
        let v = json!({"foo": "bar"});
        let event = JsonEvent::borrow(&v);
        assert_eq!(event.get_field("missing"), None);
    }

    #[test]
    fn json_null_field() {
        let v = json!({"foo": null});
        let event = JsonEvent::borrow(&v);
        assert_eq!(event.get_field("foo"), Some(EventValue::Null));
    }

    #[test]
    fn json_array_traversal() {
        let v = json!({"a": {"b": [{"c": "found"}, {"c": "other"}]}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("a.b.c"),
            Some(EventValue::Str(Cow::Borrowed("found")))
        );
    }

    #[test]
    fn json_array_traversal_no_match() {
        let v = json!({"a": {"b": [{"x": 1}, {"y": 2}]}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(event.get_field("a.b.c"), None);
    }

    #[test]
    fn json_array_traversal_deep() {
        let v = json!({
            "events": [
                {"actors": [{"name": "alice"}, {"name": "bob"}]},
                {"actors": [{"name": "charlie"}]}
            ]
        });
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("events.actors.name"),
            Some(EventValue::Str(Cow::Borrowed("alice")))
        );
    }

    #[test]
    fn json_array_at_root_level() {
        let v = json!({"process": [{"command_line": "whoami"}, {"command_line": "id"}]});
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("process.command_line"),
            Some(EventValue::Str(Cow::Borrowed("whoami")))
        );
    }

    #[test]
    fn json_array_returns_array_value() {
        let v = json!({"a": {"tags": ["t1", "t2"]}});
        let event = JsonEvent::borrow(&v);
        let result = event.get_field("a.tags");
        assert!(matches!(result, Some(EventValue::Array(_))));
    }

    #[test]
    fn json_flat_key_wins_over_array_traversal() {
        let v = json!({"a.b.c": "flat", "a": {"b": [{"c": "nested"}]}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(
            event.get_field("a.b.c"),
            Some(EventValue::Str(Cow::Borrowed("flat")))
        );
    }

    #[test]
    fn json_all_string_values() {
        let v = json!({
            "a": "hello",
            "b": 42,
            "c": {"d": "world", "e": true},
            "f": ["one", "two"]
        });
        let event = JsonEvent::borrow(&v);
        let values = event.all_string_values();
        let strs: Vec<&str> = values.iter().map(|c| c.as_ref()).collect();
        assert!(strs.contains(&"hello"));
        assert!(strs.contains(&"world"));
        assert!(strs.contains(&"one"));
        assert!(strs.contains(&"two"));
        assert_eq!(values.len(), 4);
    }

    #[test]
    fn json_to_json_roundtrip() {
        let v = json!({"a": 1, "b": "hello", "c": [1, 2]});
        let event = JsonEvent::borrow(&v);
        assert_eq!(event.to_json(), v);
    }

    #[test]
    fn json_owned_works() {
        let v = json!({"key": "value"});
        let event = JsonEvent::owned(v.clone());
        assert_eq!(
            event.get_field("key"),
            Some(EventValue::Str(Cow::Borrowed("value")))
        );
        assert_eq!(event.to_json(), v);
    }

    #[test]
    fn json_field_keys_flat() {
        let v = json!({"CommandLine": "x", "User": "y"});
        let event = JsonEvent::borrow(&v);
        let mut keys: Vec<String> = event.field_keys().iter().map(|c| c.to_string()).collect();
        keys.sort();
        assert_eq!(keys, vec!["CommandLine", "User"]);
    }

    #[test]
    fn json_field_keys_nested_leaves_only() {
        // Intermediate object names like `actor` are NOT emitted; only
        // leaves (`actor.id`, `actor.type`) and top-level scalars
        // (`verb`) appear.
        let v = json!({"actor": {"id": "u1", "type": "User"}, "verb": "login"});
        let event = JsonEvent::borrow(&v);
        let mut keys: Vec<String> = event.field_keys().iter().map(|c| c.to_string()).collect();
        keys.sort();
        assert_eq!(keys, vec!["actor.id", "actor.type", "verb"]);
    }

    #[test]
    fn json_field_keys_deeply_nested_leaves_only() {
        let v = json!({"a": {"b": {"c": 1}}, "flat": "x"});
        let event = JsonEvent::borrow(&v);
        let mut keys: Vec<String> = event.field_keys().iter().map(|c| c.to_string()).collect();
        keys.sort();
        assert_eq!(keys, vec!["a.b.c", "flat"]);
    }

    #[test]
    fn json_field_keys_array_parent_only() {
        let v = json!({"events": [{"id": 1}, {"id": 2}]});
        let event = JsonEvent::borrow(&v);
        let keys: Vec<String> = event.field_keys().iter().map(|c| c.to_string()).collect();
        // Arrays contribute their parent key only; array indices are not enumerated.
        assert_eq!(keys, vec!["events"]);
    }

    #[test]
    fn json_field_keys_top_level_non_object_empty() {
        let v = json!("just a string");
        let event = JsonEvent::owned(v);
        assert!(event.field_keys().is_empty());
    }

    #[test]
    fn json_traversal_with_consecutive_dots_does_not_panic() {
        // Pathological input -- a path like `a..b` used to be tokenised
        // by `split('.')` into `["a", "", "b"]` and then walked head-by-
        // head; the new `split_once('.')` recursion produces the same
        // `("a", ".b")` -> `("", "b")` -> ... sequence with no
        // allocation. Verify the lookup falls back to `None` rather
        // than panicking or accidentally matching.
        let v = json!({"a": {"b": "x"}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(event.get_field("a..b"), None);
    }

    #[test]
    fn json_traversal_with_trailing_dot_does_not_panic() {
        // A trailing dot used to leave an empty trailing segment in the
        // `Vec<&str>` path which the object branch tried to look up
        // against the map; the iterator-based walker preserves that
        // miss without allocating.
        let v = json!({"a": {"b": "x"}});
        let event = JsonEvent::borrow(&v);
        assert_eq!(event.get_field("a.b."), None);
    }
}