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