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
18pub(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 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
111pub(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 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 let conditions: Vec<ConditionExpr> = condition_strings
163 .iter()
164 .map(|s| parse_condition(s))
165 .collect::<Result<Vec<_>>>()?;
166
167 let timeframe = get_str(m, "timeframe").map(|s| s.to_string());
169
170 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
195fn parse_detection(value: &Value, array_matching: bool) -> Result<Detection> {
204 match value {
205 Value::Mapping(m) => {
206 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 let all_plain = seq.iter().all(|v| !v.is_mapping() && !v.is_sequence());
232 if all_plain {
233 let values = seq.iter().map(SigmaValue::from_yaml).collect();
235 Ok(Detection::Keywords(values))
236 } else {
237 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 _ => Ok(Detection::Keywords(vec![SigmaValue::from_yaml(value)])),
247 }
248}
249
250fn parse_detection_item(key: &str, value: &Value) -> Result<DetectionItem> {
259 build_item(parse_field_spec(key)?, value)
260}
261
262fn 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
281struct PathSegment {
303 name: String,
304 index: Option<i64>,
307 quantifier: Option<ArrayQuantifier>,
309}
310
311impl PathSegment {
312 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
323enum ParsedEntry {
326 Item(DetectionItem),
327 Block(Detection),
328}
329
330fn 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
348fn parse_map_entry(key: &str, value: &Value, array_matching: bool) -> Result<ParsedEntry> {
351 let (field_part, modifier_part) = match key.split_once('|') {
353 Some((f, m)) => (f, Some(m)),
354 None => (key, None),
355 };
356
357 if field_part.is_empty() {
360 return Ok(ParsedEntry::Item(parse_detection_item(key, value)?));
361 }
362
363 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 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 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
416fn 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 match value {
426 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 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 _ => {
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 let prefix = reconstruct_key(remaining, None);
455 parse_block_with_prefix(&prefix, value, array_matching)
456 } else {
457 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
467fn 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
497fn 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
527fn 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
546fn parse_field_path(field_part: &str) -> Result<Vec<PathSegment>> {
554 let mut segments = Vec::new();
555 for raw in field_part.split('.') {
556 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
602fn 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 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
625fn 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
642fn 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
654pub 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 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}