rsigma 0.12.0

CLI for parsing, validating, linting and evaluating Sigma detection rules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use clap::Args;
use rsigma_eval::{Pipeline, apply_pipelines};
use rsigma_parser::{
    CorrelationCondition, CorrelationRule, Detection, DetectionItem, Detections, FilterRule,
    SigmaCollection, SigmaRule,
};
use serde::Serialize;

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Arguments for `rsigma rule fields` (and the deprecated `rsigma fields`).
#[derive(Args, Debug)]
pub(crate) struct FieldsArgs {
    /// Path to a Sigma rule file or directory of rules
    #[arg(short, long)]
    pub rules: PathBuf,

    /// Processing pipeline(s) to apply (repeatable). Accepts builtin names (ecs_windows, sysmon) or YAML file paths.
    /// When provided, fields are shown after pipeline transformations.
    #[arg(short = 'p', long = "pipeline")]
    pub pipelines: Vec<PathBuf>,

    /// Exclude fields from filter rules
    #[arg(long)]
    pub no_filters: bool,

    /// Output as JSON instead of a table
    #[arg(long)]
    pub json: bool,
}

pub(crate) fn cmd_fields(args: FieldsArgs) {
    let FieldsArgs {
        rules: path,
        pipelines: pipeline_paths,
        no_filters,
        json,
    } = args;
    let collection = crate::load_collection(&path);
    let pipelines = crate::load_pipelines(&pipeline_paths);

    if pipelines.iter().any(|p| p.is_dynamic()) {
        eprintln!(
            "  note: dynamic sources are not resolved by `rsigma rule fields`. \
             Use `rsigma pipeline resolve` to inspect sources or `rsigma engine daemon` to evaluate \
             events with dynamic pipelines."
        );
    }

    let report = build_report(&collection, &pipelines, no_filters);

    if json {
        crate::print_json(&report, true);
    } else {
        print_table(&report);
    }
}

// ---------------------------------------------------------------------------
// Report types
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
struct FieldsReport {
    summary: Summary,
    fields: Vec<FieldEntry>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pipeline_mappings: Vec<PipelineMapping>,
}

#[derive(Debug, Serialize)]
struct Summary {
    total_rules: usize,
    total_correlations: usize,
    total_filters: usize,
    unique_fields: usize,
    pipelines_applied: usize,
}

#[derive(Debug, Serialize)]
struct FieldEntry {
    field: String,
    rule_count: usize,
    sources: Vec<String>,
}

#[derive(Debug, Serialize)]
struct PipelineMapping {
    original: String,
    mapped_to: Vec<String>,
    pipeline: String,
}

// ---------------------------------------------------------------------------
// Field collection
// ---------------------------------------------------------------------------

/// Tracks where a field was seen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum FieldSource {
    Detection,
    Correlation,
    Filter,
    Metadata,
}

impl FieldSource {
    fn as_str(self) -> &'static str {
        match self {
            FieldSource::Detection => "detection",
            FieldSource::Correlation => "correlation",
            FieldSource::Filter => "filter",
            FieldSource::Metadata => "metadata",
        }
    }
}

struct FieldCollector {
    /// field_name -> (set of rule titles that reference it, set of source types)
    fields: BTreeMap<String, (BTreeSet<String>, BTreeSet<FieldSource>)>,
}

impl FieldCollector {
    fn new() -> Self {
        Self {
            fields: BTreeMap::new(),
        }
    }

    fn add(&mut self, field: &str, rule_title: &str, source: FieldSource) {
        let entry = self
            .fields
            .entry(field.to_string())
            .or_insert_with(|| (BTreeSet::new(), BTreeSet::new()));
        entry.0.insert(rule_title.to_string());
        entry.1.insert(source);
    }

    fn collect_detection_items(
        &mut self,
        detection: &Detection,
        rule_title: &str,
        source: FieldSource,
    ) {
        match detection {
            Detection::AllOf(items) => {
                for item in items {
                    self.collect_item(item, rule_title, source);
                }
            }
            Detection::AnyOf(subs) => {
                for sub in subs {
                    self.collect_detection_items(sub, rule_title, source);
                }
            }
            Detection::Keywords(_) => {}
        }
    }

    fn collect_item(&mut self, item: &DetectionItem, rule_title: &str, source: FieldSource) {
        if let Some(ref name) = item.field.name {
            self.add(name, rule_title, source);
        }
    }

    fn collect_detections(
        &mut self,
        detections: &Detections,
        rule_title: &str,
        source: FieldSource,
    ) {
        for det in detections.named.values() {
            self.collect_detection_items(det, rule_title, source);
        }
    }

    fn collect_rule(&mut self, rule: &SigmaRule) {
        self.collect_detections(&rule.detection, &rule.title, FieldSource::Detection);
        for f in &rule.fields {
            self.add(f, &rule.title, FieldSource::Metadata);
        }
    }

    fn collect_correlation(&mut self, corr: &CorrelationRule) {
        for f in &corr.group_by {
            self.add(f, &corr.title, FieldSource::Correlation);
        }
        if let CorrelationCondition::Threshold {
            field: Some(ref fields),
            ..
        } = corr.condition
        {
            for f in fields {
                self.add(f, &corr.title, FieldSource::Correlation);
            }
        }
        for alias in &corr.aliases {
            for mapped_field in alias.mapping.values() {
                self.add(mapped_field, &corr.title, FieldSource::Correlation);
            }
        }
        for f in &corr.fields {
            self.add(f, &corr.title, FieldSource::Metadata);
        }
    }

    fn collect_filter(&mut self, filter: &FilterRule) {
        self.collect_detections(&filter.detection, &filter.title, FieldSource::Filter);
        for f in &filter.fields {
            self.add(f, &filter.title, FieldSource::Metadata);
        }
    }
}

// ---------------------------------------------------------------------------
// Pipeline mapping extraction
// ---------------------------------------------------------------------------

fn extract_pipeline_mappings(pipelines: &[Pipeline]) -> Vec<PipelineMapping> {
    use rsigma_eval::pipeline::transformations::Transformation;

    let mut mappings = Vec::new();
    for pipeline in pipelines {
        for item in &pipeline.transformations {
            match &item.transformation {
                Transformation::FieldNameMapping { mapping } => {
                    for (from, to) in mapping {
                        mappings.push(PipelineMapping {
                            original: from.clone(),
                            mapped_to: to.clone(),
                            pipeline: pipeline.name.clone(),
                        });
                    }
                }
                Transformation::FieldNamePrefixMapping { mapping } => {
                    for (prefix, replacement) in mapping {
                        mappings.push(PipelineMapping {
                            original: format!("{prefix}*"),
                            mapped_to: vec![format!("{replacement}*")],
                            pipeline: pipeline.name.clone(),
                        });
                    }
                }
                Transformation::FieldNamePrefix { prefix } => {
                    mappings.push(PipelineMapping {
                        original: "*".to_string(),
                        mapped_to: vec![format!("{prefix}*")],
                        pipeline: pipeline.name.clone(),
                    });
                }
                Transformation::FieldNameSuffix { suffix } => {
                    mappings.push(PipelineMapping {
                        original: "*".to_string(),
                        mapped_to: vec![format!("*{suffix}")],
                        pipeline: pipeline.name.clone(),
                    });
                }
                Transformation::FieldNameTransform { mapping, .. } => {
                    for (from, to) in mapping {
                        mappings.push(PipelineMapping {
                            original: from.clone(),
                            mapped_to: vec![to.clone()],
                            pipeline: pipeline.name.clone(),
                        });
                    }
                }
                _ => {}
            }
        }
    }
    mappings
}

// ---------------------------------------------------------------------------
// Report building
// ---------------------------------------------------------------------------

fn build_report(
    collection: &SigmaCollection,
    pipelines: &[Pipeline],
    no_filters: bool,
) -> FieldsReport {
    let mut collector = FieldCollector::new();

    if pipelines.is_empty() {
        for rule in &collection.rules {
            collector.collect_rule(rule);
        }
        for corr in &collection.correlations {
            collector.collect_correlation(corr);
        }
    } else {
        for rule in &collection.rules {
            let mut transformed = rule.clone();
            if let Err(e) = apply_pipelines(pipelines, &mut transformed) {
                eprintln!("Warning: pipeline error for '{}': {e}", rule.title);
                collector.collect_rule(rule);
                continue;
            }
            collector.collect_rule(&transformed);
        }
        for corr in &collection.correlations {
            collector.collect_correlation(corr);
        }
    }

    if !no_filters {
        for filter in &collection.filters {
            collector.collect_filter(filter);
        }
    }

    let pipeline_mappings = extract_pipeline_mappings(pipelines);

    let fields: Vec<FieldEntry> = collector
        .fields
        .into_iter()
        .map(|(name, (rules, sources))| FieldEntry {
            field: name,
            rule_count: rules.len(),
            sources: sources.iter().map(|s| s.as_str().to_string()).collect(),
        })
        .collect();

    let unique_fields = fields.len();

    FieldsReport {
        summary: Summary {
            total_rules: collection.rules.len(),
            total_correlations: collection.correlations.len(),
            total_filters: collection.filters.len(),
            unique_fields,
            pipelines_applied: pipelines.len(),
        },
        fields,
        pipeline_mappings,
    }
}

// ---------------------------------------------------------------------------
// Table output
// ---------------------------------------------------------------------------

fn print_table(report: &FieldsReport) {
    let s = &report.summary;
    eprintln!(
        "Rules: {} detection, {} correlation, {} filter | Pipelines: {} | Unique fields: {}",
        s.total_rules, s.total_correlations, s.total_filters, s.pipelines_applied, s.unique_fields
    );

    if report.fields.is_empty() {
        eprintln!("No fields found.");
        return;
    }

    let max_field = report
        .fields
        .iter()
        .map(|f| f.field.len())
        .max()
        .unwrap_or(5)
        .max(5);
    let max_sources = report
        .fields
        .iter()
        .map(|f| f.sources.join(", ").len())
        .max()
        .unwrap_or(7)
        .max(7);

    eprintln!();
    println!(
        "{:<width_f$}  {:>5}  {:<width_s$}",
        "FIELD",
        "RULES",
        "SOURCES",
        width_f = max_field,
        width_s = max_sources,
    );
    println!(
        "{:<width_f$}  {:>5}  {:<width_s$}",
        "-".repeat(max_field),
        "-----",
        "-".repeat(max_sources),
        width_f = max_field,
        width_s = max_sources,
    );

    for entry in &report.fields {
        println!(
            "{:<width_f$}  {:>5}  {:<width_s$}",
            entry.field,
            entry.rule_count,
            entry.sources.join(", "),
            width_f = max_field,
            width_s = max_sources,
        );
    }

    if !report.pipeline_mappings.is_empty() {
        eprintln!();
        eprintln!("Pipeline field mappings:");
        for m in &report.pipeline_mappings {
            eprintln!(
                "  {} -> {} ({})",
                m.original,
                m.mapped_to.join(" | "),
                m.pipeline
            );
        }
    }
}