Skip to main content

rsigma_parser/ruleset/
mod.rs

1//! Named rulesets: curated, overlaid rule collections resolved in memory.
2//!
3//! A ruleset is declared under `rulesets:` in `rsigma.yaml` and names its
4//! sources, include and exclude selectors, dependency policy, overlays, and
5//! pipelines. [`resolve_ruleset`] validates the spec, loads every source with
6//! per-document provenance, and returns a [`SigmaCollection`] ready for
7//! evaluation or emission.
8//!
9//! ```rust
10//! use rsigma_parser::ruleset::{resolve_ruleset, ResolveOptions, RulesetSpec};
11//!
12//! let dir = tempfile::tempdir().unwrap();
13//! std::fs::write(
14//!     dir.path().join("rule.yml"),
15//!     "title: Whoami\nlogsource:\n    product: windows\ndetection:\n    selection:\n        CommandLine|contains: whoami\n    condition: selection\n",
16//! )
17//! .unwrap();
18//!
19//! let spec: RulesetSpec = yaml_serde::from_str(&format!(
20//!     "sources:\n    - {}\n",
21//!     dir.path().display()
22//! ))
23//! .unwrap();
24//! let resolved = resolve_ruleset("local", &spec, &ResolveOptions::default()).unwrap();
25//! assert_eq!(resolved.collection.rules.len(), 1);
26//! ```
27//!
28//! [`SigmaCollection`]: crate::ast::SigmaCollection
29
30mod closure;
31mod error;
32mod overlay;
33mod select;
34mod source;
35mod spec;
36
37pub use error::RulesetError;
38pub use overlay::{
39    AppliedOverlay, FsOverlayLoader, InlineOnlyOverlayLoader, OverlayLoader, OverlayOrigin,
40};
41pub use select::Decision;
42pub use source::{
43    Candidate, CandidateDoc, DocumentKind, LoadedSources, ResolveOptions, RuleOrigin, SourceFile,
44    load_sources,
45};
46pub use spec::{
47    DependencyPolicy, LogsourceSelector, OverlayEntry, OverlayPatch, RuleSelector, RulesetSpec,
48    StaleOverlayPolicy, validate_ruleset_name, validate_spec,
49};
50
51use crate::ast::SigmaCollection;
52
53/// Resolve a ruleset from its spec, loading sources from disk.
54pub fn resolve_ruleset(
55    name: &str,
56    spec: &RulesetSpec,
57    opts: &ResolveOptions,
58) -> Result<ResolvedRuleset, RulesetError> {
59    let problems = validate_spec(name, spec);
60    if !problems.is_empty() {
61        return Err(RulesetError::InvalidSpec(problems));
62    }
63    let loader = FsOverlayLoader::new(opts.confine_to.clone());
64    let loaded = load_sources(spec, opts).map_err(|e| e.named(name))?;
65    resolve_validated(name, spec, loaded, &loader)
66}
67
68/// A resolved ruleset: the kept collection plus per-document decisions.
69#[derive(Debug, Clone)]
70pub struct ResolvedRuleset {
71    /// The ruleset name.
72    pub name: String,
73    /// The kept documents, with overlays applied.
74    pub collection: SigmaCollection,
75    /// One entry per candidate, kept or not, in candidate order.
76    pub entries: Vec<RuleEntry>,
77    /// Source files read.
78    pub files: Vec<SourceFile>,
79    /// Overlay files read.
80    pub overlay_files: Vec<SourceFile>,
81    /// Dropped correlations and skipped stale overlays.
82    pub warnings: Vec<String>,
83}
84
85/// Why one candidate is in or out of the resolved collection.
86#[derive(Debug, Clone)]
87pub struct RuleEntry {
88    /// The document kind.
89    pub kind: DocumentKind,
90    /// The document `id`.
91    pub id: Option<String>,
92    /// The document `name`.
93    pub name: Option<String>,
94    /// The document title.
95    pub title: String,
96    /// Where the document was read from.
97    pub origin: RuleOrigin,
98    /// Whether and why the document is kept.
99    pub decision: Decision,
100    /// Overlays applied to the document, in order.
101    pub overlays: Vec<AppliedOverlay>,
102}
103
104/// Resolve already-loaded sources into a collection, applying metadata
105/// overlays through `loader`. The spec is validated first, as in
106/// [`resolve_ruleset`].
107///
108/// ```rust
109/// use std::path::PathBuf;
110///
111/// use rsigma_parser::parse_sigma_yaml;
112/// use rsigma_parser::ruleset::{
113///     Candidate, CandidateDoc, InlineOnlyOverlayLoader, LoadedSources, RuleOrigin, RulesetSpec,
114///     resolve_loaded,
115/// };
116///
117/// let yaml = r#"
118/// title: Whoami
119/// id: 11111111-2222-3333-4444-555555555555
120/// logsource:
121///     product: windows
122/// detection:
123///     selection:
124///         CommandLine|contains: whoami
125///     condition: selection
126/// "#;
127/// let rule = parse_sigma_yaml(yaml).unwrap().rules.remove(0);
128/// let loaded = LoadedSources {
129///     candidates: vec![Candidate {
130///         doc: CandidateDoc::Detection(rule),
131///         origin: RuleOrigin {
132///             source: 0,
133///             root: PathBuf::from("."),
134///             file: PathBuf::from("rule.yml"),
135///             ordinal: 0,
136///         },
137///     }],
138///     ..Default::default()
139/// };
140/// let spec = RulesetSpec {
141///     sources: vec![PathBuf::from(".")],
142///     ..Default::default()
143/// };
144/// let resolved = resolve_loaded("example", &spec, loaded, &InlineOnlyOverlayLoader).unwrap();
145/// assert_eq!(resolved.collection.rules.len(), 1);
146/// ```
147pub fn resolve_loaded(
148    name: &str,
149    spec: &RulesetSpec,
150    loaded: LoadedSources,
151    loader: &dyn OverlayLoader,
152) -> Result<ResolvedRuleset, RulesetError> {
153    let problems = validate_spec(name, spec);
154    if !problems.is_empty() {
155        return Err(RulesetError::InvalidSpec(problems));
156    }
157    resolve_validated(name, spec, loaded, loader)
158}
159
160fn resolve_validated(
161    name: &str,
162    spec: &RulesetSpec,
163    loaded: LoadedSources,
164    loader: &dyn OverlayLoader,
165) -> Result<ResolvedRuleset, RulesetError> {
166    let closure = closure::close(name, spec, &loaded.candidates)?;
167    let mut candidates = loaded.candidates;
168    let expanded = overlay::expand_overlays(name, spec, loader)?;
169    let (applied, overlay_warnings) =
170        overlay::apply_overlays(name, spec, &mut candidates, &closure.decisions, expanded)?;
171
172    let entries: Vec<RuleEntry> = candidates
173        .iter()
174        .zip(&closure.decisions)
175        .enumerate()
176        .map(|(index, (candidate, decision))| RuleEntry {
177            kind: candidate.kind(),
178            id: candidate.id().map(str::to_string),
179            name: candidate.name().map(str::to_string),
180            title: candidate.title().to_string(),
181            origin: candidate.origin.clone(),
182            decision: decision.clone(),
183            overlays: applied[index].clone(),
184        })
185        .collect();
186
187    let mut collection = SigmaCollection::new();
188    collection.diagnostics = loaded.diagnostics;
189    for (candidate, decision) in candidates.into_iter().zip(closure.decisions) {
190        if !closure::is_kept(&decision) {
191            continue;
192        }
193        match candidate.doc {
194            CandidateDoc::Detection(rule) => collection.rules.push(rule),
195            CandidateDoc::Correlation(rule) => collection.correlations.push(rule),
196            CandidateDoc::Filter(rule) => collection.filters.push(rule),
197        }
198    }
199    let mut warnings = closure.warnings;
200    warnings.extend(overlay_warnings);
201    Ok(ResolvedRuleset {
202        name: name.to_string(),
203        collection,
204        entries,
205        files: loaded.files,
206        overlay_files: loader.files(),
207        warnings,
208    })
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::ast::SigmaRule;
215
216    fn rule(id: &str) -> SigmaRule {
217        crate::parse_sigma_yaml(&format!(
218            "title: Rule {id}\nid: {id}\nlogsource:\n    product: linux\ndetection:\n    selection:\n        Field: value\n    condition: selection\n"
219        ))
220        .unwrap()
221        .rules
222        .remove(0)
223    }
224
225    #[test]
226    fn resolve_loaded_keeps_every_candidate() {
227        let loaded = LoadedSources {
228            candidates: vec![Candidate {
229                doc: CandidateDoc::Detection(rule("a")),
230                origin: RuleOrigin {
231                    source: 0,
232                    root: std::path::PathBuf::from("."),
233                    file: std::path::PathBuf::from("a.yml"),
234                    ordinal: 0,
235                },
236            }],
237            ..Default::default()
238        };
239        let spec = RulesetSpec {
240            sources: vec![std::path::PathBuf::from(".")],
241            ..Default::default()
242        };
243        let resolved = resolve_loaded("test", &spec, loaded, &InlineOnlyOverlayLoader).unwrap();
244        assert_eq!(resolved.collection.rules.len(), 1);
245        assert_eq!(resolved.name, "test");
246    }
247}