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(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
44pub(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 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
114pub(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 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 let conditions: Vec<ConditionExpr> = condition_strings
166 .iter()
167 .map(|s| parse_condition(s))
168 .collect::<Result<Vec<_>>>()?;
169
170 let timeframe = get_str(m, "timeframe").map(|s| s.to_string());
172
173 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
198fn parse_detection(value: &Value, array_matching: bool) -> Result<Detection> {
207 match value {
208 Value::Mapping(m) => {
209 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 let all_plain = seq.iter().all(|v| !v.is_mapping() && !v.is_sequence());
235 if all_plain {
236 let values = seq.iter().map(SigmaValue::from_yaml).collect();
238 Ok(Detection::Keywords(values))
239 } else {
240 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 _ => Ok(Detection::Keywords(vec![SigmaValue::from_yaml(value)])),
250 }
251}
252
253fn parse_detection_item(key: &str, value: &Value) -> Result<DetectionItem> {
262 build_item(parse_field_spec(key)?, value)
263}
264
265fn 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
284struct PathSegment {
306 name: String,
307 index: Option<i64>,
310 quantifier: Option<ArrayQuantifier>,
312}
313
314impl PathSegment {
315 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
326enum ParsedEntry {
329 Item(DetectionItem),
330 Block(Detection),
331}
332
333fn 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
351fn parse_map_entry(key: &str, value: &Value, array_matching: bool) -> Result<ParsedEntry> {
354 let (field_part, modifier_part) = match key.split_once('|') {
356 Some((f, m)) => (f, Some(m)),
357 None => (key, None),
358 };
359
360 if field_part.is_empty() {
363 return Ok(ParsedEntry::Item(parse_detection_item(key, value)?));
364 }
365
366 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 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 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
419fn 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 match value {
429 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 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 _ => {
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 let prefix = reconstruct_key(remaining, None);
458 parse_block_with_prefix(&prefix, value, array_matching)
459 } else {
460 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
470fn 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
500fn 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
530fn 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
549fn parse_field_path(field_part: &str) -> Result<Vec<PathSegment>> {
557 let mut segments = Vec::new();
558 for raw in field_part.split('.') {
559 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
605fn 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 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
628fn 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
645fn 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
657pub 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 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}