1use std::collections::{BTreeMap, BTreeSet};
18
19use rsigma_parser::{
20 CorrelationCondition, CorrelationRule, Detection, DetectionItem, Detections, FilterRule,
21 SigmaCollection, SigmaRule,
22};
23use serde::Serialize;
24
25use crate::pipeline::{Pipeline, apply_pipelines};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
29#[serde(rename_all = "lowercase")]
30pub enum FieldSource {
31 Detection,
33 Correlation,
35 Filter,
37 Metadata,
39}
40
41impl FieldSource {
42 pub fn as_str(self) -> &'static str {
44 match self {
45 FieldSource::Detection => "detection",
46 FieldSource::Correlation => "correlation",
47 FieldSource::Filter => "filter",
48 FieldSource::Metadata => "metadata",
49 }
50 }
51}
52
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
55pub struct FieldOrigin {
56 pub rule_titles: BTreeSet<String>,
58 pub sources: BTreeSet<FieldSource>,
61}
62
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
70pub struct RuleFieldSet {
71 fields: BTreeMap<String, FieldOrigin>,
72}
73
74impl RuleFieldSet {
75 pub fn collect(
86 collection: &SigmaCollection,
87 pipelines: &[Pipeline],
88 include_filters: bool,
89 ) -> Self {
90 let mut collector = Collector::default();
91
92 if pipelines.is_empty() {
93 for rule in &collection.rules {
94 collector.collect_rule(rule);
95 }
96 } else {
97 for rule in &collection.rules {
98 let mut transformed = rule.clone();
99 if apply_pipelines(pipelines, &mut transformed).is_err() {
100 collector.collect_rule(rule);
101 continue;
102 }
103 collector.collect_rule(&transformed);
104 }
105 }
106
107 for corr in &collection.correlations {
108 collector.collect_correlation(corr);
109 }
110
111 if include_filters {
112 for filter in &collection.filters {
113 collector.collect_filter(filter);
114 }
115 }
116
117 Self {
118 fields: collector.fields,
119 }
120 }
121
122 pub fn contains(&self, field: &str) -> bool {
124 self.fields.contains_key(field)
125 }
126
127 pub fn origin(&self, field: &str) -> Option<&FieldOrigin> {
129 self.fields.get(field)
130 }
131
132 pub fn iter(&self) -> impl Iterator<Item = (&str, &FieldOrigin)> {
134 self.fields.iter().map(|(k, v)| (k.as_str(), v))
135 }
136
137 pub fn names(&self) -> impl Iterator<Item = &str> {
139 self.fields.keys().map(String::as_str)
140 }
141
142 pub fn len(&self) -> usize {
144 self.fields.len()
145 }
146
147 pub fn is_empty(&self) -> bool {
149 self.fields.is_empty()
150 }
151
152 pub fn extend(&mut self, other: RuleFieldSet) {
154 for (field, origin) in other.fields {
155 let entry = self.fields.entry(field).or_default();
156 entry.rule_titles.extend(origin.rule_titles);
157 entry.sources.extend(origin.sources);
158 }
159 }
160}
161
162#[derive(Default)]
163struct Collector {
164 fields: BTreeMap<String, FieldOrigin>,
165}
166
167impl Collector {
168 fn add(&mut self, field: &str, rule_title: &str, source: FieldSource) {
169 let entry = self.fields.entry(field.to_string()).or_default();
170 entry.rule_titles.insert(rule_title.to_string());
171 entry.sources.insert(source);
172 }
173
174 fn collect_detection_items(
175 &mut self,
176 detection: &Detection,
177 rule_title: &str,
178 source: FieldSource,
179 ) {
180 match detection {
181 Detection::AllOf(items) => {
182 for item in items {
183 self.collect_item(item, rule_title, source);
184 }
185 }
186 Detection::AnyOf(subs) => {
187 for sub in subs {
188 self.collect_detection_items(sub, rule_title, source);
189 }
190 }
191 Detection::ArrayMatch { field, body, .. } => {
192 self.add(field, rule_title, source);
195 self.collect_detection_items(body, rule_title, source);
196 }
197 Detection::And(subs) => {
198 for sub in subs {
199 self.collect_detection_items(sub, rule_title, source);
200 }
201 }
202 Detection::Conditional { named, .. } => {
203 for sub in named.values() {
204 self.collect_detection_items(sub, rule_title, source);
205 }
206 }
207 Detection::Keywords(_) => {}
208 }
209 }
210
211 fn collect_item(&mut self, item: &DetectionItem, rule_title: &str, source: FieldSource) {
212 if let Some(ref name) = item.field.name {
213 self.add(name, rule_title, source);
214 }
215 }
216
217 fn collect_detections(
218 &mut self,
219 detections: &Detections,
220 rule_title: &str,
221 source: FieldSource,
222 ) {
223 for det in detections.named.values() {
224 self.collect_detection_items(det, rule_title, source);
225 }
226 }
227
228 fn collect_rule(&mut self, rule: &SigmaRule) {
229 self.collect_detections(&rule.detection, &rule.title, FieldSource::Detection);
230 for f in &rule.fields {
231 self.add(f, &rule.title, FieldSource::Metadata);
232 }
233 }
234
235 fn collect_correlation(&mut self, corr: &CorrelationRule) {
236 for f in &corr.group_by {
237 self.add(f, &corr.title, FieldSource::Correlation);
238 }
239 if let CorrelationCondition::Threshold {
240 field: Some(ref fields),
241 ..
242 } = corr.condition
243 {
244 for f in fields {
245 self.add(f, &corr.title, FieldSource::Correlation);
246 }
247 }
248 for alias in &corr.aliases {
249 for mapped_field in alias.mapping.values() {
250 self.add(mapped_field, &corr.title, FieldSource::Correlation);
251 }
252 }
253 for f in &corr.fields {
254 self.add(f, &corr.title, FieldSource::Metadata);
255 }
256 }
257
258 fn collect_filter(&mut self, filter: &FilterRule) {
259 self.collect_detections(&filter.detection, &filter.title, FieldSource::Filter);
260 for f in &filter.fields {
261 self.add(f, &filter.title, FieldSource::Metadata);
262 }
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use rsigma_parser::parse_sigma_yaml;
270
271 fn build(yaml: &str) -> SigmaCollection {
272 parse_sigma_yaml(yaml).expect("parse")
273 }
274
275 #[test]
276 fn collects_detection_fields() {
277 let collection = build(
278 r#"
279title: Test
280status: test
281logsource:
282 category: test
283detection:
284 selection:
285 CommandLine|contains: whoami
286 EventID: 1
287 condition: selection
288"#,
289 );
290 let set = RuleFieldSet::collect(&collection, &[], true);
291 assert!(set.contains("CommandLine"));
292 assert!(set.contains("EventID"));
293 assert!(
294 set.origin("CommandLine")
295 .unwrap()
296 .sources
297 .contains(&FieldSource::Detection)
298 );
299 }
300
301 #[test]
302 fn collects_correlation_group_by() {
303 let collection = build(
304 r#"
305title: Login
306id: login-rule
307logsource:
308 category: auth
309detection:
310 selection:
311 EventType: login
312 condition: selection
313---
314title: Many Logins
315correlation:
316 type: event_count
317 rules:
318 - login-rule
319 group-by:
320 - User
321 timespan: 60s
322 condition:
323 gte: 3
324"#,
325 );
326 let set = RuleFieldSet::collect(&collection, &[], true);
327 assert!(set.contains("EventType"));
328 assert!(set.contains("User"));
329 let user_origin = set.origin("User").unwrap();
330 assert!(user_origin.sources.contains(&FieldSource::Correlation));
331 }
332
333 #[test]
334 fn include_filters_toggle() {
335 let collection = build(
336 r#"
337title: Detection
338status: test
339logsource:
340 category: test
341detection:
342 selection:
343 DetField: x
344 condition: selection
345---
346title: Filter
347logsource:
348 category: test
349filter:
350 rules:
351 - non-existent
352 selection:
353 FilterField: y
354 condition: selection
355"#,
356 );
357 let with_filters = RuleFieldSet::collect(&collection, &[], true);
358 let without_filters = RuleFieldSet::collect(&collection, &[], false);
359 assert!(with_filters.contains("FilterField"));
360 assert!(!without_filters.contains("FilterField"));
361 assert!(with_filters.contains("DetField"));
362 assert!(without_filters.contains("DetField"));
363 }
364
365 #[test]
366 fn empty_collection_is_empty_set() {
367 let collection = SigmaCollection::default();
368 let set = RuleFieldSet::collect(&collection, &[], true);
369 assert!(set.is_empty());
370 assert_eq!(set.len(), 0);
371 }
372
373 #[test]
374 fn extend_unions_fields_and_provenance() {
375 let first = RuleFieldSet::collect(
376 &build(
377 "title: One\nid: one\nlogsource:\n category: test\ndetection:\n selection:\n Shared: a\n First: b\n condition: selection\n",
378 ),
379 &[],
380 true,
381 );
382 let second = RuleFieldSet::collect(
383 &build(
384 "title: Two\nid: two\nlogsource:\n category: test\ndetection:\n selection:\n Second: d\n condition: selection\nfields:\n - Shared\n",
385 ),
386 &[],
387 true,
388 );
389 let mut merged = first;
390 merged.extend(second);
391 assert!(merged.contains("First"));
392 assert!(merged.contains("Second"));
393 let shared = merged.origin("Shared").unwrap();
394 assert_eq!(
395 shared.rule_titles,
396 BTreeSet::from(["One".to_string(), "Two".to_string()])
397 );
398 assert_eq!(
399 shared.sources,
400 BTreeSet::from([FieldSource::Detection, FieldSource::Metadata])
401 );
402 }
403}