Skip to main content

rsigma_eval/matcher/
mod.rs

1//! Compiled matchers for zero-allocation hot-path evaluation.
2//!
3//! Each `CompiledMatcher` variant is pre-compiled at rule load time.
4//! At evaluation time, `matches()` performs the comparison against an
5//! [`EventValue`](crate::event::EventValue) from the event with no
6//! dynamic dispatch or allocation.
7
8mod helpers;
9mod matching;
10
11pub use helpers::{ascii_lowercase_cow, parse_expand_template, sigma_string_to_regex};
12
13use aho_corasick::AhoCorasick;
14use regex::{Regex, RegexSet};
15
16use crate::event::Event;
17use crate::result::MatcherKind;
18use ipnet::IpNet;
19use rsigma_ir::IrStrOp;
20
21/// Upper bound on the length of a `pattern` string recorded in match
22/// detail. Long Aho-Corasick / regex-set joins are truncated with an
23/// ellipsis so a single match cannot bloat the output line.
24const MAX_PATTERN_LEN: usize = 256;
25
26/// A structural description of a compiled matcher, used to populate the
27/// match-detail fields on a [`FieldMatch`](crate::result::FieldMatch).
28///
29/// Purely descriptive: it reports the matcher's shape and pattern, not
30/// which value matched. Composite matchers collapse to
31/// [`MatcherKind::OneOf`] with their child patterns joined.
32#[derive(Debug, Clone)]
33pub struct MatchDescriptor {
34    /// The matcher kind that fired.
35    pub kind: MatcherKind,
36    /// The pattern the matcher tested against, truncated to `MAX_PATTERN_LEN`.
37    pub pattern: Option<String>,
38    /// Whether matching was case-sensitive, when meaningful.
39    pub case_sensitive: Option<bool>,
40    /// Whether the matcher is negated.
41    pub negated: bool,
42}
43
44fn truncate_pattern(s: String) -> String {
45    if s.len() <= MAX_PATTERN_LEN {
46        return s;
47    }
48    let mut end = MAX_PATTERN_LEN.saturating_sub(3);
49    while end > 0 && !s.is_char_boundary(end) {
50        end -= 1;
51    }
52    let mut out = s[..end].to_string();
53    out.push_str("...");
54    out
55}
56
57fn numeric_descriptor(op: &str, n: f64) -> MatchDescriptor {
58    MatchDescriptor {
59        kind: MatcherKind::Numeric,
60        pattern: Some(format!("{op} {n}")),
61        case_sensitive: None,
62        negated: false,
63    }
64}
65
66fn join_child_patterns(children: &[CompiledMatcher]) -> String {
67    children
68        .iter()
69        .filter_map(|c| c.describe().pattern)
70        .collect::<Vec<_>>()
71        .join(", ")
72}
73
74fn expand_template_to_string(parts: &[ExpandPart]) -> String {
75    let mut s = String::new();
76    for part in parts {
77        match part {
78            ExpandPart::Literal(t) => s.push_str(t),
79            ExpandPart::Placeholder(name) => {
80                s.push('%');
81                s.push_str(name);
82                s.push('%');
83            }
84        }
85    }
86    s
87}
88
89/// A pre-compiled matcher for a single value comparison.
90///
91/// All string matchers store their values in the form needed for comparison
92/// (Unicode-lowercased for case-insensitive). The `case_insensitive` flag
93/// controls whether the input is lowercased before comparison.
94#[derive(Debug, Clone)]
95pub enum CompiledMatcher {
96    // -- String matchers --
97    /// Exact string equality.
98    Exact {
99        value: String,
100        case_insensitive: bool,
101    },
102    /// Substring containment.
103    Contains {
104        value: String,
105        case_insensitive: bool,
106    },
107    /// String starts with prefix.
108    StartsWith {
109        value: String,
110        case_insensitive: bool,
111    },
112    /// String ends with suffix.
113    EndsWith {
114        value: String,
115        case_insensitive: bool,
116    },
117    /// Compiled regex pattern (flags baked in at compile time).
118    Regex(Regex),
119
120    /// Multi-pattern substring match via Aho-Corasick automaton.
121    ///
122    /// Built by the optimizer when an `AnyOf` group contains
123    /// `AHO_CORASICK_THRESHOLD` or more plain `Contains` matchers with the
124    /// same case sensitivity. Replaces the sequential O(N * haystack_len)
125    /// scan of `AnyOf([Contains, ...])` with a single linear pass.
126    ///
127    /// **Invariant**: this variant only encodes `AnyOf` (OR) semantics.
128    /// `AllOf(Contains)` (`|all` modifier) MUST NOT be collapsed into this
129    /// variant - the optimizer enforces this.
130    ///
131    /// **Case insensitivity**: when `case_insensitive` is true, needles are
132    /// stored pre-lowered (matching the `Contains` invariant) and the hot
133    /// path lowers the haystack via [`ascii_lowercase_cow`] before searching.
134    /// The `AhoCorasick` automaton itself is built case-sensitively.
135    AhoCorasickSet {
136        automaton: AhoCorasick,
137        case_insensitive: bool,
138        /// Pre-lowered needles in the same order they were fed to
139        /// [`AhoCorasick::new`]. Retained so downstream consumers (e.g. the
140        /// engine's per-field bloom builder) can recover the pattern set
141        /// without parsing the automaton's internal state.
142        needles: Vec<String>,
143    },
144
145    /// Multi-pattern regex match via [`regex::RegexSet`].
146    ///
147    /// Built by the optimizer when an `AnyOf` group contains
148    /// `REGEX_SET_THRESHOLD` or more individual `Regex` matchers. Compiles
149    /// every pattern into a single combined DFA so one traversal of the
150    /// haystack tests all patterns at once.
151    ///
152    /// **Pattern reconstruction**: the optimizer rebuilds the set from each
153    /// matcher's [`Regex::as_str`], which preserves any inline flags the
154    /// compiler inlined (e.g. `(?i)`, `(?ims)`). This relies on the eval
155    /// crate's regex builder always inlining flags into the pattern string
156    /// rather than configuring them via `RegexBuilder`. A unit test guards
157    /// against future drift in that contract.
158    RegexSetMatch { set: RegexSet, mode: GroupMode },
159
160    // -- Network --
161    /// CIDR network match for IP addresses.
162    Cidr(IpNet),
163
164    // -- Numeric --
165    /// Numeric equality.
166    NumericEq(f64),
167    /// Numeric greater-than.
168    NumericGt(f64),
169    /// Numeric greater-than-or-equal.
170    NumericGte(f64),
171    /// Numeric less-than.
172    NumericLt(f64),
173    /// Numeric less-than-or-equal.
174    NumericLte(f64),
175
176    // -- Special --
177    /// Field existence check. `true` = field must exist, `false` = must not exist.
178    Exists(bool),
179    /// Compare against another field's value.
180    ///
181    /// `op` is equality, or a substring, prefix, or suffix check
182    /// (`fieldref` followed by `contains`, `startswith`, or `endswith`).
183    FieldRef {
184        field: String,
185        op: IrStrOp,
186        case_insensitive: bool,
187    },
188    /// Match null / missing values.
189    Null,
190    /// Boolean equality.
191    BoolEq(bool),
192
193    // -- Expand --
194    /// Placeholder expansion: `%fieldname%` is resolved from the event at match time.
195    Expand {
196        template: Vec<ExpandPart>,
197        case_insensitive: bool,
198    },
199
200    // -- Timestamp --
201    /// Extract a time component from a timestamp field value and match it.
202    TimestampPart {
203        part: TimePart,
204        inner: Box<CompiledMatcher>,
205    },
206
207    // -- Negation --
208    /// Negated matcher: matches if the inner matcher does NOT match.
209    Not(Box<CompiledMatcher>),
210
211    // -- Composite --
212    /// Match if ANY child matches (OR).
213    AnyOf(Vec<CompiledMatcher>),
214    /// Match if ALL children match (AND).
215    AllOf(Vec<CompiledMatcher>),
216
217    /// A composite of case-insensitive string matchers that lowers the haystack
218    /// once before dispatching to children.
219    ///
220    /// Built by the optimizer when an `AnyOf` or `AllOf` group is composed
221    /// entirely of case-insensitive string matchers (`Contains`, `StartsWith`,
222    /// `EndsWith`, `Exact`, `AhoCorasickSet`, plus regexes that carry the
223    /// `(?i)` flag, plus `Not` / nested `AnyOf` / `AllOf` whose every leaf
224    /// satisfies these rules).
225    ///
226    /// **Invariant**: every child must be pre-lowerable. The optimizer's
227    /// `is_pre_lowerable` validator enforces this; `matches_pre_lowered`
228    /// `debug_assert!`s on violation.
229    ///
230    /// **Why this exists**: a mixed `AnyOf([Contains, StartsWith, EndsWith])`
231    /// previously called `s.to_lowercase()` once per child. Pre-lowering the
232    /// haystack a single time and dispatching to a CI-aware match path
233    /// eliminates the redundant allocations.
234    CaseInsensitiveGroup {
235        children: Vec<CompiledMatcher>,
236        mode: GroupMode,
237    },
238}
239
240/// Reduction mode for composite matchers.
241///
242/// `Any` corresponds to OR semantics; `All` to AND. Used by
243/// `CaseInsensitiveGroup` to encode whether a single match suffices or every
244/// child must match.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum GroupMode {
247    /// At least one child must match (`AnyOf` semantics).
248    Any,
249    /// Every child must match (`AllOf` semantics).
250    All,
251}
252
253/// A part of an expand template.
254#[derive(Debug, Clone)]
255pub enum ExpandPart {
256    /// Literal text.
257    Literal(String),
258    /// A placeholder field name (between `%` delimiters).
259    Placeholder(String),
260}
261
262/// Which time component to extract from a timestamp.
263#[derive(Debug, Clone, Copy)]
264pub enum TimePart {
265    Minute,
266    Hour,
267    Day,
268    Week,
269    Month,
270    Year,
271}
272
273impl CompiledMatcher {
274    /// Check if this matcher matches any string value in the event.
275    /// Used for keyword detection (field-less matching).
276    ///
277    /// Avoids allocating a `Vec` of all strings and a `String` per value by
278    /// using `matches_str` with a short-circuiting traversal.
279    #[inline]
280    pub fn matches_keyword(&self, event: &impl Event) -> bool {
281        event.any_string_value(&|s| self.matches_str(s))
282    }
283
284    /// Describe this matcher's shape for match-detail reporting.
285    ///
286    /// Runs only when assembling a detection result above
287    /// [`MatchDetailLevel::Off`](crate::result::MatchDetailLevel), never on
288    /// the matching hot path.
289    pub fn describe(&self) -> MatchDescriptor {
290        match self {
291            CompiledMatcher::Exact {
292                value,
293                case_insensitive,
294            } => MatchDescriptor {
295                kind: MatcherKind::Exact,
296                pattern: Some(truncate_pattern(value.clone())),
297                case_sensitive: Some(!case_insensitive),
298                negated: false,
299            },
300            CompiledMatcher::Contains {
301                value,
302                case_insensitive,
303            } => MatchDescriptor {
304                kind: MatcherKind::Contains,
305                pattern: Some(truncate_pattern(value.clone())),
306                case_sensitive: Some(!case_insensitive),
307                negated: false,
308            },
309            CompiledMatcher::StartsWith {
310                value,
311                case_insensitive,
312            } => MatchDescriptor {
313                kind: MatcherKind::StartsWith,
314                pattern: Some(truncate_pattern(value.clone())),
315                case_sensitive: Some(!case_insensitive),
316                negated: false,
317            },
318            CompiledMatcher::EndsWith {
319                value,
320                case_insensitive,
321            } => MatchDescriptor {
322                kind: MatcherKind::EndsWith,
323                pattern: Some(truncate_pattern(value.clone())),
324                case_sensitive: Some(!case_insensitive),
325                negated: false,
326            },
327            CompiledMatcher::Regex(re) => MatchDescriptor {
328                kind: MatcherKind::Regex,
329                pattern: Some(truncate_pattern(re.as_str().to_string())),
330                case_sensitive: None,
331                negated: false,
332            },
333            CompiledMatcher::AhoCorasickSet {
334                needles,
335                case_insensitive,
336                ..
337            } => MatchDescriptor {
338                kind: MatcherKind::OneOf,
339                pattern: Some(truncate_pattern(needles.join(", "))),
340                case_sensitive: Some(!case_insensitive),
341                negated: false,
342            },
343            CompiledMatcher::RegexSetMatch { set, .. } => MatchDescriptor {
344                kind: MatcherKind::OneOf,
345                pattern: Some(truncate_pattern(set.patterns().join(", "))),
346                case_sensitive: None,
347                negated: false,
348            },
349            CompiledMatcher::Cidr(net) => MatchDescriptor {
350                kind: MatcherKind::Cidr,
351                pattern: Some(net.to_string()),
352                case_sensitive: None,
353                negated: false,
354            },
355            CompiledMatcher::NumericEq(n) => numeric_descriptor("=", *n),
356            CompiledMatcher::NumericGt(n) => numeric_descriptor(">", *n),
357            CompiledMatcher::NumericGte(n) => numeric_descriptor(">=", *n),
358            CompiledMatcher::NumericLt(n) => numeric_descriptor("<", *n),
359            CompiledMatcher::NumericLte(n) => numeric_descriptor("<=", *n),
360            CompiledMatcher::Exists(expect) => MatchDescriptor {
361                kind: MatcherKind::Exists,
362                pattern: Some(expect.to_string()),
363                case_sensitive: None,
364                negated: false,
365            },
366            CompiledMatcher::FieldRef {
367                field,
368                case_insensitive,
369                ..
370            } => MatchDescriptor {
371                kind: MatcherKind::FieldRef,
372                pattern: Some(field.clone()),
373                case_sensitive: Some(!case_insensitive),
374                negated: false,
375            },
376            CompiledMatcher::Null => MatchDescriptor {
377                kind: MatcherKind::Null,
378                pattern: None,
379                case_sensitive: None,
380                negated: false,
381            },
382            CompiledMatcher::BoolEq(b) => MatchDescriptor {
383                kind: MatcherKind::Bool,
384                pattern: Some(b.to_string()),
385                case_sensitive: None,
386                negated: false,
387            },
388            CompiledMatcher::Expand {
389                template,
390                case_insensitive,
391            } => MatchDescriptor {
392                kind: MatcherKind::Expand,
393                pattern: Some(truncate_pattern(expand_template_to_string(template))),
394                case_sensitive: Some(!case_insensitive),
395                negated: false,
396            },
397            CompiledMatcher::TimestampPart { inner, .. } => {
398                let inner_d = inner.describe();
399                MatchDescriptor {
400                    kind: MatcherKind::Timestamp,
401                    pattern: inner_d.pattern,
402                    case_sensitive: inner_d.case_sensitive,
403                    negated: inner_d.negated,
404                }
405            }
406            CompiledMatcher::Not(inner) => {
407                let mut d = inner.describe();
408                d.negated = !d.negated;
409                d
410            }
411            CompiledMatcher::AnyOf(ms) | CompiledMatcher::AllOf(ms) => MatchDescriptor {
412                kind: MatcherKind::OneOf,
413                pattern: Some(truncate_pattern(join_child_patterns(ms))),
414                case_sensitive: None,
415                negated: false,
416            },
417            CompiledMatcher::CaseInsensitiveGroup { children, .. } => MatchDescriptor {
418                kind: MatcherKind::OneOf,
419                pattern: Some(truncate_pattern(join_child_patterns(children))),
420                case_sensitive: Some(false),
421                negated: false,
422            },
423        }
424    }
425}
426
427#[cfg(test)]
428mod describe_tests {
429    use super::*;
430
431    #[test]
432    fn string_matchers_report_kind_pattern_and_case() {
433        let d = CompiledMatcher::Contains {
434            value: "abc".to_string(),
435            case_insensitive: true,
436        }
437        .describe();
438        assert_eq!(d.kind, MatcherKind::Contains);
439        assert_eq!(d.pattern.as_deref(), Some("abc"));
440        assert_eq!(d.case_sensitive, Some(false));
441        assert!(!d.negated);
442
443        let cased = CompiledMatcher::EndsWith {
444            value: "\\powershell.exe".to_string(),
445            case_insensitive: false,
446        }
447        .describe();
448        assert_eq!(cased.kind, MatcherKind::EndsWith);
449        assert_eq!(cased.case_sensitive, Some(true));
450    }
451
452    #[test]
453    fn numeric_exists_and_null_descriptors() {
454        let gt = CompiledMatcher::NumericGt(5.0).describe();
455        assert_eq!(gt.kind, MatcherKind::Numeric);
456        assert_eq!(gt.pattern.as_deref(), Some("> 5"));
457
458        let exists = CompiledMatcher::Exists(false).describe();
459        assert_eq!(exists.kind, MatcherKind::Exists);
460        assert_eq!(exists.pattern.as_deref(), Some("false"));
461
462        let null = CompiledMatcher::Null.describe();
463        assert_eq!(null.kind, MatcherKind::Null);
464        assert!(null.pattern.is_none());
465    }
466
467    #[test]
468    fn not_inverts_negated_flag_and_keeps_inner_kind() {
469        let inner = CompiledMatcher::Contains {
470            value: "evil".to_string(),
471            case_insensitive: true,
472        };
473        let d = CompiledMatcher::Not(Box::new(inner)).describe();
474        assert_eq!(d.kind, MatcherKind::Contains);
475        assert!(d.negated);
476        assert_eq!(d.pattern.as_deref(), Some("evil"));
477    }
478
479    #[test]
480    fn composite_collapses_to_one_of_with_joined_patterns() {
481        let d = CompiledMatcher::AnyOf(vec![
482            CompiledMatcher::Contains {
483                value: "foo".to_string(),
484                case_insensitive: true,
485            },
486            CompiledMatcher::Contains {
487                value: "bar".to_string(),
488                case_insensitive: true,
489            },
490        ])
491        .describe();
492        assert_eq!(d.kind, MatcherKind::OneOf);
493        assert_eq!(d.pattern.as_deref(), Some("foo, bar"));
494    }
495
496    #[test]
497    fn long_patterns_are_truncated() {
498        let long = "x".repeat(MAX_PATTERN_LEN * 2);
499        let d = CompiledMatcher::Contains {
500            value: long,
501            case_insensitive: true,
502        }
503        .describe();
504        let pattern = d.pattern.unwrap();
505        assert!(pattern.len() <= MAX_PATTERN_LEN);
506        assert!(pattern.ends_with("..."));
507    }
508}