Skip to main content

rsigma_parser/ruleset/
select.rs

1//! Metadata selection of ruleset candidates.
2
3use std::collections::{HashMap, HashSet};
4
5use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
6
7use crate::ast::{Level, Status};
8
9use super::error::RulesetError;
10use super::source::{Candidate, CandidateDoc, DocumentKind};
11use super::spec::RuleSelector;
12
13/// A compiled selector. Globs are built once; exact keys are stored in sets.
14pub(crate) struct CompiledSelector {
15    ids: HashSet<String>,
16    names: HashSet<String>,
17    titles: Option<GlobSet>,
18    tags: Option<GlobSet>,
19    levels: HashSet<Level>,
20    statuses: HashSet<Status>,
21    kinds: HashSet<DocumentKind>,
22    paths: Option<GlobSet>,
23    logsource: Option<CompiledLogsource>,
24}
25
26struct CompiledLogsource {
27    product: HashSet<String>,
28    category: HashSet<String>,
29    service: HashSet<String>,
30}
31
32/// Candidate indices keyed by id and name, used for correlation references and
33/// logsource matching.
34pub(crate) struct RefIndex {
35    by_id: HashMap<String, Vec<usize>>,
36    by_name: HashMap<String, Vec<usize>>,
37    by_title: HashMap<String, Vec<usize>>,
38}
39
40impl RefIndex {
41    pub(crate) fn build(candidates: &[Candidate]) -> Self {
42        let mut by_id: HashMap<String, Vec<usize>> = HashMap::new();
43        let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
44        let mut by_title: HashMap<String, Vec<usize>> = HashMap::new();
45        for (index, candidate) in candidates.iter().enumerate() {
46            if let Some(id) = candidate.id() {
47                by_id.entry(id.to_string()).or_default().push(index);
48            }
49            if let Some(name) = candidate.name() {
50                by_name.entry(name.to_string()).or_default().push(index);
51            }
52            by_title
53                .entry(candidate.title().to_string())
54                .or_default()
55                .push(index);
56        }
57        Self {
58            by_id,
59            by_name,
60            by_title,
61        }
62    }
63
64    /// Resolve a correlation reference by exact id or name.
65    pub(crate) fn resolve(&self, key: &str) -> Vec<usize> {
66        let mut found = self.by_id.get(key).cloned().unwrap_or_default();
67        if let Some(by_name) = self.by_name.get(key) {
68            found.extend(by_name);
69        }
70        found.sort_unstable();
71        found.dedup();
72        found
73    }
74
75    /// Resolve a filter target by id, name, or (deprecated) title.
76    pub(crate) fn resolve_filter_target(&self, key: &str) -> Vec<usize> {
77        let mut found = self.resolve(key);
78        if let Some(by_title) = self.by_title.get(key) {
79            found.extend(by_title);
80        }
81        found.sort_unstable();
82        found.dedup();
83        found
84    }
85}
86
87/// Why a candidate was kept or dropped.
88#[derive(Debug, Clone, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum Decision {
91    /// Admitted by the include selector at this index, or by an empty include
92    /// list.
93    Included {
94        /// The matching include selector, or `None` for an empty include list.
95        selector: Option<usize>,
96    },
97    /// Rejected by the exclude selector at this index.
98    Excluded {
99        /// The matching exclude selector.
100        selector: usize,
101    },
102    /// Matched no include selector.
103    NotSelected,
104    /// Pulled in as a dependency of the correlation with this id, name, or
105    /// title.
106    PulledIn {
107        /// The correlation that referenced it.
108        by: String,
109    },
110    /// A correlation dropped for an unresolved reference, and why.
111    Dropped {
112        /// The unresolved reference and why it did not resolve.
113        reason: String,
114    },
115    /// A filter kept because it targets any rule or a kept detection.
116    FilterKept,
117    /// A filter whose targets are all gone.
118    FilterOrphaned,
119}
120
121impl Decision {
122    /// The snake_case label used in reports.
123    pub fn as_str(&self) -> &'static str {
124        match self {
125            Self::Included { .. } => "included",
126            Self::Excluded { .. } => "excluded",
127            Self::NotSelected => "not_selected",
128            Self::PulledIn { .. } => "pulled_in",
129            Self::Dropped { .. } => "dropped",
130            Self::FilterKept => "filter_kept",
131            Self::FilterOrphaned => "filter_orphaned",
132        }
133    }
134}
135
136pub(crate) fn compile_selector(selector: &RuleSelector) -> Result<CompiledSelector, RulesetError> {
137    let mut levels = HashSet::new();
138    for value in &selector.level {
139        levels.insert(
140            value
141                .parse::<Level>()
142                .map_err(|_| RulesetError::Selector(format!("unknown level '{value}'")))?,
143        );
144    }
145    let mut statuses = HashSet::new();
146    for value in &selector.status {
147        statuses.insert(
148            value
149                .parse::<Status>()
150                .map_err(|_| RulesetError::Selector(format!("unknown status '{value}'")))?,
151        );
152    }
153    let mut kinds = HashSet::new();
154    for value in &selector.kind {
155        kinds.insert(match value.as_str() {
156            "detection" => DocumentKind::Detection,
157            "correlation" => DocumentKind::Correlation,
158            "filter" => DocumentKind::Filter,
159            other => {
160                return Err(RulesetError::Selector(format!("unknown kind '{other}'")));
161            }
162        });
163    }
164
165    let titles = build_glob_set(&selector.title, true, false)?;
166    let tags = build_glob_set(&selector.tags, true, false)?;
167    let paths = build_glob_set(&selector.path, false, true)?;
168    let logsource = selector
169        .logsource
170        .as_ref()
171        .map(|logsource| CompiledLogsource {
172            product: logsource
173                .product
174                .iter()
175                .map(|s| s.to_ascii_lowercase())
176                .collect(),
177            category: logsource
178                .category
179                .iter()
180                .map(|s| s.to_ascii_lowercase())
181                .collect(),
182            service: logsource
183                .service
184                .iter()
185                .map(|s| s.to_ascii_lowercase())
186                .collect(),
187        });
188
189    Ok(CompiledSelector {
190        ids: selector.id.iter().map(|s| s.to_ascii_lowercase()).collect(),
191        names: selector.name.iter().cloned().collect(),
192        titles,
193        tags,
194        levels,
195        statuses,
196        kinds,
197        paths,
198        logsource,
199    })
200}
201
202fn build_glob_set(
203    patterns: &[String],
204    case_insensitive: bool,
205    literal_separator: bool,
206) -> Result<Option<GlobSet>, RulesetError> {
207    if patterns.is_empty() {
208        return Ok(None);
209    }
210    let mut builder = GlobSetBuilder::new();
211    for pattern in patterns {
212        let glob = GlobBuilder::new(pattern)
213            .case_insensitive(case_insensitive)
214            .literal_separator(literal_separator)
215            .build()
216            .map_err(|e| RulesetError::Selector(format!("invalid glob '{pattern}': {e}")))?;
217        builder.add(glob);
218    }
219    builder
220        .build()
221        .map(Some)
222        .map_err(|e| RulesetError::Selector(format!("invalid glob set: {e}")))
223}
224
225impl CompiledSelector {
226    /// True when every key that is set matches the candidate.
227    pub(crate) fn matches(
228        &self,
229        candidate_index: usize,
230        candidates: &[Candidate],
231        refs: &RefIndex,
232    ) -> bool {
233        let candidate = &candidates[candidate_index];
234        if !self.ids.is_empty() {
235            match candidate.id() {
236                Some(id) if self.ids.contains(&id.to_ascii_lowercase()) => {}
237                _ => return false,
238            }
239        }
240        if !self.names.is_empty() {
241            match candidate.name() {
242                Some(name) if self.names.contains(name) => {}
243                _ => return false,
244            }
245        }
246        if let Some(titles) = &self.titles
247            && !titles.is_match(candidate.title())
248        {
249            return false;
250        }
251        if let Some(tags) = &self.tags
252            && !candidate.tags().iter().any(|tag| tags.is_match(tag))
253        {
254            return false;
255        }
256        if !self.levels.is_empty() {
257            match candidate.level() {
258                Some(level) if self.levels.contains(&level) => {}
259                _ => return false,
260            }
261        }
262        if !self.statuses.is_empty() {
263            match candidate.status() {
264                Some(status) if self.statuses.contains(&status) => {}
265                _ => return false,
266            }
267        }
268        if !self.kinds.is_empty() && !self.kinds.contains(&candidate.kind()) {
269            return false;
270        }
271        if let Some(paths) = &self.paths
272            && !paths.is_match(&candidate.origin.file)
273        {
274            return false;
275        }
276        if let Some(logsource) = &self.logsource
277            && !logsource_matches(candidate_index, candidates, refs, logsource)
278        {
279            return false;
280        }
281        true
282    }
283}
284
285/// Whether a candidate's logsource matches; a correlation matches when any
286/// document reachable through its references does. Walks with an explicit
287/// stack, since a crafted ruleset can chain thousands of correlations.
288fn logsource_matches(
289    index: usize,
290    candidates: &[Candidate],
291    refs: &RefIndex,
292    selector: &CompiledLogsource,
293) -> bool {
294    let mut visited = HashSet::new();
295    let mut stack = vec![index];
296    while let Some(index) = stack.pop() {
297        if !visited.insert(index) {
298            continue;
299        }
300        let matched = match &candidates[index].doc {
301            CandidateDoc::Detection(rule) => logsource_fields_match(&rule.logsource, selector),
302            CandidateDoc::Filter(rule) => rule
303                .logsource
304                .as_ref()
305                .is_some_and(|logsource| logsource_fields_match(logsource, selector)),
306            CandidateDoc::Correlation(rule) => {
307                for reference in &rule.rules {
308                    stack.extend(refs.resolve(reference));
309                }
310                false
311            }
312        };
313        if matched {
314            return true;
315        }
316    }
317    false
318}
319
320fn logsource_fields_match(logsource: &crate::ast::LogSource, selector: &CompiledLogsource) -> bool {
321    let matches = |set: &HashSet<String>, value: &Option<String>| {
322        set.is_empty()
323            || value
324                .as_ref()
325                .is_some_and(|v| set.contains(&v.to_ascii_lowercase()))
326    };
327    matches(&selector.product, &logsource.product)
328        && matches(&selector.category, &logsource.category)
329        && matches(&selector.service, &logsource.service)
330}
331
332/// Decide every detection and correlation candidate. Filters are marked
333/// `Excluded` when an exclude selector matches and `NotSelected` otherwise;
334/// dependency closure decides their fate.
335pub(crate) fn decide(
336    candidates: &[Candidate],
337    spec: &super::spec::RulesetSpec,
338) -> Result<Vec<Decision>, RulesetError> {
339    let include: Vec<CompiledSelector> = spec
340        .include
341        .iter()
342        .map(compile_selector)
343        .collect::<Result<_, _>>()?;
344    let exclude: Vec<CompiledSelector> = spec
345        .exclude
346        .iter()
347        .map(compile_selector)
348        .collect::<Result<_, _>>()?;
349    let refs = RefIndex::build(candidates);
350
351    let mut decisions = Vec::with_capacity(candidates.len());
352    for index in 0..candidates.len() {
353        if candidates[index].kind() == DocumentKind::Filter {
354            let excluded = exclude
355                .iter()
356                .position(|selector| selector.matches(index, candidates, &refs));
357            decisions.push(match excluded {
358                Some(selector) => Decision::Excluded { selector },
359                None => Decision::NotSelected,
360            });
361            continue;
362        }
363
364        if let Some(selector) = exclude
365            .iter()
366            .position(|selector| selector.matches(index, candidates, &refs))
367        {
368            decisions.push(Decision::Excluded { selector });
369            continue;
370        }
371
372        if include.is_empty() {
373            decisions.push(Decision::Included { selector: None });
374            continue;
375        }
376
377        match include
378            .iter()
379            .position(|selector| selector.matches(index, candidates, &refs))
380        {
381            Some(selector) => decisions.push(Decision::Included {
382                selector: Some(selector),
383            }),
384            None => decisions.push(Decision::NotSelected),
385        }
386    }
387    Ok(decisions)
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use crate::ruleset::source::RuleOrigin;
394    use crate::ruleset::spec::{LogsourceSelector, RuleSelector, RulesetSpec};
395
396    fn candidate(yaml: &str, file: &str) -> Candidate {
397        let collection = crate::parse_sigma_yaml(yaml).unwrap();
398        let doc = if let Some(rule) = collection.rules.into_iter().next() {
399            CandidateDoc::Detection(rule)
400        } else if let Some(rule) = collection.correlations.into_iter().next() {
401            CandidateDoc::Correlation(rule)
402        } else {
403            CandidateDoc::Filter(collection.filters.into_iter().next().unwrap())
404        };
405        Candidate {
406            doc,
407            origin: RuleOrigin {
408                source: 0,
409                root: std::path::PathBuf::from("."),
410                file: std::path::PathBuf::from(file),
411                ordinal: 0,
412            },
413        }
414    }
415
416    fn detection(id: &str, title: &str, tags: &[&str], level: &str, file: &str) -> Candidate {
417        let tags = tags
418            .iter()
419            .map(|tag| format!("        - {tag}\n"))
420            .collect::<String>();
421        candidate(
422            &format!(
423                "title: {title}\nid: {id}\nstatus: experimental\nlogsource:\n    product: windows\n    category: process_creation\ndetection:\n    selection:\n        Field: value\n    condition: selection\ntags:\n{tags}level: {level}\n"
424            ),
425            file,
426        )
427    }
428
429    fn select(spec: RulesetSpec, candidates: &[Candidate]) -> Vec<Decision> {
430        decide(candidates, &spec).unwrap()
431    }
432
433    fn spec(include: Vec<RuleSelector>, exclude: Vec<RuleSelector>) -> RulesetSpec {
434        RulesetSpec {
435            sources: vec![std::path::PathBuf::from("rules")],
436            include,
437            exclude,
438            ..Default::default()
439        }
440    }
441
442    #[test]
443    fn or_across_selectors_and_and_across_keys() {
444        let candidates = vec![
445            detection("a", "A", &["attack.t1059.001"], "high", "a.yml"),
446            detection("b", "B", &["attack.t1059.001"], "low", "b.yml"),
447            detection("c", "C", &["attack.t1071"], "high", "c.yml"),
448        ];
449        let include = vec![
450            RuleSelector {
451                tags: vec!["attack.t1059*".into()],
452                level: vec!["high".into()],
453                ..Default::default()
454            },
455            RuleSelector {
456                id: vec!["C".into()],
457                ..Default::default()
458            },
459        ];
460        let decisions = select(spec(include, vec![]), &candidates);
461        assert_eq!(decisions[0], Decision::Included { selector: Some(0) });
462        assert_eq!(decisions[1], Decision::NotSelected);
463        assert_eq!(decisions[2], Decision::Included { selector: Some(1) });
464    }
465
466    #[test]
467    fn empty_include_admits_all_and_exclude_wins() {
468        let candidates = vec![
469            detection("a", "A", &[], "high", "a.yml"),
470            detection("b", "B", &[], "low", "b.yml"),
471        ];
472        let exclude = vec![RuleSelector {
473            id: vec!["A".into()],
474            ..Default::default()
475        }];
476        let decisions = select(spec(vec![], exclude), &candidates);
477        assert_eq!(decisions[0], Decision::Excluded { selector: 0 });
478        assert_eq!(decisions[1], Decision::Included { selector: None });
479    }
480
481    #[test]
482    fn path_globs_respect_separators() {
483        let candidates = vec![detection("a", "A", &[], "high", "dir/a.yml")];
484        let include = vec![RuleSelector {
485            path: vec!["*.yml".into()],
486            ..Default::default()
487        }];
488        let decisions = select(spec(include, vec![]), &candidates);
489        assert_eq!(decisions[0], Decision::NotSelected);
490
491        let include = vec![RuleSelector {
492            path: vec!["**/*.yml".into()],
493            ..Default::default()
494        }];
495        let decisions = select(spec(include, vec![]), &candidates);
496        assert_eq!(decisions[0], Decision::Included { selector: Some(0) });
497    }
498
499    #[test]
500    fn tag_glob_matches_nested_tag() {
501        let candidates = vec![detection("a", "A", &["attack.t1059.001"], "high", "a.yml")];
502        let include = vec![RuleSelector {
503            tags: vec!["attack.t1059*".into()],
504            ..Default::default()
505        }];
506        let decisions = select(spec(include, vec![]), &candidates);
507        assert_eq!(decisions[0], Decision::Included { selector: Some(0) });
508    }
509
510    #[test]
511    fn correlation_logsource_matches_through_a_chain() {
512        let candidates = vec![
513            detection("base", "Base", &[], "high", "base.yml"),
514            candidate(
515                "title: Chain\nid: chain\ncorrelation:\n    type: event_count\n    rules:\n        - base\n    timespan: 5m\n    condition:\n        gte: 2\n",
516                "chain.yml",
517            ),
518            candidate(
519                "title: Parent\nid: parent\ncorrelation:\n    type: event_count\n    rules:\n        - chain\n    timespan: 5m\n    condition:\n        gte: 2\n",
520                "parent.yml",
521            ),
522        ];
523        let include = vec![RuleSelector {
524            logsource: Some(LogsourceSelector {
525                product: vec!["WINDOWS".into()],
526                ..Default::default()
527            }),
528            ..Default::default()
529        }];
530        let decisions = select(spec(include, vec![]), &candidates);
531        assert_eq!(decisions[2], Decision::Included { selector: Some(0) });
532    }
533
534    #[test]
535    fn a_deep_correlation_chain_does_not_exhaust_the_stack() {
536        const DEPTH: usize = 2_000;
537        let mut candidates = vec![detection("c0", "Base", &[], "high", "base.yml")];
538        for depth in 1..=DEPTH {
539            candidates.push(candidate(
540                &format!(
541                    "title: C{depth}\nid: c{depth}\ncorrelation:\n    type: event_count\n    rules:\n        - c{}\n    timespan: 5m\n    condition:\n        gte: 2\n",
542                    depth - 1
543                ),
544                "chain.yml",
545            ));
546        }
547        let include = vec![RuleSelector {
548            logsource: Some(LogsourceSelector {
549                product: vec!["windows".into()],
550                ..Default::default()
551            }),
552            ..Default::default()
553        }];
554        let decisions = std::thread::Builder::new()
555            .stack_size(64 * 1024)
556            .spawn(move || select(spec(include, vec![]), &candidates))
557            .unwrap()
558            .join()
559            .unwrap();
560        assert_eq!(decisions[DEPTH], Decision::Included { selector: Some(0) });
561    }
562
563    #[test]
564    fn level_and_status_are_exact_and_case_sensitive_enums() {
565        let candidates = vec![detection("a", "A", &[], "high", "a.yml")];
566        let include = vec![RuleSelector {
567            level: vec!["HIGH".into()],
568            ..Default::default()
569        }];
570        let error = decide(&candidates, &spec(include, vec![])).unwrap_err();
571        assert!(error.to_string().contains("'HIGH'"), "{error}");
572
573        let include = vec![RuleSelector {
574            status: vec!["Stable".into()],
575            ..Default::default()
576        }];
577        let error = decide(&candidates, &spec(include, vec![])).unwrap_err();
578        assert!(error.to_string().contains("'Stable'"), "{error}");
579    }
580
581    #[test]
582    fn filter_in_include_is_rejected_before_selection() {
583        let candidates = vec![detection("a", "A", &[], "high", "a.yml")];
584        let include = vec![RuleSelector {
585            kind: vec!["filter".into()],
586            ..Default::default()
587        }];
588        let loaded = crate::ruleset::LoadedSources {
589            candidates,
590            ..Default::default()
591        };
592        let error = crate::ruleset::resolve_loaded(
593            "test",
594            &spec(include, vec![]),
595            loaded,
596            &crate::ruleset::InlineOnlyOverlayLoader,
597        )
598        .unwrap_err();
599        assert!(
600            matches!(error, crate::ruleset::RulesetError::InvalidSpec(_)),
601            "{error}"
602        );
603    }
604}