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