rsigma-parser 0.12.0

Parser for Sigma detection rules, correlations, and filters
Documentation
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
use yaml_serde::Value;

use super::super::{
    Fix, FixDisposition, FixPatch, LintRule, LintWarning, Severity, closest_match, err, info, key,
    safe_fix, warning,
};

/// Valid status values.
const VALID_STATUSES: &[&str] = &[
    "stable",
    "test",
    "experimental",
    "deprecated",
    "unsupported",
];

/// Valid level values.
const VALID_LEVELS: &[&str] = &["informational", "low", "medium", "high", "critical"];

/// Validate a date string matches YYYY-MM-DD with correct day-of-month.
fn is_valid_date(s: &str) -> bool {
    if s.len() != 10 {
        return false;
    }
    let bytes = s.as_bytes();
    if bytes[4] != b'-' || bytes[7] != b'-' {
        return false;
    }
    let year_ok = bytes[0..4].iter().all(|b| b.is_ascii_digit());
    let year: u16 = s[0..4].parse().unwrap_or(0);
    let month: u8 = s[5..7].parse().unwrap_or(0);
    let day: u8 = s[8..10].parse().unwrap_or(0);
    if !year_ok || !(1..=12).contains(&month) || day == 0 {
        return false;
    }
    let is_leap = (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400);
    let max_day = match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if is_leap {
                29
            } else {
                28
            }
        }
        _ => return false,
    };
    day <= max_day
}

/// Extract a date string from a YAML value, handling yaml_serde auto-parsing.
///
/// `yaml_serde` sometimes deserialises `YYYY-MM-DD` as a tagged/non-string
/// type. This helper coerces such values back to a trimmed string.
fn extract_date_string(raw: &Value) -> Option<String> {
    raw.as_str().map(|s| s.to_string()).or_else(|| {
        yaml_serde::to_string(raw)
            .ok()
            .map(|s| s.trim().to_string())
    })
}

/// Validate a UUID string (any version, hyphenated form).
pub(crate) fn is_valid_uuid(s: &str) -> bool {
    if s.len() != 36 {
        return false;
    }
    let parts: Vec<&str> = s.split('-').collect();
    if parts.len() != 5 {
        return false;
    }
    let expected_lens = [8, 4, 4, 4, 12];
    parts
        .iter()
        .zip(expected_lens.iter())
        .all(|(part, &len)| part.len() == len && part.chars().all(|c| c.is_ascii_hexdigit()))
}

pub(crate) fn lint_shared(m: &yaml_serde::Mapping, warnings: &mut Vec<LintWarning>) {
    // ── title ────────────────────────────────────────────────────────────
    match super::super::get_str(m, "title") {
        None => warnings.push(err(
            LintRule::MissingTitle,
            "missing required field 'title'",
            "/title",
        )),
        Some(t) if t.trim().is_empty() => {
            warnings.push(err(
                LintRule::EmptyTitle,
                "title must not be empty",
                "/title",
            ));
        }
        Some(t) if t.len() > 256 => {
            warnings.push(warning(
                LintRule::TitleTooLong,
                format!("title is {} characters, maximum is 256", t.len()),
                "/title",
            ));
        }
        _ => {}
    }

    // ── id ───────────────────────────────────────────────────────────────
    if let Some(id) = super::super::get_str(m, "id")
        && !is_valid_uuid(id)
    {
        warnings.push(warning(
            LintRule::InvalidId,
            format!("id \"{id}\" is not a valid UUID"),
            "/id",
        ));
    }

    // ── status ───────────────────────────────────────────────────────────
    if let Some(status) = super::super::get_str(m, "status")
        && !VALID_STATUSES.contains(&status)
    {
        let fix = closest_match(status, VALID_STATUSES, 3).map(|closest| Fix {
            title: format!("replace '{status}' with '{closest}'"),
            disposition: FixDisposition::Safe,
            patches: vec![FixPatch::ReplaceValue {
                path: "/status".into(),
                new_value: closest.into(),
            }],
        });
        warnings.push(LintWarning {
            rule: LintRule::InvalidStatus,
            severity: Severity::Error,
            message: format!(
                "invalid status \"{status}\", expected one of: {}",
                VALID_STATUSES.join(", ")
            ),
            path: "/status".into(),
            span: None,
            fix,
        });
    }

    // ── level ────────────────────────────────────────────────────────────
    if let Some(level) = super::super::get_str(m, "level")
        && !VALID_LEVELS.contains(&level)
    {
        let fix = closest_match(level, VALID_LEVELS, 3).map(|closest| Fix {
            title: format!("replace '{level}' with '{closest}'"),
            disposition: FixDisposition::Safe,
            patches: vec![FixPatch::ReplaceValue {
                path: "/level".into(),
                new_value: closest.into(),
            }],
        });
        warnings.push(LintWarning {
            rule: LintRule::InvalidLevel,
            severity: Severity::Error,
            message: format!(
                "invalid level \"{level}\", expected one of: {}",
                VALID_LEVELS.join(", ")
            ),
            path: "/level".into(),
            span: None,
            fix,
        });
    }

    // ── date ─────────────────────────────────────────────────────────────
    let date_string = m.get(key("date")).and_then(extract_date_string);
    if let Some(d) = &date_string
        && !is_valid_date(d)
    {
        warnings.push(err(
            LintRule::InvalidDate,
            format!("invalid date \"{d}\", expected YYYY-MM-DD"),
            "/date",
        ));
    }

    // ── modified ─────────────────────────────────────────────────────────
    let modified_string = m.get(key("modified")).and_then(extract_date_string);
    if let Some(d) = &modified_string
        && !is_valid_date(d)
    {
        warnings.push(err(
            LintRule::InvalidModified,
            format!("invalid modified date \"{d}\", expected YYYY-MM-DD"),
            "/modified",
        ));
    }

    // ── modified >= date ─────────────────────────────────────────────────
    if let (Some(date_val), Some(mod_val)) = (&date_string, &modified_string)
        && is_valid_date(date_val)
        && is_valid_date(mod_val)
        && mod_val.as_str() < date_val.as_str()
    {
        warnings.push(warning(
            LintRule::ModifiedBeforeDate,
            format!("modified date \"{mod_val}\" is before creation date \"{date_val}\""),
            "/modified",
        ));
    }

    // ── description (missing) ──────────────────────────────────────────
    if !m.contains_key(key("description")) {
        warnings.push(info(
            LintRule::MissingDescription,
            "missing recommended field 'description'",
            "/description",
        ));
    }

    // ── author (missing) ─────────────────────────────────────────────
    if !m.contains_key(key("author")) {
        warnings.push(info(
            LintRule::MissingAuthor,
            "missing recommended field 'author'",
            "/author",
        ));
    }

    // ── description (too long) ───────────────────────────────────────
    if let Some(desc) = super::super::get_str(m, "description")
        && desc.len() > 65535
    {
        warnings.push(warning(
            LintRule::DescriptionTooLong,
            format!("description is {} characters, maximum is 65535", desc.len()),
            "/description",
        ));
    }

    // ── name ─────────────────────────────────────────────────────────────
    if let Some(name) = super::super::get_str(m, "name")
        && name.len() > 256
    {
        warnings.push(warning(
            LintRule::NameTooLong,
            format!("name is {} characters, maximum is 256", name.len()),
            "/name",
        ));
    }

    // ── taxonomy ─────────────────────────────────────────────────────────
    if let Some(tax) = super::super::get_str(m, "taxonomy")
        && tax.len() > 256
    {
        warnings.push(warning(
            LintRule::TaxonomyTooLong,
            format!("taxonomy is {} characters, maximum is 256", tax.len()),
            "/taxonomy",
        ));
    }

    // ── lowercase keys ───────────────────────────────────────────────────
    for k in m.keys() {
        if let Some(ks) = k.as_str()
            && ks != ks.to_ascii_lowercase()
        {
            let lower = ks.to_ascii_lowercase();
            let mut w = warning(
                LintRule::NonLowercaseKey,
                format!("key \"{ks}\" should be lowercase"),
                format!("/{ks}"),
            );
            w.fix = safe_fix(
                format!("rename '{ks}' to '{lower}'"),
                vec![FixPatch::ReplaceKey {
                    path: format!("/{ks}"),
                    new_key: lower,
                }],
            );
            warnings.push(w);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::super::{Fix, LintRule, LintWarning, Severity, lint_yaml_value};
    use super::*;

    fn yaml_value(yaml: &str) -> yaml_serde::Value {
        yaml_serde::from_str(yaml).unwrap()
    }

    fn lint(yaml: &str) -> Vec<LintWarning> {
        lint_yaml_value(&yaml_value(yaml))
    }

    fn has_rule(warnings: &[LintWarning], rule: LintRule) -> bool {
        warnings.iter().any(|w| w.rule == rule)
    }

    fn has_no_rule(warnings: &[LintWarning], rule: LintRule) -> bool {
        !has_rule(warnings, rule)
    }

    fn find_fix(warnings: &[LintWarning], rule: LintRule) -> Option<&Fix> {
        warnings
            .iter()
            .find(|w| w.rule == rule)
            .and_then(|w| w.fix.as_ref())
    }

    fn fix_summary(fix: &Fix) -> String {
        use std::fmt::Write;
        let mut s = String::new();
        writeln!(s, "title: {}", fix.title).unwrap();
        writeln!(s, "disposition: {:?}", fix.disposition).unwrap();
        for (i, p) in fix.patches.iter().enumerate() {
            match p {
                super::super::super::FixPatch::ReplaceValue { path, new_value } => {
                    writeln!(s, "patch[{i}]: ReplaceValue {path} -> {new_value}").unwrap();
                }
                super::super::super::FixPatch::ReplaceKey { path, new_key } => {
                    writeln!(s, "patch[{i}]: ReplaceKey {path} -> {new_key}").unwrap();
                }
                super::super::super::FixPatch::Remove { path } => {
                    writeln!(s, "patch[{i}]: Remove {path}").unwrap();
                }
            }
        }
        s
    }

    #[test]
    fn missing_title() {
        let w = lint(
            r#"
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::MissingTitle));
    }

    #[test]
    fn empty_title() {
        let w = lint(
            r#"
title: ''
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
level: medium
"#,
        );
        assert!(has_rule(&w, LintRule::EmptyTitle));
    }

    #[test]
    fn title_too_long() {
        let long_title = "a".repeat(257);
        let yaml = format!(
            r#"
title: '{long_title}'
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#
        );
        let w = lint(&yaml);
        assert!(has_rule(&w, LintRule::TitleTooLong));
    }

    #[test]
    fn invalid_id() {
        let w = lint(
            r#"
title: Test
id: not-a-uuid
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::InvalidId));
    }

    #[test]
    fn valid_id_no_warning() {
        let w = lint(
            r#"
title: Test
id: 929a690e-bef0-4204-a928-ef5e620d6fcc
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_no_rule(&w, LintRule::InvalidId));
    }

    #[test]
    fn invalid_status() {
        let w = lint(
            r#"
title: Test
status: invalid
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::InvalidStatus));
    }

    #[test]
    fn invalid_level() {
        let w = lint(
            r#"
title: Test
level: important
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::InvalidLevel));
    }

    #[test]
    fn invalid_date_format() {
        let w = lint(
            r#"
title: Test
date: 'Jan 2025'
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::InvalidDate));
    }

    #[test]
    fn modified_before_date() {
        let w = lint(
            r#"
title: Test
date: '2025-06-15'
modified: '2025-06-10'
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::ModifiedBeforeDate));
    }

    #[test]
    fn non_lowercase_key() {
        let w = lint(
            r#"
title: Test
Status: test
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
"#,
        );
        assert!(has_rule(&w, LintRule::NonLowercaseKey));
    }

    #[test]
    fn invalid_date_feb_30() {
        assert!(!is_valid_date("2025-02-30"));
    }

    #[test]
    fn invalid_date_apr_31() {
        assert!(!is_valid_date("2025-04-31"));
    }

    #[test]
    fn valid_date_feb_28() {
        assert!(is_valid_date("2025-02-28"));
    }

    #[test]
    fn valid_date_leap_year_feb_29() {
        assert!(is_valid_date("2024-02-29"));
    }

    #[test]
    fn invalid_date_non_leap_feb_29() {
        assert!(!is_valid_date("2025-02-29"));
    }

    #[test]
    fn missing_description_info() {
        let w = lint(
            r#"
title: Test
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
level: medium
"#,
        );
        assert!(has_rule(&w, LintRule::MissingDescription));
        let md = w
            .iter()
            .find(|w| w.rule == LintRule::MissingDescription)
            .unwrap();
        assert_eq!(md.severity, Severity::Info);
    }

    #[test]
    fn has_description_no_info() {
        let w = lint(
            r#"
title: Test
description: A fine description
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
level: medium
"#,
        );
        assert!(has_no_rule(&w, LintRule::MissingDescription));
    }

    #[test]
    fn missing_author_info() {
        let w = lint(
            r#"
title: Test
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
level: medium
"#,
        );
        assert!(has_rule(&w, LintRule::MissingAuthor));
        let ma = w
            .iter()
            .find(|w| w.rule == LintRule::MissingAuthor)
            .unwrap();
        assert_eq!(ma.severity, Severity::Info);
    }

    #[test]
    fn has_author_no_info() {
        let w = lint(
            r#"
title: Test
author: tester
logsource:
    category: test
detection:
    selection:
        field: value
    condition: selection
level: medium
"#,
        );
        assert!(has_no_rule(&w, LintRule::MissingAuthor));
    }

    #[test]
    fn fix_invalid_status() {
        let w = lint(
            r#"
title: Test
status: expreimental
logsource:
    category: test
detection:
    sel:
        field: value
    condition: sel
"#,
        );
        let fix = find_fix(&w, LintRule::InvalidStatus).expect("should have fix");
        insta::assert_snapshot!(fix_summary(fix), @r"
        title: replace 'expreimental' with 'experimental'
        disposition: Safe
        patch[0]: ReplaceValue /status -> experimental
        ");
    }

    #[test]
    fn fix_invalid_level() {
        let w = lint(
            r#"
title: Test
level: hgih
logsource:
    category: test
detection:
    sel:
        field: value
    condition: sel
"#,
        );
        let fix = find_fix(&w, LintRule::InvalidLevel).expect("should have fix");
        insta::assert_snapshot!(fix_summary(fix), @r"
        title: replace 'hgih' with 'high'
        disposition: Safe
        patch[0]: ReplaceValue /level -> high
        ");
    }

    #[test]
    fn fix_non_lowercase_key() {
        let w = lint(
            r#"
title: Test
Status: test
logsource:
    category: test
detection:
    sel:
        field: value
    condition: sel
"#,
        );
        let fix = find_fix(&w, LintRule::NonLowercaseKey).expect("should have fix");
        insta::assert_snapshot!(fix_summary(fix), @r"
        title: rename 'Status' to 'status'
        disposition: Safe
        patch[0]: ReplaceKey /Status -> status
        ");
    }

    #[test]
    fn no_fix_for_far_invalid_status() {
        let w = lint(
            r#"
title: Test
status: totallyinvalidxyz
logsource:
    category: test
detection:
    sel:
        field: value
    condition: sel
"#,
        );
        assert!(has_rule(&w, LintRule::InvalidStatus));
        assert!(
            find_fix(&w, LintRule::InvalidStatus).is_none(),
            "no fix when edit distance is too large"
        );
    }
}