Skip to main content

rsigma_parser/
ast.rs

1//! AST types for all Sigma constructs: rules, detections, conditions,
2//! correlations, and filters.
3//!
4//! Reference: Sigma specification V2.0.0 (2024-08-08)
5//! Reference: pySigma types, conditions, correlations, rule modules
6
7use std::collections::HashMap;
8use std::fmt;
9use std::num::NonZeroU64;
10use std::str::FromStr;
11
12use serde::{Deserialize, Serialize};
13
14use crate::diagnostic::CollectionDiagnostic;
15use crate::value::{SigmaValue, Timespan};
16
17// =============================================================================
18// Enumerations
19// =============================================================================
20
21/// Rule maturity status.
22///
23/// Reference: pySigma rule.py SigmaStatus
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum Status {
27    Stable,
28    Test,
29    Experimental,
30    Deprecated,
31    Unsupported,
32}
33
34impl FromStr for Status {
35    type Err = ();
36    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
37        match s {
38            "stable" => Ok(Status::Stable),
39            "test" => Ok(Status::Test),
40            "experimental" => Ok(Status::Experimental),
41            "deprecated" => Ok(Status::Deprecated),
42            "unsupported" => Ok(Status::Unsupported),
43            _ => Err(()),
44        }
45    }
46}
47
48/// Severity level of a triggered rule.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
50#[serde(rename_all = "lowercase")]
51pub enum Level {
52    Informational,
53    Low,
54    Medium,
55    High,
56    Critical,
57}
58
59impl Level {
60    pub fn as_str(&self) -> &'static str {
61        match self {
62            Level::Informational => "informational",
63            Level::Low => "low",
64            Level::Medium => "medium",
65            Level::High => "high",
66            Level::Critical => "critical",
67        }
68    }
69}
70
71impl FromStr for Level {
72    type Err = ();
73    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
74        match s {
75            "informational" => Ok(Level::Informational),
76            "low" => Ok(Level::Low),
77            "medium" => Ok(Level::Medium),
78            "high" => Ok(Level::High),
79            "critical" => Ok(Level::Critical),
80            _ => Err(()),
81        }
82    }
83}
84
85/// Relationship type for the `related` field.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "lowercase")]
88pub enum RelationType {
89    Correlation,
90    Derived,
91    Obsolete,
92    Merged,
93    Renamed,
94    Similar,
95}
96
97impl FromStr for RelationType {
98    type Err = ();
99    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
100        match s {
101            "correlation" => Ok(RelationType::Correlation),
102            "derived" => Ok(RelationType::Derived),
103            "obsolete" => Ok(RelationType::Obsolete),
104            "merged" => Ok(RelationType::Merged),
105            "renamed" => Ok(RelationType::Renamed),
106            "similar" => Ok(RelationType::Similar),
107            _ => Err(()),
108        }
109    }
110}
111
112// =============================================================================
113// Field Modifiers
114// =============================================================================
115
116/// All supported Sigma field modifiers.
117///
118/// Reference: pySigma modifiers.py modifier_mapping
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
120#[serde(rename_all = "lowercase")]
121pub enum Modifier {
122    // String matching modifiers
123    Contains,
124    StartsWith,
125    EndsWith,
126
127    // Value linking
128    All,
129
130    // Encoding modifiers
131    Base64,
132    Base64Offset,
133    Wide,
134    Utf16be,
135    Utf16,
136    WindAsh,
137
138    // Pattern matching
139    Re,
140    Cidr,
141
142    // Case sensitivity
143    Cased,
144
145    // Field existence
146    Exists,
147
148    // Placeholder expansion
149    Expand,
150
151    // Field reference
152    FieldRef,
153
154    // Numeric/value comparison
155    Gt,
156    Gte,
157    Lt,
158    Lte,
159    /// Not equal: field value must differ from the specified value.
160    Neq,
161
162    // Regex flags
163    #[serde(rename = "i")]
164    IgnoreCase,
165    #[serde(rename = "m")]
166    Multiline,
167    #[serde(rename = "s")]
168    DotAll,
169
170    // Timestamp parts
171    Minute,
172    Hour,
173    Day,
174    Week,
175    Month,
176    Year,
177}
178
179/// Parse a modifier identifier string.
180///
181/// Reference: pySigma modifiers.py modifier_mapping
182impl FromStr for Modifier {
183    type Err = ();
184    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
185        match s {
186            "contains" => Ok(Modifier::Contains),
187            "startswith" => Ok(Modifier::StartsWith),
188            "endswith" => Ok(Modifier::EndsWith),
189            "all" => Ok(Modifier::All),
190            "base64" => Ok(Modifier::Base64),
191            "base64offset" => Ok(Modifier::Base64Offset),
192            "wide" | "utf16le" => Ok(Modifier::Wide),
193            "utf16be" => Ok(Modifier::Utf16be),
194            "utf16" => Ok(Modifier::Utf16),
195            "windash" => Ok(Modifier::WindAsh),
196            "re" => Ok(Modifier::Re),
197            "cidr" => Ok(Modifier::Cidr),
198            "cased" => Ok(Modifier::Cased),
199            "exists" => Ok(Modifier::Exists),
200            "expand" => Ok(Modifier::Expand),
201            "fieldref" => Ok(Modifier::FieldRef),
202            "gt" => Ok(Modifier::Gt),
203            "gte" => Ok(Modifier::Gte),
204            "lt" => Ok(Modifier::Lt),
205            "lte" => Ok(Modifier::Lte),
206            "neq" => Ok(Modifier::Neq),
207            "i" | "ignorecase" => Ok(Modifier::IgnoreCase),
208            "m" | "multiline" => Ok(Modifier::Multiline),
209            "s" | "dotall" => Ok(Modifier::DotAll),
210            "minute" => Ok(Modifier::Minute),
211            "hour" => Ok(Modifier::Hour),
212            "day" => Ok(Modifier::Day),
213            "week" => Ok(Modifier::Week),
214            "month" => Ok(Modifier::Month),
215            "year" => Ok(Modifier::Year),
216            _ => Err(()),
217        }
218    }
219}
220
221// =============================================================================
222// Field Specification
223// =============================================================================
224
225/// A field name with optional modifiers, parsed from detection keys like
226/// `TargetObject|endswith` or `Destination|contains|all`.
227///
228/// Reference: pySigma rule/detection.py SigmaDetectionItem.from_mapping
229#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
230pub struct FieldSpec {
231    /// Field name (`None` for keyword detections without a field).
232    pub name: Option<String>,
233    /// Ordered list of modifiers applied to this field.
234    pub modifiers: Vec<Modifier>,
235}
236
237impl FieldSpec {
238    pub fn new(name: Option<String>, modifiers: Vec<Modifier>) -> Self {
239        FieldSpec { name, modifiers }
240    }
241
242    pub fn has_modifier(&self, m: Modifier) -> bool {
243        self.modifiers.contains(&m)
244    }
245
246    pub fn is_keyword(&self) -> bool {
247        self.name.is_none()
248    }
249}
250
251// =============================================================================
252// Condition Expression AST
253// =============================================================================
254
255/// Parsed condition expression AST.
256///
257/// Produced by the PEG parser + Pratt parser from condition strings like
258/// `selection and not filter` or `1 of selection_* and not 1 of filter_*`.
259///
260/// Reference: pySigma conditions.py ConditionItem hierarchy
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262pub enum ConditionExpr {
263    /// Logical AND of sub-expressions.
264    And(Vec<ConditionExpr>),
265    /// Logical OR of sub-expressions.
266    Or(Vec<ConditionExpr>),
267    /// Logical NOT of a sub-expression.
268    Not(Box<ConditionExpr>),
269    /// Reference to a named detection identifier.
270    Identifier(String),
271    /// Quantified selector: `1 of selection_*`, `all of them`, etc.
272    Selector {
273        quantifier: Quantifier,
274        pattern: SelectorPattern,
275    },
276}
277
278impl fmt::Display for ConditionExpr {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        match self {
281            ConditionExpr::And(args) => {
282                let parts: Vec<String> = args.iter().map(|a| format!("{a}")).collect();
283                write!(f, "({})", parts.join(" and "))
284            }
285            ConditionExpr::Or(args) => {
286                let parts: Vec<String> = args.iter().map(|a| format!("{a}")).collect();
287                write!(f, "({})", parts.join(" or "))
288            }
289            ConditionExpr::Not(arg) => write!(f, "not {arg}"),
290            ConditionExpr::Identifier(id) => write!(f, "{id}"),
291            ConditionExpr::Selector {
292                quantifier,
293                pattern,
294            } => write!(f, "{quantifier} of {pattern}"),
295        }
296    }
297}
298
299/// Quantifier in a selector expression.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301pub enum Quantifier {
302    /// Match any (at least one): `1 of ...` or `any of ...`
303    Any,
304    /// Match all: `all of ...`
305    All,
306    /// Match at least `N` detections: `N of ...`. The parser maps `1 of` to
307    /// [`Quantifier::Any`] and rejects `0 of`.
308    Count(NonZeroU64),
309}
310
311impl fmt::Display for Quantifier {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        match self {
314            Quantifier::Any => write!(f, "1"),
315            Quantifier::All => write!(f, "all"),
316            Quantifier::Count(n) => write!(f, "{n}"),
317        }
318    }
319}
320
321/// Target pattern in a selector expression.
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323pub enum SelectorPattern {
324    /// All detection identifiers: `... of them`
325    Them,
326    /// A wildcard pattern matching detection names: `... of selection_*`
327    Pattern(String),
328}
329
330impl fmt::Display for SelectorPattern {
331    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332        match self {
333            SelectorPattern::Them => write!(f, "them"),
334            SelectorPattern::Pattern(p) => write!(f, "{p}"),
335        }
336    }
337}
338
339// =============================================================================
340// Detection Section
341// =============================================================================
342
343/// Quantifier for matching the members of an array-valued field.
344///
345/// Used by array object-scope blocks (`field[any]:` / `field[all]:`). This is
346/// deliberately distinct from the `all` value-list modifier ([`Modifier::All`]),
347/// which links several *values* of one field with AND. An array quantifier
348/// instead ranges over the *members* of an array-valued field.
349///
350/// Reference: proposed Sigma array-matching extension (sigma-specification
351/// Discussion #106).
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
353#[serde(rename_all = "lowercase")]
354pub enum ArrayQuantifier {
355    /// At least one array member must satisfy the nested detection.
356    Any,
357    /// Every array member must satisfy the nested detection, and the array
358    /// must be non-empty.
359    All,
360    /// Every array member must satisfy the nested detection, but an empty or
361    /// missing array also matches (the vacuously-true reading of [`All`]).
362    ///
363    /// [`All`]: ArrayQuantifier::All
364    AllOrEmpty,
365    /// No array member satisfies the nested detection (the dual of [`Any`]).
366    /// Matches an empty or missing array (vacuously, no member matches).
367    ///
368    /// [`Any`]: ArrayQuantifier::Any
369    None,
370}
371
372impl fmt::Display for ArrayQuantifier {
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        match self {
375            ArrayQuantifier::Any => write!(f, "any"),
376            ArrayQuantifier::All => write!(f, "all"),
377            ArrayQuantifier::AllOrEmpty => write!(f, "all_or_empty"),
378            ArrayQuantifier::None => write!(f, "none"),
379        }
380    }
381}
382
383/// A single detection item: a field (with modifiers) mapped to one or more values.
384///
385/// Examples:
386/// - `EventType: "user.mfa.factor.deactivate"` → field="EventType", values=["user.mfa..."]
387/// - `Destination|contains|all: ['new-object', 'net.webclient']` → field="Destination",
388///   modifiers=[Contains, All], values=[...]
389///
390/// Reference: pySigma rule/detection.py SigmaDetectionItem
391#[derive(Debug, Clone, PartialEq, Serialize)]
392pub struct DetectionItem {
393    /// The field specification (name + modifiers).
394    pub field: FieldSpec,
395    /// One or more values to match against.
396    pub values: Vec<SigmaValue>,
397}
398
399/// A detection definition: a group of detection items or nested detections.
400///
401/// When constructed from a YAML mapping, items are AND-linked.
402/// When constructed from a YAML list of mappings, sub-detections are OR-linked.
403///
404/// Reference: pySigma rule/detection.py SigmaDetection
405#[derive(Debug, Clone, PartialEq, Serialize)]
406pub enum Detection {
407    /// AND-linked detection items (from a YAML mapping).
408    AllOf(Vec<DetectionItem>),
409    /// OR-linked sub-detections (from a YAML list of mappings).
410    AnyOf(Vec<Detection>),
411    /// Keyword detection: plain value(s) without a field.
412    Keywords(Vec<SigmaValue>),
413    /// Array object-scope quantifier block: `field[any]:` / `field[all]:`
414    /// opening a nested detection that is evaluated against a single array
415    /// member.
416    ///
417    /// - `field` is the dot-path to the array (quantifier markers stripped).
418    /// - `quantifier` decides whether one (`any`) or every (`all`) member must
419    ///   satisfy `body`.
420    /// - `body` is the nested detection applied per member. A `body` item with
421    ///   no field name (`FieldSpec::name == None`) matches the array member
422    ///   value itself (the scalar-array case `field[all]: value`).
423    ///
424    /// This is the only construct that expresses same-member correlation across
425    /// multiple predicates, and the only one that lowers cleanly to backend
426    /// array primitives (Elasticsearch `nested`, KQL `mv-apply`, SQL
427    /// `jsonb_array_elements`, Splunk `mvexpand`).
428    ArrayMatch {
429        /// Dot-path to the array field (quantifier markers stripped).
430        field: String,
431        /// Whether one or all members must satisfy `body`.
432        quantifier: ArrayQuantifier,
433        /// Nested detection evaluated against a single array member.
434        body: Box<Detection>,
435    },
436    /// AND of heterogeneous sub-detections. Produced when a YAML mapping mixes
437    /// plain detection items with one or more array object-scope blocks, which
438    /// [`Detection::AllOf`] (a list of simple items) cannot represent.
439    And(Vec<Detection>),
440    /// Extended object-scope block body: named element-scoped sub-selections
441    /// combined by a `condition` expression (the recursive "mini-event" form),
442    /// enabling per-element `and`/`or`/`not`. Produced only as an
443    /// [`ArrayMatch`](Detection::ArrayMatch) body when the block map carries a
444    /// `condition:` key. The basic conjunction-map body is the degenerate case
445    /// (an implicit AND of items); this is the explicit-condition form.
446    Conditional {
447        /// Element-scoped named sub-selections (each a nested detection).
448        named: HashMap<String, Detection>,
449        /// Boolean combination of the named sub-selections, evaluated per
450        /// array member.
451        condition: ConditionExpr,
452    },
453}
454
455/// The complete detection section of a Sigma rule.
456///
457/// Contains named detection identifiers, condition expressions, and optional timeframe.
458///
459/// Reference: pySigma rule/detection.py SigmaDetections
460#[derive(Debug, Clone, PartialEq, Serialize)]
461pub struct Detections {
462    /// Named detections (e.g. `selection`, `filter_main`, etc.)
463    pub named: HashMap<String, Detection>,
464    /// One or more condition expressions (parsed from condition string or list).
465    pub conditions: Vec<ConditionExpr>,
466    /// Raw condition strings (before parsing).
467    pub condition_strings: Vec<String>,
468    /// Optional timeframe for aggregation rules (deprecated in favor of correlations).
469    pub timeframe: Option<String>,
470}
471
472// =============================================================================
473// Log Source
474// =============================================================================
475
476/// Log source specification.
477///
478/// Reference: Sigma schema `logsource` object
479#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
480pub struct LogSource {
481    pub category: Option<String>,
482    pub product: Option<String>,
483    pub service: Option<String>,
484    pub definition: Option<String>,
485    /// Any additional custom logsource fields.
486    #[serde(flatten)]
487    pub custom: HashMap<String, String>,
488}
489
490// =============================================================================
491// Related Rule Reference
492// =============================================================================
493
494/// A reference to a related Sigma rule.
495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
496pub struct Related {
497    pub id: String,
498    pub relation_type: RelationType,
499}
500
501// =============================================================================
502// Sigma Detection Rule
503// =============================================================================
504
505/// A complete Sigma detection rule.
506///
507/// Reference: Sigma schema V2.0.0, pySigma rule.py SigmaRule
508#[derive(Debug, Clone, PartialEq, Serialize)]
509pub struct SigmaRule {
510    // Required fields
511    pub title: String,
512    pub logsource: LogSource,
513    pub detection: Detections,
514
515    /// The Sigma specification MAJOR version this rule targets (the
516    /// `sigma-version` attribute, e.g. `3`). `None` means absent, which resolves
517    /// to the fixed floor [`crate::version::SPEC_VERSION_FLOOR`]. Only the major
518    /// is stored, since breaking spec changes occur only at major bumps; it
519    /// gates version-sensitive interpretation such as array-matching brackets.
520    #[serde(skip_serializing_if = "Option::is_none")]
521    pub sigma_version: Option<u32>,
522
523    // Optional metadata
524    pub id: Option<String>,
525    pub name: Option<String>,
526    pub related: Vec<Related>,
527    pub taxonomy: Option<String>,
528    pub status: Option<Status>,
529    pub description: Option<String>,
530    pub license: Option<String>,
531    pub author: Option<String>,
532    pub references: Vec<String>,
533    pub date: Option<String>,
534    pub modified: Option<String>,
535    pub fields: Vec<String>,
536    pub falsepositives: Vec<String>,
537    pub level: Option<Level>,
538    pub tags: Vec<String>,
539    pub scope: Vec<String>,
540
541    /// Custom attributes attached to the rule.
542    ///
543    /// Populated from (a) any top-level YAML key that is not part of the
544    /// standard Sigma rule schema, (b) the entries of the dedicated top-level
545    /// `custom_attributes:` mapping (explicit entries win over arbitrary keys
546    /// of the same name), and (c) pipeline transformations such as
547    /// `SetCustomAttribute`, which are applied last and override both.
548    ///
549    /// Mirrors pySigma's `SigmaRule.custom_attributes` dict. Engines and
550    /// backends can read these to modify per-rule behavior.
551    #[serde(skip_serializing_if = "HashMap::is_empty")]
552    pub custom_attributes: HashMap<String, yaml_serde::Value>,
553}
554
555// =============================================================================
556// Correlation Rule
557// =============================================================================
558
559/// Correlation rule type.
560///
561/// Reference: pySigma correlations.py SigmaCorrelationType
562#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
563#[serde(rename_all = "snake_case")]
564pub enum CorrelationType {
565    EventCount,
566    ValueCount,
567    Temporal,
568    TemporalOrdered,
569    ValueSum,
570    ValueAvg,
571    ValuePercentile,
572    ValueMedian,
573}
574
575impl CorrelationType {
576    pub fn as_str(&self) -> &'static str {
577        match self {
578            CorrelationType::EventCount => "event_count",
579            CorrelationType::ValueCount => "value_count",
580            CorrelationType::Temporal => "temporal",
581            CorrelationType::TemporalOrdered => "temporal_ordered",
582            CorrelationType::ValueSum => "value_sum",
583            CorrelationType::ValueAvg => "value_avg",
584            CorrelationType::ValuePercentile => "value_percentile",
585            CorrelationType::ValueMedian => "value_median",
586        }
587    }
588}
589
590impl FromStr for CorrelationType {
591    type Err = ();
592    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
593        match s {
594            "event_count" => Ok(CorrelationType::EventCount),
595            "value_count" => Ok(CorrelationType::ValueCount),
596            "temporal" => Ok(CorrelationType::Temporal),
597            "temporal_ordered" => Ok(CorrelationType::TemporalOrdered),
598            "value_sum" => Ok(CorrelationType::ValueSum),
599            "value_avg" => Ok(CorrelationType::ValueAvg),
600            "value_percentile" => Ok(CorrelationType::ValuePercentile),
601            "value_median" => Ok(CorrelationType::ValueMedian),
602            _ => Err(()),
603        }
604    }
605}
606
607/// Window semantics for a correlation rule's `timespan`.
608///
609/// Controls how `timespan` is anchored to the event stream. `Sliding` is the
610/// default and matches the behavior the Sigma correlation specification already
611/// prefers (a trailing per-event window), so omitting `window` never changes the
612/// meaning of an existing rule.
613///
614/// - `Sliding`: trailing window `(t - timespan, t]` evaluated per event.
615/// - `Tumbling`: fixed, boundary-aligned, non-overlapping buckets of size
616///   `timespan`.
617/// - `Session`: dynamic window that extends while consecutive in-group events
618///   stay within `gap`, capped by `timespan` as the maximum total span.
619#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
620#[serde(rename_all = "snake_case")]
621pub enum WindowMode {
622    #[default]
623    Sliding,
624    Tumbling,
625    Session,
626}
627
628impl WindowMode {
629    pub fn as_str(&self) -> &'static str {
630        match self {
631            WindowMode::Sliding => "sliding",
632            WindowMode::Tumbling => "tumbling",
633            WindowMode::Session => "session",
634        }
635    }
636}
637
638impl FromStr for WindowMode {
639    type Err = ();
640    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
641        match s {
642            "sliding" => Ok(WindowMode::Sliding),
643            "tumbling" => Ok(WindowMode::Tumbling),
644            "session" => Ok(WindowMode::Session),
645            _ => Err(()),
646        }
647    }
648}
649
650/// Comparison operator in a correlation condition.
651///
652/// Reference: pySigma correlations.py SigmaCorrelationConditionOperator
653#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
654pub enum ConditionOperator {
655    Lt,
656    Lte,
657    Gt,
658    Gte,
659    Eq,
660    Neq,
661}
662
663impl FromStr for ConditionOperator {
664    type Err = ();
665    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
666        match s {
667            "lt" => Ok(ConditionOperator::Lt),
668            "lte" => Ok(ConditionOperator::Lte),
669            "gt" => Ok(ConditionOperator::Gt),
670            "gte" => Ok(ConditionOperator::Gte),
671            "eq" => Ok(ConditionOperator::Eq),
672            "neq" => Ok(ConditionOperator::Neq),
673            _ => Err(()),
674        }
675    }
676}
677
678/// Condition for a correlation rule.
679///
680/// Reference: pySigma correlations.py SigmaCorrelationCondition
681#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
682pub enum CorrelationCondition {
683    /// Threshold condition with one or more predicates (supports ranges).
684    ///
685    /// Single: `gte: 100`
686    /// Range: `gt: 100` + `lte: 200`
687    Threshold {
688        /// One or more (operator, value) predicates. All must be satisfied.
689        predicates: Vec<(ConditionOperator, u64)>,
690        /// Optional field reference(s) (required for `value_count` type).
691        /// A single string is normalized to a one-element vec.
692        field: Option<Vec<String>>,
693        /// Percentile rank (0-100) for `value_percentile` type.
694        /// Defaults to 50 if not specified.
695        percentile: Option<u64>,
696    },
697    /// Extended boolean condition for temporal types: `"rule_a and rule_b"`
698    Extended(ConditionExpr),
699}
700
701/// Field alias mapping in a correlation rule.
702///
703/// Maps a canonical alias name to per-rule field name mappings.
704///
705/// Reference: pySigma correlations.py SigmaCorrelationFieldAlias
706#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
707pub struct FieldAlias {
708    pub alias: String,
709    /// Maps rule reference (ID or name) → field name in that rule's events.
710    pub mapping: HashMap<String, String>,
711}
712
713/// A Sigma correlation rule.
714///
715/// Reference: pySigma correlations.py SigmaCorrelationRule
716#[derive(Debug, Clone, PartialEq, Serialize)]
717pub struct CorrelationRule {
718    // Metadata (shared with detection rules)
719    pub title: String,
720    /// The Sigma specification MAJOR version this document targets (the
721    /// `sigma-version` attribute). See [`SigmaRule::sigma_version`]. A
722    /// correlation rule and the rules it aggregates should share a major.
723    #[serde(skip_serializing_if = "Option::is_none")]
724    pub sigma_version: Option<u32>,
725    pub id: Option<String>,
726    pub name: Option<String>,
727    pub status: Option<Status>,
728    pub description: Option<String>,
729    pub author: Option<String>,
730    pub date: Option<String>,
731    pub modified: Option<String>,
732    pub related: Vec<Related>,
733    pub references: Vec<String>,
734    pub taxonomy: Option<String>,
735    pub license: Option<String>,
736    pub tags: Vec<String>,
737    pub fields: Vec<String>,
738    pub falsepositives: Vec<String>,
739    pub level: Option<Level>,
740    pub scope: Vec<String>,
741
742    // Correlation-specific fields
743    pub correlation_type: CorrelationType,
744    pub rules: Vec<String>,
745    pub group_by: Vec<String>,
746    pub timespan: Timespan,
747    /// Window semantics for `timespan`: `sliding` (default), `tumbling`, or
748    /// `session`. Absent in the source defaults to [`WindowMode::Sliding`].
749    pub window: WindowMode,
750    /// Maximum inactivity between consecutive in-group events for a `session`
751    /// window. Required when `window` is `session`, and unset otherwise.
752    #[serde(skip_serializing_if = "Option::is_none")]
753    pub gap: Option<Timespan>,
754    pub condition: CorrelationCondition,
755    pub aliases: Vec<FieldAlias>,
756    pub generate: bool,
757
758    /// Custom attributes attached to the correlation rule.
759    ///
760    /// Populated the same way as `SigmaRule.custom_attributes`: arbitrary
761    /// top-level YAML keys, the dedicated `custom_attributes:` block, and
762    /// pipeline `SetCustomAttribute` transformations (last-write-wins).
763    /// Engine-level `rsigma.*` extensions (e.g. `rsigma.correlation_event_mode`,
764    /// `rsigma.suppress`, `rsigma.action`) are read from here.
765    #[serde(skip_serializing_if = "HashMap::is_empty")]
766    pub custom_attributes: HashMap<String, yaml_serde::Value>,
767}
768
769// =============================================================================
770// Filter Rule
771// =============================================================================
772
773/// Which rules a filter applies to.
774#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
775pub enum FilterRuleTarget {
776    /// The filter applies to every loaded rule.
777    Any,
778    /// The filter applies only to rules matching these IDs or titles.
779    Specific(Vec<String>),
780}
781
782/// A Sigma filter rule that modifies the detection logic of referenced rules.
783///
784/// Filters add additional conditions (typically exclusions) to existing rules
785/// without modifying the original rule files.
786#[derive(Debug, Clone, PartialEq, Serialize)]
787pub struct FilterRule {
788    pub title: String,
789    /// The Sigma specification MAJOR version this document targets (the
790    /// `sigma-version` attribute). See [`SigmaRule::sigma_version`]. A filter and
791    /// the rules it targets should share a major.
792    #[serde(skip_serializing_if = "Option::is_none")]
793    pub sigma_version: Option<u32>,
794    pub id: Option<String>,
795    pub name: Option<String>,
796    pub taxonomy: Option<String>,
797    pub status: Option<Status>,
798    pub description: Option<String>,
799    pub author: Option<String>,
800    pub date: Option<String>,
801    pub modified: Option<String>,
802    pub related: Vec<Related>,
803    pub license: Option<String>,
804    pub references: Vec<String>,
805    pub tags: Vec<String>,
806    pub fields: Vec<String>,
807    pub falsepositives: Vec<String>,
808    pub level: Option<Level>,
809    pub scope: Vec<String>,
810    /// The log source the filter applies to. The parser always sets it, as the
811    /// Sigma filter specification requires; `None` on a filter built in code
812    /// applies it to rules of any log source.
813    pub logsource: Option<LogSource>,
814
815    /// Rules this filter applies to (by ID or name), or all rules.
816    pub rules: FilterRuleTarget,
817    /// The filter detection section.
818    pub detection: Detections,
819
820    /// Custom attributes attached to the filter rule.
821    #[serde(skip_serializing_if = "HashMap::is_empty")]
822    pub custom_attributes: HashMap<String, yaml_serde::Value>,
823}
824
825// =============================================================================
826// Collection / Document
827// =============================================================================
828
829/// A single parsed document from a Sigma YAML file.
830///
831/// A YAML file may contain multiple documents separated by `---`.
832/// Each document is either a detection rule, correlation rule, filter, or action.
833#[derive(Debug, Clone, PartialEq, Serialize)]
834pub enum SigmaDocument {
835    Rule(Box<SigmaRule>),
836    Correlation(CorrelationRule),
837    Filter(FilterRule),
838}
839
840/// A collection of parsed Sigma documents from one or more YAML files.
841#[derive(Debug, Clone, Serialize)]
842pub struct SigmaCollection {
843    pub rules: Vec<SigmaRule>,
844    pub correlations: Vec<CorrelationRule>,
845    pub filters: Vec<FilterRule>,
846    /// Problems found while building the collection, in the order they
847    /// were found. An [error](crate::DiagnosticSeverity::Error) means a
848    /// document was dropped; a [warning](crate::DiagnosticSeverity::Warning)
849    /// means a document was kept with an invalid value ignored. The
850    /// collection is returned on `Ok(_)` either way, so callers decide
851    /// whether a partial parse is acceptable;
852    /// [`SigmaCollection::has_errors`] and [`SigmaCollection::into_result`]
853    /// cover the common "fail on any error" path.
854    #[serde(skip)]
855    pub diagnostics: Vec<CollectionDiagnostic>,
856}
857
858impl SigmaCollection {
859    pub fn new() -> Self {
860        SigmaCollection {
861            rules: Vec::new(),
862            correlations: Vec::new(),
863            filters: Vec::new(),
864            diagnostics: Vec::new(),
865        }
866    }
867
868    /// Total number of parsed documents.
869    pub fn len(&self) -> usize {
870        self.rules.len() + self.correlations.len() + self.filters.len()
871    }
872
873    pub fn is_empty(&self) -> bool {
874        self.len() == 0
875    }
876
877    /// The error diagnostics, in order.
878    pub fn errors(&self) -> impl Iterator<Item = &CollectionDiagnostic> {
879        self.diagnostics.iter().filter(|d| d.is_error())
880    }
881
882    /// The warning diagnostics, in order.
883    pub fn warnings(&self) -> impl Iterator<Item = &CollectionDiagnostic> {
884        self.diagnostics.iter().filter(|d| !d.is_error())
885    }
886
887    /// True when at least one diagnostic is an error. Warnings do not count.
888    pub fn has_errors(&self) -> bool {
889        self.errors().next().is_some()
890    }
891
892    /// Number of error diagnostics.
893    pub fn error_count(&self) -> usize {
894        self.errors().count()
895    }
896
897    /// Number of warning diagnostics.
898    pub fn warning_count(&self) -> usize {
899        self.warnings().count()
900    }
901
902    /// Promote errors to a hard failure. Returns the collection, warnings
903    /// included, when [`SigmaCollection::has_errors`] is false; otherwise
904    /// returns every diagnostic, warnings included, so callers can report
905    /// them together. The collection is consumed either way so the success
906    /// path can move out of `self` without re-cloning the documents.
907    pub fn into_result(self) -> Result<Self, Vec<CollectionDiagnostic>> {
908        if self.has_errors() {
909            Err(self.diagnostics)
910        } else {
911            Ok(self)
912        }
913    }
914}
915
916impl Default for SigmaCollection {
917    fn default() -> Self {
918        Self::new()
919    }
920}