Skip to main content

rsigma_parser/parser/
detection.rs

1use std::collections::HashMap;
2
3use yaml_serde::Value;
4
5use crate::ast::*;
6use crate::condition::parse_condition;
7use crate::diagnostic::CollectionDiagnostic;
8use crate::error::{Result, SigmaParserError};
9use crate::fieldpath::{ends_with_unescaped, escape_brackets, first_unescaped};
10use crate::validate::{check_condition, check_detection, check_detection_item};
11use crate::value::SigmaValue;
12
13use super::{
14    collect_custom_attributes, get_str, get_str_list, parse_enum_with_warn, parse_logsource,
15    parse_related, parse_sigma_version, val_key,
16};
17
18/// Top-level keys the parser reads; any other top-level key becomes a
19/// custom attribute.
20pub(crate) const STANDARD_RULE_KEYS: &[&str] = &[
21    "title",
22    "sigma-version",
23    "id",
24    "related",
25    "name",
26    "taxonomy",
27    "status",
28    "description",
29    "license",
30    "author",
31    "references",
32    "date",
33    "modified",
34    "logsource",
35    "detection",
36    "fields",
37    "falsepositives",
38    "level",
39    "tags",
40    "scope",
41    "custom_attributes",
42];
43
44// =============================================================================
45// Detection Rule Parsing
46// =============================================================================
47
48/// Parse a detection rule from a YAML value.
49///
50/// `warnings` receives non-fatal issues that would otherwise be
51/// silently swallowed (invalid `status` / `level` values, malformed
52/// `related:` entries). The parser still returns `Ok(rule)` for
53/// these so a single typo does not invalidate the whole document.
54///
55/// Reference: pySigma rule.py SigmaRule.from_yaml / from_dict
56pub(super) fn parse_detection_rule(
57    value: &Value,
58    warnings: &mut Vec<CollectionDiagnostic>,
59) -> Result<SigmaRule> {
60    let m = value
61        .as_mapping()
62        .ok_or_else(|| SigmaParserError::InvalidRule("Expected a YAML mapping".into()))?;
63
64    let title = get_str(m, "title")
65        .ok_or_else(|| SigmaParserError::MissingField("title".into()))?
66        .to_string();
67
68    let sigma_version = parse_sigma_version(m, warnings);
69
70    let detection_val = m
71        .get(val_key("detection"))
72        .ok_or_else(|| SigmaParserError::MissingField("detection".into()))?;
73    let detection = parse_detections(
74        detection_val,
75        crate::version::array_matching_enabled(sigma_version),
76    )?;
77
78    let logsource = parse_logsource(
79        m.get(val_key("logsource"))
80            .ok_or_else(|| SigmaParserError::MissingField("logsource".into()))?,
81    )?;
82
83    // Custom attributes: merge arbitrary top-level keys and the entries of the
84    // dedicated `custom_attributes:` mapping. Entries in `custom_attributes:`
85    // win over a top-level key of the same name (last-write-wins).
86    // Mirrors pySigma's `SigmaRule.custom_attributes` dict.
87    let custom_attributes = collect_custom_attributes(m, STANDARD_RULE_KEYS);
88
89    Ok(SigmaRule {
90        title,
91        logsource,
92        detection,
93        sigma_version,
94        id: get_str(m, "id").map(|s| s.to_string()),
95        name: get_str(m, "name").map(|s| s.to_string()),
96        related: parse_related(m.get(val_key("related")), warnings),
97        taxonomy: get_str(m, "taxonomy").map(|s| s.to_string()),
98        status: parse_enum_with_warn(get_str(m, "status"), "status", warnings),
99        description: get_str(m, "description").map(|s| s.to_string()),
100        license: get_str(m, "license").map(|s| s.to_string()),
101        author: get_str(m, "author").map(|s| s.to_string()),
102        references: get_str_list(m, "references"),
103        date: get_str(m, "date").map(|s| s.to_string()),
104        modified: get_str(m, "modified").map(|s| s.to_string()),
105        fields: get_str_list(m, "fields"),
106        falsepositives: get_str_list(m, "falsepositives"),
107        level: parse_enum_with_warn(get_str(m, "level"), "level", warnings),
108        tags: get_str_list(m, "tags"),
109        scope: get_str_list(m, "scope"),
110        custom_attributes,
111    })
112}
113
114// =============================================================================
115// Detection Section Parsing
116// =============================================================================
117
118/// Parse the `detection:` section of a rule.
119///
120/// The detection section contains:
121/// - `condition`: string or list of strings
122/// - `timeframe`: optional duration string
123/// - Everything else: named detection identifiers
124///
125/// Reference: pySigma rule/detection.py SigmaDetections.from_dict
126pub(super) fn parse_detections(value: &Value, array_matching: bool) -> Result<Detections> {
127    let m = value.as_mapping().ok_or_else(|| {
128        SigmaParserError::InvalidDetection("Detection section must be a mapping".into())
129    })?;
130
131    // Extract condition (required)
132    let condition_val = m
133        .get(val_key("condition"))
134        .ok_or_else(|| SigmaParserError::MissingField("condition".into()))?;
135
136    let condition_strings = match condition_val {
137        Value::String(s) => vec![s.clone()],
138        Value::Sequence(seq) => {
139            if seq.is_empty() {
140                return Err(SigmaParserError::InvalidDetection(
141                    "condition list must not be empty".into(),
142                ));
143            }
144            let mut strings = Vec::with_capacity(seq.len());
145            for v in seq {
146                match v.as_str() {
147                    Some(s) => strings.push(s.to_string()),
148                    None => {
149                        return Err(SigmaParserError::InvalidDetection(format!(
150                            "condition list items must be strings, got: {v:?}"
151                        )));
152                    }
153                }
154            }
155            strings
156        }
157        _ => {
158            return Err(SigmaParserError::InvalidDetection(
159                "condition must be a string or list of strings".into(),
160            ));
161        }
162    };
163
164    // Parse each condition string
165    let conditions: Vec<ConditionExpr> = condition_strings
166        .iter()
167        .map(|s| parse_condition(s))
168        .collect::<Result<Vec<_>>>()?;
169
170    // Extract optional timeframe
171    let timeframe = get_str(m, "timeframe").map(|s| s.to_string());
172
173    // Parse all named detections (everything except condition and timeframe)
174    let mut named = HashMap::new();
175    for (key, val) in m {
176        let key_str = key.as_str().unwrap_or("");
177        if key_str == "condition" || key_str == "timeframe" {
178            continue;
179        }
180        let detection = parse_detection(val, array_matching)?;
181        check_detection(key_str, &detection)?;
182        named.insert(key_str.to_string(), detection);
183    }
184
185    let names: Vec<&str> = named.keys().map(String::as_str).collect();
186    for condition in &conditions {
187        check_condition(condition, &names)?;
188    }
189
190    Ok(Detections {
191        named,
192        conditions,
193        condition_strings,
194        timeframe,
195    })
196}
197
198/// Parse a single named detection definition.
199///
200/// A detection can be:
201/// 1. A mapping (key-value pairs, AND-linked)
202/// 2. A list of plain values (keyword detection)
203/// 3. A list of mappings (OR-linked sub-detections)
204///
205/// Reference: pySigma rule/detection.py SigmaDetection.from_definition
206fn parse_detection(value: &Value, array_matching: bool) -> Result<Detection> {
207    match value {
208        Value::Mapping(m) => {
209            // Case 1: key-value mapping → AND-linked detection items.
210            //
211            // Keys without an `any`/`all` selector become plain detection items
212            // exactly as before (a positional `[N]` index stays in the field
213            // path). Keys carrying an `any`/`all` selector desugar into
214            // `Detection::ArrayMatch` object-scope blocks. A map with no blocks
215            // stays an `AllOf`; a single block becomes that block; a mix
216            // becomes an `And`.
217            let mut items: Vec<DetectionItem> = Vec::new();
218            let mut blocks: Vec<Detection> = Vec::new();
219            for (k, v) in m.iter() {
220                match parse_map_entry(k.as_str().unwrap_or(""), v, array_matching)? {
221                    ParsedEntry::Item(item) => items.push(item),
222                    ParsedEntry::Block(block) => blocks.push(block),
223                }
224            }
225            Ok(combine_entries(items, blocks))
226        }
227        Value::Sequence(seq) => {
228            if seq.iter().any(Value::is_sequence) {
229                return Err(SigmaParserError::InvalidDetection(
230                    "a detection list must not contain nested lists".into(),
231                ));
232            }
233            // Check if all items are plain values (strings/numbers/etc.)
234            let all_plain = seq.iter().all(|v| !v.is_mapping() && !v.is_sequence());
235            if all_plain {
236                // Case 2: list of plain values → keyword detection
237                let values = seq.iter().map(SigmaValue::from_yaml).collect();
238                Ok(Detection::Keywords(values))
239            } else {
240                // Case 3: list of mappings → OR-linked sub-detections
241                let subs: Vec<Detection> = seq
242                    .iter()
243                    .map(|v| parse_detection(v, array_matching))
244                    .collect::<Result<Vec<_>>>()?;
245                Ok(Detection::AnyOf(subs))
246            }
247        }
248        // Plain value → single keyword
249        _ => Ok(Detection::Keywords(vec![SigmaValue::from_yaml(value)])),
250    }
251}
252
253/// Parse a single detection item from a key-value pair.
254///
255/// The key contains the field name and optional modifiers separated by `|`:
256/// - `EventType` → field="EventType", no modifiers
257/// - `TargetObject|endswith` → field="TargetObject", modifiers=[EndsWith]
258/// - `Destination|contains|all` → field="Destination", modifiers=[Contains, All]
259///
260/// Reference: pySigma rule/detection.py SigmaDetectionItem.from_mapping
261fn parse_detection_item(key: &str, value: &Value) -> Result<DetectionItem> {
262    build_item(parse_field_spec(key)?, value)
263}
264
265/// Build and check a detection item from its field spec and a scalar or list
266/// value.
267fn build_item(field: FieldSpec, value: &Value) -> Result<DetectionItem> {
268    let scalars = match value {
269        Value::Sequence(seq) => seq.as_slice(),
270        _ => std::slice::from_ref(value),
271    };
272    if scalars.iter().any(|v| v.is_sequence() || v.is_mapping()) {
273        let subject = field.name.as_deref().unwrap_or("keyword");
274        return Err(SigmaParserError::InvalidValue(format!(
275            "'{subject}' takes a value or a list of values, not a nested list or mapping"
276        )));
277    }
278    let values = scalars.iter().map(|v| to_sigma_value(v, &field)).collect();
279    let item = DetectionItem { field, values };
280    check_detection_item(&item)?;
281    Ok(item)
282}
283
284// =============================================================================
285// Array matching: object-scope quantifier blocks + positional indexing
286// =============================================================================
287//
288// Proposed Sigma array-matching extension (sigma-specification Discussion #106,
289// rsigma #158). A detection key whose field path carries an `any`/`all`
290// selector desugars into a `Detection::ArrayMatch`:
291//
292//   connections[any]:            ArrayMatch { field: "connections", quantifier: Any,
293//     protocol: "TCP"      ==>       body: AllOf([protocol == "TCP", ip cidr ...]) }
294//     ip|cidr: "10.0.0.0/8"
295//
296//   connections[any].ip: "x" ==> ArrayMatch { field: "connections", quantifier: Any,
297//                                              body: AllOf([ip == "x"]) }
298//
299// A positional `[N]` index is NOT a quantifier: it stays in the field-path
300// string (`args[0]`, `connections[0].ip`) and is resolved by the evaluator and
301// converters. Keys with no `any`/`all` selector parse exactly as before.
302
303/// A parsed field-path segment: a name plus an optional array selector. At most
304/// one of `index` / `quantifier` is set (a segment carries one `[...]`).
305struct PathSegment {
306    name: String,
307    /// Positional `[N]` index, possibly negative (`[-1]` is the last element).
308    /// Stays in the literal field path.
309    index: Option<i64>,
310    /// `[any]`/`[all]` quantifier (a desugaring point for object-scope blocks).
311    quantifier: Option<ArrayQuantifier>,
312}
313
314impl PathSegment {
315    /// Render this segment as part of a literal field path, re-appending a
316    /// positional `[N]` marker (but not the `any`/`all` quantifier, which is
317    /// consumed when a block is opened).
318    fn path_str(&self) -> String {
319        match self.index {
320            Some(i) => format!("{}[{i}]", self.name),
321            None => self.name.clone(),
322        }
323    }
324}
325
326/// The result of parsing one mapping entry: either a plain detection item or an
327/// array object-scope block.
328enum ParsedEntry {
329    Item(DetectionItem),
330    Block(Detection),
331}
332
333/// Combine the items and blocks parsed from a YAML mapping into a detection: an
334/// `AllOf` when there are no blocks, the single block alone, or an `And` of the
335/// plain items plus each block.
336fn combine_entries(items: Vec<DetectionItem>, blocks: Vec<Detection>) -> Detection {
337    if blocks.is_empty() {
338        Detection::AllOf(items)
339    } else if items.is_empty() && blocks.len() == 1 {
340        blocks.into_iter().next().expect("len checked")
341    } else {
342        let mut parts: Vec<Detection> = Vec::new();
343        if !items.is_empty() {
344            parts.push(Detection::AllOf(items));
345        }
346        parts.extend(blocks);
347        Detection::And(parts)
348    }
349}
350
351/// Parse one `key: value` mapping entry, desugaring `any`/`all` array
352/// quantifiers and indexed object-scope blocks.
353fn parse_map_entry(key: &str, value: &Value, array_matching: bool) -> Result<ParsedEntry> {
354    // Split the field path from the trailing modifier chain (`field|mod1|mod2`).
355    let (field_part, modifier_part) = match key.split_once('|') {
356        Some((f, m)) => (f, Some(m)),
357        None => (key, None),
358    };
359
360    // Empty field part (keyword-style key or bare modifiers): defer to the
361    // existing field-spec parser, which already handles these cases.
362    if field_part.is_empty() {
363        return Ok(ParsedEntry::Item(parse_detection_item(key, value)?));
364    }
365
366    // Below the array-matching spec version, a trailing `[...]` is not a
367    // selector: brackets are literal field-name characters. Escape any
368    // unescaped bracket so the escape-aware field resolver (evaluator and
369    // converters) reads the name literally, and keep the entry a plain item.
370    if !array_matching {
371        let escaped = escape_brackets(field_part);
372        let plain_key = match modifier_part {
373            Some(m) => format!("{escaped}|{m}"),
374            None => escaped.into_owned(),
375        };
376        return Ok(ParsedEntry::Item(parse_detection_item(&plain_key, value)?));
377    }
378
379    let segments = parse_field_path(field_part)?;
380    match segments.iter().position(|s| s.quantifier.is_some()) {
381        Some(idx) => {
382            let quantifier = segments[idx]
383                .quantifier
384                .expect("position found a quantifier");
385            // The array lives at the path up to and including the quantified
386            // segment (positional `[N]` markers before it are preserved).
387            let array_field = segments[..=idx]
388                .iter()
389                .map(PathSegment::path_str)
390                .collect::<Vec<_>>()
391                .join(".");
392            let body =
393                build_block_body(&segments[idx + 1..], modifier_part, value, array_matching)?;
394            Ok(ParsedEntry::Block(Detection::ArrayMatch {
395                field: array_field,
396                quantifier,
397                body: Box::new(body),
398            }))
399        }
400        // No `any`/`all` selector. A map value on an indexed key opens a block
401        // scoped to that one element; otherwise it is a plain item whose field
402        // path keeps any positional `[N]` markers.
403        None => {
404            let has_index = segments.iter().any(|s| s.index.is_some());
405            if value.is_mapping() && has_index {
406                let prefix = reconstruct_key(&segments, None);
407                Ok(ParsedEntry::Block(parse_block_with_prefix(
408                    &prefix,
409                    value,
410                    array_matching,
411                )?))
412            } else {
413                Ok(ParsedEntry::Item(parse_detection_item(key, value)?))
414            }
415        }
416    }
417}
418
419/// Build the nested detection that an array block evaluates per member.
420fn build_block_body(
421    remaining: &[PathSegment],
422    modifier_part: Option<&str>,
423    value: &Value,
424    array_matching: bool,
425) -> Result<Detection> {
426    if remaining.is_empty() {
427        // The quantifier was on the final path segment.
428        match value {
429            // `field[any]: { sub-map }` → object-scope block over member fields.
430            Value::Mapping(m) => {
431                if modifier_part.is_some() {
432                    return Err(SigmaParserError::InvalidFieldSpec(
433                        "value modifiers cannot be applied to an array object-scope block; \
434                         move the modifier onto a field inside the block"
435                            .into(),
436                    ));
437                }
438                // A `condition:` key opens the extended (nested-detection) body:
439                // named element-scoped sub-selections combined with and/or/not.
440                // Without it, the body is the basic conjunction map.
441                if m.iter().any(|(k, _)| k.as_str() == Some("condition")) {
442                    parse_extended_block_body(value, array_matching)
443                } else {
444                    parse_detection(value, array_matching)
445                }
446            }
447            // `field[all]: value` (or a list) → match the array member itself.
448            // Represented as a body item with no field name.
449            _ => {
450                let field = FieldSpec::new(None, parse_modifiers(modifier_part)?);
451                Ok(Detection::AllOf(vec![build_item(field, value)?]))
452            }
453        }
454    } else if value.is_mapping() {
455        // A map value after more path segments: the element's sub-object must
456        // satisfy the block. Expand it under the remaining path prefix.
457        let prefix = reconstruct_key(remaining, None);
458        parse_block_with_prefix(&prefix, value, array_matching)
459    } else {
460        // A selector in the middle of the path with a scalar/list leaf: recurse
461        // on the remainder so further selectors and the leaf predicate desugar.
462        let remaining_key = reconstruct_key(remaining, modifier_part);
463        match parse_map_entry(&remaining_key, value, array_matching)? {
464            ParsedEntry::Item(item) => Ok(Detection::AllOf(vec![item])),
465            ParsedEntry::Block(block) => Ok(block),
466        }
467    }
468}
469
470/// Parse the **extended** object-scope block body: named element-scoped
471/// sub-selections plus a `condition:` combining them with `and`/`or`/`not`,
472/// evaluated against a single array member (the recursive "mini-event" form).
473fn parse_extended_block_body(value: &Value, array_matching: bool) -> Result<Detection> {
474    let m = value.as_mapping().ok_or_else(|| {
475        SigmaParserError::InvalidDetection("extended array block body must be a mapping".into())
476    })?;
477    let mut named: HashMap<String, Detection> = HashMap::new();
478    let mut condition: Option<ConditionExpr> = None;
479    for (k, v) in m.iter() {
480        let key = k.as_str().ok_or_else(|| {
481            SigmaParserError::InvalidDetection("non-string key in array block body".into())
482        })?;
483        if key == "condition" {
484            condition = Some(parse_block_condition(v)?);
485        } else {
486            named.insert(key.to_string(), parse_detection(v, array_matching)?);
487        }
488    }
489    let condition = condition.ok_or_else(|| {
490        SigmaParserError::InvalidDetection("extended array block requires a 'condition'".into())
491    })?;
492    if named.is_empty() {
493        return Err(SigmaParserError::InvalidDetection(
494            "extended array block has a 'condition' but no named sub-selections".into(),
495        ));
496    }
497    Ok(Detection::Conditional { named, condition })
498}
499
500/// Parse the `condition:` value inside an extended array block: a single
501/// expression string, or a list of strings combined with OR.
502fn parse_block_condition(value: &Value) -> Result<ConditionExpr> {
503    match value {
504        Value::String(s) => parse_condition(s),
505        Value::Sequence(seq) => {
506            if seq.is_empty() {
507                return Err(SigmaParserError::InvalidDetection(
508                    "array block 'condition' list must not be empty".into(),
509                ));
510            }
511            let exprs = seq
512                .iter()
513                .map(|x| {
514                    let s = x.as_str().ok_or_else(|| {
515                        SigmaParserError::InvalidDetection(
516                            "array block 'condition' list items must be strings".into(),
517                        )
518                    })?;
519                    parse_condition(s)
520                })
521                .collect::<Result<Vec<_>>>()?;
522            Ok(ConditionExpr::Or(exprs))
523        }
524        _ => Err(SigmaParserError::InvalidDetection(
525            "array block 'condition' must be a string or list of strings".into(),
526        )),
527    }
528}
529
530/// Parse a YAML mapping as a detection, prefixing every key with `prefix.` so
531/// the entries are scoped to an indexed element or a nested object.
532fn parse_block_with_prefix(prefix: &str, value: &Value, array_matching: bool) -> Result<Detection> {
533    let m = value.as_mapping().ok_or_else(|| {
534        SigmaParserError::InvalidDetection("array block body must be a mapping".into())
535    })?;
536    let mut items: Vec<DetectionItem> = Vec::new();
537    let mut blocks: Vec<Detection> = Vec::new();
538    for (k, v) in m.iter() {
539        let sub = k.as_str().unwrap_or("");
540        let key = format!("{prefix}.{sub}");
541        match parse_map_entry(&key, v, array_matching)? {
542            ParsedEntry::Item(item) => items.push(item),
543            ParsedEntry::Block(block) => blocks.push(block),
544        }
545    }
546    Ok(combine_entries(items, blocks))
547}
548
549/// Split a field path into dot-separated segments, recognizing the array
550/// selectors `[any]`, `[all]`, `[all_or_empty]`, `[none]`, and positional `[N]`
551/// (negative allowed) on the tail of a segment.
552///
553/// Only a well-formed quantifier or `name[<integer>]` is treated as a selector.
554/// Any other bracket token is a parse error so typos surface instead of
555/// silently matching a literal field name with brackets.
556fn parse_field_path(field_part: &str) -> Result<Vec<PathSegment>> {
557    let mut segments = Vec::new();
558    for raw in field_part.split('.') {
559        // Only an unescaped trailing `[...]` is a selector. An escaped bracket
560        // (`\[` / `\]`) is a literal part of the field name and leaves the
561        // segment plain; it is unescaped when the field is resolved.
562        if let Some(open) = first_unescaped(raw, b'[')
563            && ends_with_unescaped(raw, b']')
564        {
565            let name = &raw[..open];
566            let token = &raw[open + 1..raw.len() - 1];
567            if name.is_empty() {
568                return Err(SigmaParserError::InvalidFieldSpec(format!(
569                    "array selector without a field name in '{field_part}'"
570                )));
571            }
572            let (index, quantifier) = match token {
573                "any" => (None, Some(ArrayQuantifier::Any)),
574                "all" => (None, Some(ArrayQuantifier::All)),
575                "all_or_empty" => (None, Some(ArrayQuantifier::AllOrEmpty)),
576                "none" => (None, Some(ArrayQuantifier::None)),
577                _ => match token.parse::<i64>() {
578                    Ok(n) => (Some(n), None),
579                    Err(_) => {
580                        return Err(SigmaParserError::InvalidFieldSpec(format!(
581                            "unknown array selector '[{token}]' in field '{field_part}'; \
582                             only [any], [all], [all_or_empty], [none], and an integer index \
583                             [N] (negative counts from the end) are supported; \
584                             escape a literal bracket as \\[ or \\]"
585                        )));
586                    }
587                },
588            };
589            segments.push(PathSegment {
590                name: name.to_string(),
591                index,
592                quantifier,
593            });
594        } else {
595            segments.push(PathSegment {
596                name: raw.to_string(),
597                index: None,
598                quantifier: None,
599            });
600        }
601    }
602    Ok(segments)
603}
604
605/// Parse the pipe-separated modifier chain that follows the first `|` in a key.
606fn parse_modifiers(modifier_part: Option<&str>) -> Result<Vec<Modifier>> {
607    let mut modifiers = Vec::new();
608    if let Some(part) = modifier_part {
609        for mod_str in part.split('|') {
610            // Sigma reserves `not` for condition expressions; it is not a value
611            // modifier. Catch this idiom up front so the diagnostic explains
612            // the workaround instead of just saying "unknown modifier".
613            if mod_str == "not" {
614                return Err(SigmaParserError::NotIsNotAModifier);
615            }
616            let m = mod_str
617                .parse::<Modifier>()
618                .map_err(|_| SigmaParserError::UnknownModifier(mod_str.to_string()))?;
619            if modifiers.contains(&m) {
620                return Err(SigmaParserError::DuplicateModifier(mod_str.to_string()));
621            }
622            modifiers.push(m);
623        }
624    }
625    Ok(modifiers)
626}
627
628/// Rebuild a detection key string from path segments plus an optional modifier
629/// chain, re-appending `[any]`/`[all]` and positional `[N]` markers.
630fn reconstruct_key(segments: &[PathSegment], modifier_part: Option<&str>) -> String {
631    let path = segments
632        .iter()
633        .map(|s| match s.quantifier {
634            Some(q) => format!("{}[{q}]", s.name),
635            None => s.path_str(),
636        })
637        .collect::<Vec<_>>()
638        .join(".");
639    match modifier_part {
640        Some(m) => format!("{path}|{m}"),
641        None => path,
642    }
643}
644
645/// Convert a YAML value to a SigmaValue, respecting field modifiers.
646///
647/// When the `re` modifier is present, strings are treated as raw (no wildcard parsing).
648fn to_sigma_value(v: &Value, field: &FieldSpec) -> SigmaValue {
649    if field.has_modifier(Modifier::Re)
650        && let Value::String(s) = v
651    {
652        return SigmaValue::from_raw_string(s);
653    }
654    SigmaValue::from_yaml(v)
655}
656
657/// Parse a field specification string like `"TargetObject|endswith"`.
658///
659/// Reference: pySigma rule/detection.py — `field, *modifier_ids = key.split("|")`
660pub fn parse_field_spec(key: &str) -> Result<FieldSpec> {
661    if key.is_empty() {
662        return Ok(FieldSpec::new(None, Vec::new()));
663    }
664
665    let (field_name, modifier_part) = match key.split_once('|') {
666        Some((f, m)) => (f, Some(m)),
667        None => (key, None),
668    };
669    // A standalone `.` is the array-element reference inside an object-scope
670    // block body (the current scalar member); it lowers to a field-less item,
671    // which the evaluator matches against the member value itself. Outside a
672    // block body it has no special meaning, but a literal field named `.` is
673    // not a realistic event field, so the mapping is unconditional.
674    let field = if field_name.is_empty() || field_name == "." {
675        None
676    } else {
677        Some(field_name.to_string())
678    };
679
680    Ok(FieldSpec::new(field, parse_modifiers(modifier_part)?))
681}