Skip to main content

rsigma_parser/parser/
mod.rs

1//! Main YAML → AST parser for Sigma rules, correlations, filters, and collections.
2//!
3//! Handles:
4//! - Single-document YAML (one rule)
5//! - Multi-document YAML (--- separator, action: global/reset/repeat)
6//! - Detection section parsing (named detections, field modifiers, values)
7//! - Correlation rule parsing
8//! - Filter rule parsing
9//! - Directory-based rule collection loading
10//!
11//! Reference: pySigma collection.py, rule.py, rule/detection.py, correlations.py
12
13mod correlation;
14mod detection;
15mod filter;
16#[cfg(test)]
17mod tests;
18
19pub use detection::parse_field_spec;
20pub(crate) use {
21    correlation::STANDARD_CORRELATION_KEYS, detection::STANDARD_RULE_KEYS,
22    filter::STANDARD_FILTER_KEYS,
23};
24
25use std::collections::HashMap;
26use std::path::Path;
27
28use serde::Deserialize;
29use yaml_serde::Value;
30
31use crate::ast::*;
32use crate::diagnostic::{CollectionDiagnostic, DiagnosticKind};
33use crate::error::{Result, SigmaParserError, SourceLocation};
34
35// =============================================================================
36// Public API
37// =============================================================================
38
39/// Parse a YAML string containing one or more Sigma documents.
40///
41/// Handles multi-document YAML (separated by `---`) and collection actions
42/// (`action: global`, `action: reset`, `action: repeat`).
43///
44/// Reference: pySigma collection.py SigmaCollection.from_yaml
45pub fn parse_sigma_yaml(yaml: &str) -> Result<SigmaCollection> {
46    let mut collection = SigmaCollection::new();
47    let mut global: Option<Value> = None;
48    let mut previous: Option<Value> = None;
49
50    for (index, doc) in yaml_serde::Deserializer::from_str(yaml).enumerate() {
51        let report = |collection: &mut SigmaCollection, diagnostic: CollectionDiagnostic| {
52            collection.diagnostics.push(diagnostic.with_document(index));
53        };
54
55        let value: Value = match Value::deserialize(doc) {
56            Ok(v) => v,
57            Err(e) => {
58                let location = e.location().map(|loc| SourceLocation {
59                    line: u32::try_from(loc.line()).unwrap_or(u32::MAX),
60                    col: u32::try_from(loc.column()).unwrap_or(u32::MAX),
61                });
62                report(
63                    &mut collection,
64                    CollectionDiagnostic::error(
65                        DiagnosticKind::YamlSyntax,
66                        format!("YAML parse error: {e}"),
67                    )
68                    .with_location(location),
69                );
70                // A parse error leaves the YAML stream in an undefined state;
71                // the deserializer iterator may never terminate on malformed
72                // input, so we must stop iterating.
73                break;
74            }
75        };
76
77        let Some(mapping) = value.as_mapping() else {
78            report(
79                &mut collection,
80                CollectionDiagnostic::error(
81                    DiagnosticKind::NotAMapping,
82                    "Document is not a YAML mapping",
83                ),
84            );
85            continue;
86        };
87
88        // Check for collection action
89        let to_parse = if let Some(action_val) = mapping.get(Value::String("action".to_string())) {
90            let Some(action) = action_val.as_str() else {
91                report(
92                    &mut collection,
93                    CollectionDiagnostic::error(
94                        DiagnosticKind::CollectionAction,
95                        format!("collection 'action' must be a string, got: {action_val:?}"),
96                    ),
97                );
98                continue;
99            };
100            match action {
101                "global" => {
102                    let mut global_map = value.clone();
103                    if let Some(m) = global_map.as_mapping_mut() {
104                        m.remove(Value::String("action".to_string()));
105                    }
106                    global = Some(global_map);
107                    continue;
108                }
109                "reset" => {
110                    global = None;
111                    continue;
112                }
113                "repeat" => {
114                    // Merge current document onto the previous document
115                    let Some(ref prev) = previous else {
116                        report(
117                            &mut collection,
118                            CollectionDiagnostic::error(
119                                DiagnosticKind::CollectionAction,
120                                "'action: repeat' without a previous document",
121                            ),
122                        );
123                        continue;
124                    };
125                    let mut repeat_val = value.clone();
126                    if let Some(m) = repeat_val.as_mapping_mut() {
127                        m.remove(Value::String("action".to_string()));
128                    }
129                    let merged_repeat = deep_merge(prev.clone(), repeat_val)?;
130
131                    // Apply global template if present
132                    if let Some(ref global_val) = global {
133                        deep_merge(global_val.clone(), merged_repeat)?
134                    } else {
135                        merged_repeat
136                    }
137                }
138                other => {
139                    report(
140                        &mut collection,
141                        CollectionDiagnostic::error(
142                            DiagnosticKind::CollectionAction,
143                            format!("Unknown collection action: {other}"),
144                        ),
145                    );
146                    continue;
147                }
148            }
149        } else if let Some(ref global_val) = global {
150            // Merge with global template if present
151            deep_merge(global_val.clone(), value)?
152        } else {
153            value
154        };
155
156        // Track previous document for `action: repeat`
157        previous = Some(to_parse.clone());
158
159        // Determine document type and parse
160        let mut doc_warnings = Vec::new();
161        let parsed = parse_document(&to_parse, &mut doc_warnings);
162        for warning in doc_warnings {
163            report(&mut collection, warning);
164        }
165        match parsed {
166            Ok(SigmaDocument::Rule(rule)) => collection.rules.push(*rule),
167            Ok(SigmaDocument::Correlation(corr)) => collection.correlations.push(corr),
168            Ok(SigmaDocument::Filter(filter)) => collection.filters.push(filter),
169            Err(e) => report(&mut collection, CollectionDiagnostic::document(&e)),
170        }
171    }
172
173    Ok(collection)
174}
175
176/// Parse a single Sigma YAML file from a path.
177///
178/// Every diagnostic in the returned collection carries `path`.
179pub fn parse_sigma_file(path: &Path) -> Result<SigmaCollection> {
180    let content = std::fs::read_to_string(path)?;
181    let mut collection = parse_sigma_yaml(&content)?;
182    for diagnostic in &mut collection.diagnostics {
183        diagnostic.path = Some(path.to_path_buf());
184    }
185    Ok(collection)
186}
187
188/// Parse all Sigma YAML files from a directory (recursively).
189///
190/// A file that cannot be read or parsed at all is recorded as a
191/// [`DiagnosticKind::File`] error and the walk continues.
192pub fn parse_sigma_directory(dir: &Path) -> Result<SigmaCollection> {
193    let mut collection = SigmaCollection::new();
194
195    fn walk(dir: &Path, collection: &mut SigmaCollection) -> Result<()> {
196        for entry in std::fs::read_dir(dir)? {
197            let entry = entry?;
198            let path = entry.path();
199            if path.is_dir() {
200                walk(&path, collection)?;
201            } else if matches!(
202                path.extension().and_then(|e| e.to_str()),
203                Some("yml" | "yaml")
204            ) {
205                match parse_sigma_file(&path) {
206                    Ok(sub) => {
207                        collection.rules.extend(sub.rules);
208                        collection.correlations.extend(sub.correlations);
209                        collection.filters.extend(sub.filters);
210                        collection.diagnostics.extend(sub.diagnostics);
211                    }
212                    Err(e) => {
213                        collection
214                            .diagnostics
215                            .push(CollectionDiagnostic::file(&path, &e));
216                    }
217                }
218            }
219        }
220        Ok(())
221    }
222
223    walk(dir, &mut collection)?;
224    Ok(collection)
225}
226
227// =============================================================================
228// Document type detection and dispatch
229// =============================================================================
230
231/// Parse a single YAML value into the appropriate Sigma document type.
232///
233/// Reference: pySigma collection.py from_dicts — checks for 'correlation' and 'filter' keys
234fn parse_document(
235    value: &Value,
236    warnings: &mut Vec<CollectionDiagnostic>,
237) -> Result<SigmaDocument> {
238    let mapping = value
239        .as_mapping()
240        .ok_or_else(|| SigmaParserError::InvalidRule("Document is not a YAML mapping".into()))?;
241
242    if mapping.contains_key(Value::String("correlation".into())) {
243        correlation::parse_correlation_rule(value, warnings).map(SigmaDocument::Correlation)
244    } else if mapping.contains_key(Value::String("filter".into())) {
245        filter::parse_filter_rule(value, warnings).map(SigmaDocument::Filter)
246    } else {
247        detection::parse_detection_rule(value, warnings).map(|r| SigmaDocument::Rule(Box::new(r)))
248    }
249}
250
251// =============================================================================
252// Shared helpers
253// =============================================================================
254
255/// Build the unified `custom_attributes` map for a rule document.
256///
257/// Merges two sources:
258/// 1. Any top-level YAML key not in `standard_keys` (kept as-is, supports
259///    arbitrary nested values).
260/// 2. The entries of the top-level `custom_attributes:` mapping (if present),
261///    which override (1) for colliding keys.
262///
263/// Pipeline transformations such as `SetCustomAttribute` are applied later
264/// and can further override both sources.
265pub(super) fn collect_custom_attributes(
266    m: &yaml_serde::Mapping,
267    standard_keys: &[&str],
268) -> HashMap<String, Value> {
269    let mut attrs: HashMap<String, Value> = m
270        .iter()
271        .filter_map(|(k, v)| {
272            let key = k.as_str()?;
273            if standard_keys.contains(&key) {
274                None
275            } else {
276                Some((key.to_string(), v.clone()))
277            }
278        })
279        .collect();
280
281    if let Some(Value::Mapping(explicit)) = m.get(val_key("custom_attributes")) {
282        for (k, v) in explicit {
283            if let Some(key) = k.as_str() {
284                attrs.insert(key.to_string(), v.clone());
285            }
286        }
287    }
288
289    attrs
290}
291
292pub(super) fn parse_logsource(value: &Value) -> Result<LogSource> {
293    let m = value
294        .as_mapping()
295        .ok_or_else(|| SigmaParserError::InvalidRule("logsource must be a mapping".into()))?;
296
297    let known_keys = ["category", "product", "service", "definition"];
298    for key in known_keys {
299        if let Some(v) = m.get(val_key(key))
300            && !v.is_string()
301            && !v.is_null()
302        {
303            return Err(SigmaParserError::InvalidRule(format!(
304                "logsource {key} must be a string"
305            )));
306        }
307    }
308    if ["category", "product", "service"]
309        .iter()
310        .all(|key| get_str(m, key).is_none_or(str::is_empty))
311    {
312        return Err(SigmaParserError::InvalidRule(
313            "logsource must set at least one of category, product, or service".into(),
314        ));
315    }
316
317    let mut custom = HashMap::new();
318
319    for (k, v) in m {
320        let key_str = k.as_str().unwrap_or("");
321        if !known_keys.contains(&key_str) && !key_str.is_empty() {
322            match v.as_str() {
323                Some(val_str) => {
324                    custom.insert(key_str.to_string(), val_str.to_string());
325                }
326                None => {
327                    log::warn!(
328                        "logsource custom field '{key_str}' has non-string value ({v:?}), skipping"
329                    );
330                }
331            }
332        }
333    }
334
335    Ok(LogSource {
336        category: get_str(m, "category").map(|s| s.to_string()),
337        product: get_str(m, "product").map(|s| s.to_string()),
338        service: get_str(m, "service").map(|s| s.to_string()),
339        definition: get_str(m, "definition").map(|s| s.to_string()),
340        custom,
341    })
342}
343
344/// Parse a `related:` list. Surfaces invalid entries through
345/// `warnings` instead of silently dropping them so a typo in
346/// `type: derved` (a misspelt `derived`) shows up in
347/// `SigmaCollection.diagnostics` rather than being absent without trace.
348pub(super) fn parse_related(
349    value: Option<&Value>,
350    warnings: &mut Vec<CollectionDiagnostic>,
351) -> Vec<Related> {
352    let Some(seq_val) = value else {
353        return Vec::new();
354    };
355    let Some(seq) = seq_val.as_sequence() else {
356        warnings.push(metadata_warning(format!(
357            "'related' must be a sequence of mappings, got: {seq_val:?}"
358        )));
359        return Vec::new();
360    };
361
362    seq.iter()
363        .enumerate()
364        .filter_map(|(i, item)| {
365            let Some(m) = item.as_mapping() else {
366                warnings.push(metadata_warning(format!(
367                    "related[{i}] is not a mapping: {item:?}"
368                )));
369                return None;
370            };
371            let id = match get_str(m, "id") {
372                Some(s) => s.to_string(),
373                None => {
374                    warnings.push(metadata_warning(format!("related[{i}] missing 'id'")));
375                    return None;
376                }
377            };
378            let type_str = match get_str(m, "type") {
379                Some(s) => s,
380                None => {
381                    warnings.push(metadata_warning(format!("related[{i}] missing 'type'")));
382                    return None;
383                }
384            };
385            let relation_type = match type_str.parse() {
386                Ok(t) => t,
387                Err(_) => {
388                    warnings.push(metadata_warning(format!(
389                        "related[{i}] invalid type '{type_str}' (expected one of: \
390                         derived, obsolete, merged, renamed, similar)"
391                    )));
392                    return None;
393                }
394            };
395            Some(Related { id, relation_type })
396        })
397        .collect()
398}
399
400/// Parse a string value into an enum, pushing a warning into
401/// `warnings` when the value is present but does not parse. Returns
402/// `None` for both "absent" and "invalid", matching the previous
403/// silent `parse().ok()` contract for downstream consumers.
404pub(super) fn parse_enum_with_warn<T: std::str::FromStr>(
405    raw: Option<&str>,
406    field: &str,
407    warnings: &mut Vec<CollectionDiagnostic>,
408) -> Option<T> {
409    let raw = raw?;
410    match raw.parse() {
411        Ok(v) => Some(v),
412        Err(_) => {
413            warnings.push(metadata_warning(format!("invalid {field}: '{raw}'")));
414            None
415        }
416    }
417}
418
419/// Parse the optional top-level `sigma-version` attribute into its
420/// specification MAJOR version. Accepts an integer major (`3`) or a release
421/// string (`"2.1.0"`); only the major is significant, since breaking spec
422/// changes occur only at major bumps. A present-but-malformed value is reported
423/// through `warnings` and treated as absent (resolving to the fixed floor).
424pub(super) fn parse_sigma_version(
425    m: &yaml_serde::Mapping,
426    warnings: &mut Vec<CollectionDiagnostic>,
427) -> Option<u32> {
428    let value = m.get(val_key("sigma-version"))?;
429    match crate::version::major_from_value(value) {
430        Some(major) => Some(major),
431        None => {
432            warnings.push(metadata_warning(format!(
433                "invalid sigma-version: {value:?} (expected a major version integer like 3, \
434                 or a release string like \"2.1.0\")"
435            )));
436            None
437        }
438    }
439}
440
441fn metadata_warning(message: String) -> CollectionDiagnostic {
442    CollectionDiagnostic::warning(DiagnosticKind::Metadata, message)
443}
444
445pub(super) fn val_key(s: &str) -> Value {
446    Value::String(s.to_string())
447}
448
449pub(super) fn get_str<'a>(m: &'a yaml_serde::Mapping, key: &str) -> Option<&'a str> {
450    m.get(val_key(key)).and_then(|v| v.as_str())
451}
452
453pub(super) fn get_str_list(m: &yaml_serde::Mapping, key: &str) -> Vec<String> {
454    match m.get(val_key(key)) {
455        Some(Value::String(s)) => vec![s.clone()],
456        Some(Value::Sequence(seq)) => seq
457            .iter()
458            .filter_map(|v| v.as_str().map(|s| s.to_string()))
459            .collect(),
460        _ => Vec::new(),
461    }
462}
463
464/// Deep-merge two YAML values (src overrides dest, recursively for mappings).
465///
466/// Uses an explicit work-stack to avoid unbounded recursion from crafted input.
467/// Returns `MergeTooDeep` if nesting exceeds `MAX_DEPTH`.
468///
469/// Reference: pySigma collection.py deep_dict_update
470fn deep_merge(dest: Value, src: Value) -> crate::error::Result<Value> {
471    const MAX_DEPTH: usize = 64;
472
473    let (mut root_dest, root_src) = match (dest, src) {
474        (Value::Mapping(d), Value::Mapping(s)) => (d, s),
475        (_, src) => return Ok(src),
476    };
477
478    fn merge_level(
479        dest: &mut yaml_serde::Mapping,
480        src: yaml_serde::Mapping,
481        depth: usize,
482    ) -> crate::error::Result<()> {
483        if depth > MAX_DEPTH {
484            return Err(crate::error::SigmaParserError::MergeTooDeep(MAX_DEPTH));
485        }
486        for (k, v) in src {
487            if let Some(existing) = dest.remove(&k) {
488                match (existing, v) {
489                    (Value::Mapping(mut d), Value::Mapping(s)) => {
490                        merge_level(&mut d, s, depth + 1)?;
491                        dest.insert(k, Value::Mapping(d));
492                    }
493                    (_, src_val) => {
494                        dest.insert(k, src_val);
495                    }
496                }
497            } else {
498                dest.insert(k, v);
499            }
500        }
501        Ok(())
502    }
503
504    merge_level(&mut root_dest, root_src, 0)?;
505    Ok(Value::Mapping(root_dest))
506}