use proptest::prelude::*;
use super::*;
fn header_pipes(span: &[u8], at: usize) -> bool {
span.get(at..)
.is_some_and(|rest| memchr::memchr_iter(b'|', rest).nth(4).is_some())
}
fn severity_tag(span: &[u8], at: usize) -> bool {
let rest = span.get(at + 1..).unwrap_or_default();
let fac = rest.iter().take_while(|b| b.is_ascii_uppercase()).count();
fac > 0 && rest.get(fac) == Some(&b'-') && rest.get(fac + 1).is_some_and(u8::is_ascii_digit)
}
const CEF: usize = 0;
const VENDOR_A: usize = 1;
const VENDOR_B: usize = 2;
const TAG_CATCH_ALL: usize = 3;
const KEY_SET: usize = 4;
const SYSLOG: usize = 5;
fn table() -> Vec<Signature> {
vec![
Signature::builder()
.anchored(["CEF:", "LEEF:"])
.verify(header_pipes)
.priority(50)
.build()
.unwrap(),
Signature::builder()
.any_of(["%VNDA-"])
.priority(40)
.build()
.unwrap(),
Signature::builder()
.any_of(["%VNDB-", "%VNDA-6-430"])
.priority(45)
.build()
.unwrap(),
Signature::builder()
.any_of(["%"])
.verify(severity_tag)
.priority(10)
.build()
.unwrap(),
Signature::builder()
.all_of(["IN=", "OUT=", "SRC="])
.priority(30)
.build()
.unwrap(),
Signature::builder()
.anchored(["<"])
.specificity(Specificity::Generic)
.priority(255)
.build()
.unwrap(),
Signature::builder()
.any_of(["apikey"])
.within(12)
.specificity(Specificity::Generic)
.build()
.unwrap(),
Signature::builder()
.anchored(["CEF:"])
.any_of(["OUT="])
.specificity(Specificity::Generic)
.build()
.unwrap(),
Signature::builder()
.anchored(["<"])
.all_of(["key", "SRC="])
.within(20)
.specificity(Specificity::Generic)
.build()
.unwrap(),
]
}
#[test]
fn best_names_the_winner() {
let sigs = table();
let set = SignatureSet::new(&sigs).unwrap();
let mut scratch = set.scratch();
let rows: &[(&str, &[u8], Option<usize>)] = &[
(
"cef header",
b"CEF:0|Acme|Widget|1.0|100|x|5|src=1.2.3.4",
Some(CEF),
),
("leef header", b"LEEF:2.0|Acme|Widget|1.0|100|", Some(CEF)),
("cef not at start", b"x CEF:0|a|b|c|d|e|f|", None),
("cef too few pipes", b"CEF:0|a|b", None),
("vendor a", b"%VNDA-6-302013: Built inbound", Some(VENDOR_A)),
(
"vendor b owns its tag",
b"%VNDB-6-430003: x",
Some(VENDOR_B),
),
(
"vendor b wins a shared id",
b"%VNDA-6-430003: x",
Some(VENDOR_B),
),
(
"catch-all tag",
b"r: %SYS-5-CONFIG_I: Configured",
Some(TAG_CATCH_ALL),
),
("a percent is not a tag", b"100% sure", None),
(
"key set needs every key",
b"IN=eth0 OUT= SRC=1.2.3.4",
Some(KEY_SET),
),
("key set missing one", b"IN=eth0 SRC=1.2.3.4", None),
(
"specific beats generic",
b"<13>%SYS-5-X: y",
Some(TAG_CATCH_ALL),
),
("generic alone", b"<13>plain line", Some(SYSLOG)),
("empty", b"", None),
];
for (name, span, want) in rows {
let got = set.best(span, &mut scratch).map(|m| m.index);
assert_eq!(got, *want, "{name}");
}
}
#[test]
fn a_verify_that_rejects_one_hit_still_sees_the_next() {
let sig = Signature::builder()
.any_of(["%"])
.verify(severity_tag)
.build()
.unwrap();
let span = b"50% then %LINK-3-UPDOWN";
assert!(sig.may_match(span));
let set = SignatureSet::new([&sig]).unwrap();
let m = set.best(span, &mut set.scratch()).unwrap();
assert_eq!(m.at, 9);
}
fn only_at_one(_: &[u8], at: usize) -> bool {
at == 1
}
fn never(_: &[u8], _: usize) -> bool {
false
}
#[test]
fn overlapping_hits_and_the_verify_cap_agree_alone_and_in_a_set() {
let overlap = Signature::builder()
.any_of(["aa"])
.verify(only_at_one)
.build()
.unwrap();
let capped = Signature::builder()
.any_of(["%"])
.verify(never)
.build()
.unwrap();
let uncapped = Signature::builder()
.any_of(["%"])
.verify(never)
.verify_cap(None)
.build()
.unwrap();
let two = Signature::builder()
.any_of(["%"])
.verify(never)
.verify_cap(Some(2))
.build()
.unwrap();
let at_cap = "%".repeat(usize::from(MAX_VERIFY));
let past_cap = "%".repeat(usize::from(MAX_VERIFY) + 1);
let far_past = "%".repeat(300);
let cases: [(&Signature, &str, bool); 9] = [
(&overlap, "aaa", true),
(&overlap, "aab", false),
(&capped, &at_cap, false),
(&capped, &past_cap, true),
(&uncapped, &past_cap, false),
(&uncapped, &far_past, false),
(&two, "%%", false),
(&two, "%%%", true),
(&two, &past_cap, true),
];
let table = table();
for (sig, span, want) in cases {
assert_eq!(sig.may_match(span.as_bytes()), want, "{span}");
let alone = SignatureSet::new([sig]).unwrap();
let fired = alone.best(span.as_bytes(), &mut alone.scratch()).is_some();
assert_eq!(fired, want, "{span} alone in a set");
let crowd = SignatureSet::new(std::iter::once(sig).chain(&table)).unwrap();
let mut fired = false;
crowd.for_each_match(span.as_bytes(), &mut crowd.scratch(), |m| {
fired |= m.index == 0;
});
assert_eq!(fired, want, "{span} in a crowded set");
}
}
type HitCase<'a> = (&'a Signature, &'a [&'a [u8]], &'a [(usize, usize)]);
#[test]
fn every_hit_reports_each_firing_hit_with_its_span() {
let opener = Signature::builder()
.any_of(["CEF:", "LEEF:"])
.every_hit(true)
.build()
.unwrap();
let even = Signature::builder()
.any_of(["%"])
.verify(even_at)
.verify_cap(None)
.every_hit(true)
.build()
.unwrap();
let needs_key = Signature::builder()
.all_of(["key="])
.any_of(["CEF:"])
.every_hit(true)
.build()
.unwrap();
let first_only = Signature::builder()
.any_of(["CEF:", "LEEF:"])
.build()
.unwrap();
let two = Signature::builder()
.any_of(["%"])
.verify(never)
.verify_cap(Some(2))
.every_hit(true)
.build()
.unwrap();
let cases: [HitCase<'_>; 9] = [
(
&opener,
&[b"x CEF:0| LEEF:1| CEF:"],
&[(0, 2), (0, 9), (0, 17)],
),
(&opener, &[b"no opener"], &[]),
(&opener, &[b"CEF:", b"a LEEF:"], &[(0, 0), (1, 2)]),
(&even, &[b"%%%%%"], &[(0, 0), (0, 2), (0, 4)]),
(&even, &[b"x%x%", b"%%"], &[(1, 0)]),
(&needs_key, &[b"CEF: CEF:", b"key="], &[(0, 0), (0, 5)]),
(&needs_key, &[b"CEF: CEF:"], &[]),
(&first_only, &[b"x CEF:0| LEEF:1|"], &[(0, 2)]),
(&two, &[b"%%%%"], &[(0, 2), (0, 3)]),
];
let table = table();
for (sig, spans, want) in cases {
let alone = SignatureSet::new([sig]).unwrap();
let crowd = SignatureSet::new(std::iter::once(sig).chain(&table)).unwrap();
for (name, set) in [("alone", &alone), ("crowd", &crowd)] {
let mut got = Vec::new();
set.for_each_match_spans(spans, &mut set.scratch(), |m| {
if m.index == 0 {
got.push((m.span, m.at));
}
});
assert_eq!(got, want, "{spans:?} {name}");
if let [span] = spans {
let mut one = Vec::new();
set.for_each_match(span, &mut set.scratch(), |m| {
if m.index == 0 {
one.push((m.span, m.at));
}
});
assert_eq!(one, want, "{span:?} {name} one span");
}
}
}
}
#[test]
fn nested_literals_are_all_reported() {
let short = Signature::builder().any_of(["key"]).build().unwrap();
let long = Signature::builder().any_of(["apikey"]).build().unwrap();
let set = SignatureSet::new([&short, &long]).unwrap();
let mut hits = Vec::new();
set.for_each_match(b"my apikey=1", &mut set.scratch(), |m| hits.push(m.index));
assert_eq!(hits, [0, 1]);
}
#[test]
fn a_key_set_pools_across_spans_and_a_tag_names_its_span() {
let key_set = Signature::builder()
.all_of(["IN=", " SRC="])
.build()
.unwrap();
let tag = Signature::builder().any_of(["Tag:"]).build().unwrap();
let set = SignatureSet::new([&key_set, &tag]).unwrap();
let spans: [&[u8]; 2] = [b"IN=eth0 OUT=", b" host Tag: SRC=1"];
let mut hits = Vec::new();
set.for_each_match_spans(&spans, &mut set.scratch(), |m| {
hits.push((m.index, m.span, m.at));
});
assert_eq!(hits, [(0, 0, 0), (1, 1, 6)]);
assert_eq!(matches_spans(&set, &[], &mut set.scratch()), []);
}
#[test]
fn a_literal_free_signature_is_flagged_and_never_fires_in_a_set() {
let free = Signature::builder().build().unwrap();
assert!(free.is_literal_free());
assert!(free.may_match(b"anything"));
let set = SignatureSet::new([&free]).unwrap();
assert!(set.best(b"anything", &mut set.scratch()).is_none());
}
#[test]
fn bad_signatures_are_refused() {
assert!(matches!(
Signature::builder().any_of([""]).build(),
Err(SignatureError::EmptyLiteral)
));
let many: Vec<String> = (0..=MAX_ALL_OF).map(|i| format!("k{i}=")).collect();
assert!(matches!(
Signature::builder().all_of(&many).build(),
Err(SignatureError::TooManyAllOf { got: 65, max: 64 })
));
let exact: Vec<String> = (0..MAX_ALL_OF).map(|i| format!("k{i}=")).collect();
let sig = Signature::builder().all_of(&exact).build().unwrap();
let span = exact.concat();
assert!(sig.may_match(span.as_bytes()));
let set = SignatureSet::new([&sig]).unwrap();
assert!(set.best(span.as_bytes(), &mut set.scratch()).is_some());
}
#[test]
fn scratch_from_another_set_is_resized() {
let sigs = table();
let set = SignatureSet::new(&sigs).unwrap();
let mut small = SignatureSet::new(&sigs[..1]).unwrap().scratch();
assert_eq!(
set.best(b"IN=a OUT=b SRC=c", &mut small).map(|m| m.index),
Some(KEY_SET)
);
}
#[test]
fn within_bounds_where_a_searched_literal_may_sit() {
let sig = Signature::builder()
.any_of([" stdout F "])
.within(16)
.build()
.unwrap();
let set = SignatureSet::new([&sig]).unwrap();
let cases: [(&[u8], bool); 4] = [
(b"12:00 stdout F x", true),
(b"12:00:00 stdout F x", false),
(b"a line with the marker far along it stdout F x", false),
(b"", false),
];
for (span, want) in cases {
let mut fired = false;
set.for_each_match(span, &mut set.scratch(), |_| fired = true);
assert_eq!(
sig.may_match(span),
want,
"{}",
String::from_utf8_lossy(span)
);
assert_eq!(fired, want, "{}", String::from_utf8_lossy(span));
}
}
fn span_strategy() -> impl Strategy<Value = Vec<u8>> {
let pieces = prop::sample::select(vec![
"CEF:", "LEEF:", "|", "%VNDA-", "%VNDB-", "6-430", "%", "%%%", "SYS", "-5-", "IN=", "OUT=",
"SRC=", "<", "13>", " ", "x", "key", "apikey",
]);
prop::collection::vec(pieces, 0..24).prop_map(|p| p.concat().into_bytes())
}
#[test]
fn a_short_span_is_ruled_out_unless_it_starts_with_a_whole_anchor() {
let anchored = Signature::builder()
.anchored(["Jan ", "<"])
.build()
.unwrap();
let free = Signature::builder()
.all_of(["0123456789abcdef"])
.build()
.unwrap();
let set = SignatureSet::new(&[anchored, free]).unwrap();
for (span, could) in [
(&b"Jan 15"[..], true),
(b"Jan ", true),
(b"<34>", true),
(b"Jane", false),
(b"Jan", false),
(b"J", false),
(b"", false),
(b"0123456789abcdefg", true),
] {
assert_eq!(
set.could_fire(span),
could,
"{:?}",
String::from_utf8_lossy(span)
);
}
}
fn upper_at(span: &[u8], at: usize) -> bool {
span.get(at).is_some_and(u8::is_ascii_uppercase)
}
fn matches(set: &SignatureSet, span: &[u8], scratch: &mut SignatureScratch) -> Vec<SignatureMatch> {
let mut out = Vec::new();
set.for_each_match(span, scratch, |m| out.push(m));
out
}
fn matches_spans(
set: &SignatureSet,
spans: &[&[u8]],
scratch: &mut SignatureScratch,
) -> Vec<SignatureMatch> {
let mut out = Vec::new();
set.for_each_match_spans(spans, scratch, |m| out.push(m));
out
}
#[test]
fn folded_signatures_fold_ascii_case_and_nothing_else() {
let folded = |b: SignatureBuilder| b.ascii_case_insensitive(true).build().unwrap();
let cef = folded(Signature::builder().anchored(["cef:"]).verify(header_pipes));
let model = folded(Signature::builder().all_of(["SM-", "Build"]));
let kelvin = folded(Signature::builder().any_of(["k"]));
let accent = folded(Signature::builder().any_of(["\u{e9}t\u{e9}"]));
let upper = folded(Signature::builder().any_of(["x"]).verify(upper_at));
let exact = Signature::builder().any_of(["Build"]).build().unwrap();
let rows: [(&Signature, &str, Option<usize>); 16] = [
(&cef, "CEF:0|a|b|c|d|e|f|", Some(0)),
(&cef, "Cef:0|a|b|c|d|e|f|", Some(0)),
(&cef, "CEF:0|a|b", None),
(&cef, "xCEF:0|a|b|c|d|e|f|", None),
(&cef, "CE", None),
(&model, "Linux; SM-G960F BUILD/R16NW", Some(0)),
(&model, "linux; sm-g960f build/r16nw", Some(0)),
(&model, "Linux; SM-G960F", None),
(&model, "", None),
(&kelvin, "OK", Some(1)),
(&kelvin, "\u{212a}", None),
(&accent, "\u{e9}T\u{e9}", Some(0)),
(&accent, "\u{c9}t\u{c9}", None),
(&upper, "x X", Some(2)),
(&exact, "build", None),
(&exact, "Build", Some(0)),
];
let table = table();
for (sig, span, want) in rows {
let span = span.as_bytes();
let label = String::from_utf8_lossy(span);
assert_eq!(sig.may_match(span), want.is_some(), "{label} alone");
let alone = SignatureSet::new([sig]).unwrap();
let crowd = SignatureSet::new(std::iter::once(sig).chain(&table)).unwrap();
for (name, set) in [("alone", alone), ("crowd", crowd)] {
let got = matches(&set, span, &mut set.scratch());
let at = got.iter().find(|m| m.index == 0).map(|m| m.at);
assert_eq!(at, want, "{label} {name}");
}
}
let set = SignatureSet::new([&cef]).unwrap();
for (span, could) in [(&b"CEF:"[..], true), (b"cef:", true), (b"CE", false)] {
assert_eq!(set.could_fire(span), could, "{span:?}");
}
}
#[test]
fn a_scratch_past_its_last_epoch_still_answers() {
let mut sigs = table();
sigs.push(Signature::builder().any_of(["zz"]).build().unwrap());
let set = SignatureSet::new(&sigs).unwrap();
let spans: [&[u8]; 4] = [
b"IN=a OUT=b SRC=c",
b"CEF:0|a|b|c|d|e|OUT=|",
b"IN=a OUT=b SRC=c",
b"<13>key SRC=1",
];
let mut worn = set.scratch();
let _ = matches(&set, spans[0], &mut worn);
let _ = matches_spans(&set, &spans, &mut worn);
worn.epoch = u32::MAX - 1;
worn.span_epoch = u32::MAX - 2;
for span in spans {
let want = matches(&set, span, &mut set.scratch());
assert!(!want.is_empty(), "{}", String::from_utf8_lossy(span));
assert_eq!(matches(&set, span, &mut worn), want);
let pair = [span, &b"<13>"[..]];
let want = matches_spans(&set, &pair, &mut set.scratch());
assert_eq!(matches_spans(&set, &pair, &mut worn), want);
}
}
fn even_at(_: &[u8], at: usize) -> bool {
at.is_multiple_of(2)
}
fn after_digit(span: &[u8], at: usize) -> bool {
at.checked_sub(1)
.and_then(|i| span.get(i))
.is_some_and(u8::is_ascii_digit)
}
const VERIFIES: [Verify; 4] = [only_at_one, never, even_at, after_digit];
struct OldSet<'a> {
sigs: &'a [Signature],
ac: Option<AhoCorasick>,
uses: Vec<Vec<(usize, Option<u64>)>>,
free: Vec<usize>,
}
#[derive(Debug, Clone, Copy, Default)]
struct OldProgress {
touched: bool,
anchored: bool,
all: u64,
trigger: Option<usize>,
refused: u8,
settled: bool,
}
impl<'a> OldSet<'a> {
fn new(sigs: &'a [Signature]) -> Self {
let mut literals: Vec<&[u8]> = Vec::new();
let mut uses: Vec<Vec<(usize, Option<u64>)>> = Vec::new();
let mut add = |literal: &'a [u8], u| {
if let Some(id) = literals.iter().position(|l| *l == literal) {
uses[id].push(u);
} else {
literals.push(literal);
uses.push(vec![u]);
}
};
for (i, s) in sigs.iter().enumerate() {
for (bit, f) in s.all_of.iter().enumerate() {
add(f.bytes(), (i, Some(1 << bit)));
}
for f in &s.any_of {
add(f.bytes(), (i, None));
}
}
let ac = (!literals.is_empty()).then(|| {
AhoCorasick::builder()
.match_kind(MatchKind::Standard)
.build(&literals)
.unwrap()
});
let free = (0..sigs.len())
.filter(|&i| sigs[i].anchored.is_empty() && sigs[i].searched_len() > 0)
.collect();
Self {
sigs,
ac,
uses,
free,
}
}
fn matches(&self, span: &[u8]) -> Vec<SignatureMatch> {
let reach = |s: &Signature| {
if s.searched_len() > 0 {
s.within.unwrap_or(usize::MAX)
} else {
0
}
};
let mut p = vec![OldProgress::default(); self.sigs.len()];
let mut touched = Vec::new();
let mut read = self
.free
.iter()
.map(|&i| reach(&self.sigs[i]))
.max()
.unwrap_or(0);
let mut literals: usize = self.free.iter().map(|&i| self.sigs[i].searched_len()).sum();
for (i, s) in self.sigs.iter().enumerate() {
if s.anchored.iter().any(|a| span.starts_with(a)) {
touched.push(i);
p[i].touched = true;
p[i].anchored = true;
literals += s.searched_len();
read = read.max(reach(s));
}
}
if literals <= DIRECT_LITERALS {
let anchored = touched.len();
touched.extend_from_slice(&self.free);
for (k, &i) in touched.iter().enumerate() {
if k < anchored && reach(&self.sigs[i]) == 0 {
continue;
}
p[i].touched = true;
p[i].settled = true;
p[i].trigger = self.sigs[i].searched(span);
}
} else if let Some(ac) = &self.ac
&& read > 0
{
for hit in ac.find_overlapping_iter(&span[..span.len().min(read)]) {
for &(i, bit) in &self.uses[hit.pattern().as_usize()] {
let s = &self.sigs[i];
if hit.end() > s.within.unwrap_or(usize::MAX) {
continue;
}
if !p[i].touched {
p[i].touched = true;
touched.push(i);
}
match bit {
Some(bit) => p[i].all |= bit,
None if p[i].trigger.is_some() => {}
None => {
if p[i].refused == MAX_VERIFY
|| s.verify.is_none_or(|v| v(span, hit.start()))
{
p[i].trigger = Some(hit.start());
} else {
p[i].refused += 1;
}
}
}
}
}
}
touched.sort_unstable();
let mut out = Vec::new();
for i in touched {
let (q, s) = (p[i], &self.sigs[i]);
let full = match s.all_of.len() {
0 => 0,
MAX_ALL_OF => u64::MAX,
n => (1 << n) - 1,
};
let at = if q.settled || !s.any_of.is_empty() {
q.trigger
} else {
s.verify.is_none_or(|v| v(span, 0)).then_some(0)
};
if let Some(at) = at
&& (s.anchored.is_empty() || q.anchored)
&& (q.settled || q.all == full)
{
out.push(SignatureMatch {
index: i,
at,
span: 0,
});
}
}
out
}
}
type Spec = (
Vec<&'static str>,
Vec<&'static str>,
Vec<&'static str>,
Option<usize>,
Option<usize>,
);
fn spec_strategy() -> impl Strategy<Value = Spec> {
let literal = || {
prop::sample::select(vec![
"a", "b", "ab", "ba", "aa", "abc", "Ab", "%", "%a", "x", "1", "a1", "k",
])
};
(
prop::collection::vec(literal(), 0..2),
prop::collection::vec(literal(), 0..4),
prop::collection::vec(literal(), 0..4),
prop::option::of(0..VERIFIES.len()),
prop::option::of(0..24_usize),
)
}
fn build_spec(spec: &Spec, folded: bool, lower: bool) -> Signature {
let case = |l: &&str| {
if lower {
l.to_ascii_lowercase()
} else {
(*l).to_string()
}
};
let (anchored, all_of, any_of, verify, within) = spec;
let mut b = Signature::builder()
.anchored(anchored.iter().map(case))
.all_of(all_of.iter().map(case))
.any_of(any_of.iter().map(case))
.ascii_case_insensitive(folded);
if let Some(v) = verify {
b = b.verify(VERIFIES[*v]);
}
if let Some(n) = within {
b = b.within(*n);
}
b.build().unwrap()
}
fn mixed_span() -> impl Strategy<Value = Vec<u8>> {
let pieces = prop::sample::select(vec![
"a", "A", "b", "B", "ab", "AB", "aB", "%", "1", "x", "X", " ", "c", "K", "\u{212a}",
"\u{e9}",
]);
prop::collection::vec(pieces, 0..30).prop_map(|p| p.concat().into_bytes())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1024))]
#[test]
fn the_walk_gives_the_old_walks_matches(
specs in prop::collection::vec(spec_strategy(), 1..16),
spans in prop::collection::vec(mixed_span(), 1..4),
) {
let sigs: Vec<Signature> = specs.iter().map(|s| build_spec(s, false, false)).collect();
let set = SignatureSet::new(&sigs).unwrap();
let old = OldSet::new(&sigs);
let mut scratch = set.scratch();
for span in &spans {
prop_assert_eq!(matches(&set, span, &mut scratch), old.matches(span));
}
}
#[test]
fn a_folded_set_is_the_old_walk_over_lower_case(
specs in prop::collection::vec(spec_strategy(), 1..16),
spans in prop::collection::vec(mixed_span(), 1..4),
) {
let folded: Vec<Signature> = specs.iter().map(|s| build_spec(s, true, false)).collect();
let lower: Vec<Signature> = specs.iter().map(|s| build_spec(s, false, true)).collect();
let set = SignatureSet::new(&folded).unwrap();
let old = OldSet::new(&lower);
let mut scratch = set.scratch();
for span in &spans {
let low = span.to_ascii_lowercase();
prop_assert_eq!(matches(&set, span, &mut scratch), old.matches(&low));
for (i, (f, l)) in folded.iter().zip(&lower).enumerate() {
prop_assert_eq!(f.may_match(span), l.may_match(&low), "signature {}", i);
}
}
}
#[test]
fn a_mixed_set_agrees_with_each_signature_alone(
specs in prop::collection::vec((spec_strategy(), any::<bool>()), 1..16),
span in mixed_span(),
) {
let sigs: Vec<Signature> = specs.iter().map(|(s, f)| build_spec(s, *f, false)).collect();
let set = SignatureSet::new(&sigs).unwrap();
let mut fired = vec![false; sigs.len()];
set.for_each_match(&span, &mut set.scratch(), |m| fired[m.index] = true);
for (i, sig) in sigs.iter().enumerate() {
let want = !sig.is_literal_free() && sig.may_match(&span);
prop_assert_eq!(fired[i], want, "signature {}", i);
}
prop_assert!(set.could_fire(&span) || !fired.contains(&true));
}
}
proptest! {
#[test]
fn a_set_agrees_with_each_signature_alone(span in span_strategy()) {
let sigs = table();
let set = SignatureSet::new(&sigs).unwrap();
let mut fired = vec![false; sigs.len()];
set.for_each_match(&span, &mut set.scratch(), |m| fired[m.index] = true);
for (i, sig) in sigs.iter().enumerate() {
prop_assert_eq!(fired[i], sig.may_match(&span), "signature {}", i);
}
for cut in [span.len(), span.len().min(3), 0] {
let short = &span[..cut];
if !set.could_fire(short) {
set.for_each_match(short, &mut set.scratch(), |m| {
panic!("signature {} fired on a span ruled out", m.index);
});
}
}
for (i, a) in sigs.iter().enumerate() {
let b = &sigs[(i + 1) % sigs.len()];
for pair in [[a, b], [b, a]] {
let set = SignatureSet::new(pair).unwrap();
let mut fired = [false; 2];
set.for_each_match(&span, &mut set.scratch(), |m| fired[m.index] = true);
prop_assert_eq!(fired[0], pair[0].may_match(&span), "pair {} first", i);
prop_assert_eq!(fired[1], pair[1].may_match(&span), "pair {} second", i);
}
}
}
}
fn shape(h: &[u8], p: usize, pattern: &[u8]) -> bool {
h.get(p..p + pattern.len()).is_some_and(|w| {
w.iter().zip(pattern).all(|(&b, &want)| {
if want == b'd' {
b.is_ascii_digit()
} else {
b == want
}
})
})
}
fn run_of(h: &[u8], p: usize, keep: fn(u8) -> bool) -> usize {
h.get(p..)
.map_or(0, |rest| rest.iter().take_while(|&&b| keep(b)).count())
}
const fn mnemonic_byte(b: u8) -> bool {
b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_'
}
fn mnemonic(h: &[u8], at: usize) -> bool {
let tail = |p: usize| {
let name = run_of(h, p + 3, mnemonic_byte);
let end = p + 3 + name;
let end = end + usize::from(h.get(end) == Some(&b' '));
shape(h, p, b"-d-") && name > 0 && h.get(end) == Some(&b':')
};
let fac_end = at + 1 + run_of(h, at + 1, mnemonic_byte);
if fac_end == at + 1 {
return false;
}
let sub = (h.get(fac_end) == Some(&b'-')).then(|| {
fac_end
+ 1
+ run_of(h, fac_end + 1, |b| {
b.is_ascii_uppercase() || b.is_ascii_digit()
})
});
tail(fac_end) || sub.is_some_and(|end| end > fac_end + 1 && tail(end))
}
fn year_first(h: &[u8], at: usize) -> bool {
at.checked_sub(4)
.and_then(|from| h.get(from..at))
.is_some_and(|y| y.iter().all(u8::is_ascii_digit))
&& h.get(at + 1).is_some_and(u8::is_ascii_uppercase)
&& h.get(at + 4) == Some(&b' ')
&& (shape(h, at + 5, b" d") || shape(h, at + 5, b"dd"))
&& shape(h, at + 7, b" dd:dd:dd")
}
fn csv_date(h: &[u8], at: usize) -> bool {
let mut comma = at;
for _ in 0..3 {
let Some(next) = h
.get(comma + 1..)
.and_then(|rest| memchr::memchr(b',', rest))
else {
return false;
};
comma += 1 + next;
}
shape(h, comma + 1, b"dddd/dd/dd") || shape(h, comma + 1, b"dddd-dd-dd")
}
fn epoch_fraction(h: &[u8], at: usize) -> bool {
shape(h, at + br#"{"stamp":"#.len(), b"dddddddddd.")
}
fn csv_ids(h: &[u8], at: usize) -> bool {
let mut p = at + 2;
for _ in 0..3 {
let digits = run_of(h, p, |b| b.is_ascii_digit());
if digits == 0 || h.get(p + digits) != Some(&b',') {
return false;
}
p += digits + 1;
}
h.get(p) == Some(&b'"')
}
fn action_status(h: &[u8], at: usize) -> bool {
let name = if h.get(at..).is_some_and(|r| r.starts_with(b"NONE")) {
4
} else {
3
};
let slash = at + name + run_of(h, at + name, |b| b.is_ascii_uppercase() || b == b'_');
h.get(slash) == Some(&b'/') && shape(h, slash + 1, b"ddd ")
}
fn colon_stamp(h: &[u8], at: usize) -> bool {
shape(h, at, b"20dd:dd:dd-dd:dd:dd ")
}
#[test]
fn a_verify_reads_the_span_its_hit_is_in() {
let rows: &[(&str, Verify, &str, &str, bool)] = &[
(
"epoch",
epoch_fraction,
r#"{"stamp":1397248033.914,"md5""#,
r#"{"stamp":"#,
true,
),
(
"millis",
epoch_fraction,
r#"{"stamp":1725443872001,"id""#,
r#"{"stamp":"#,
false,
),
("mnemonic", mnemonic, "x %SYS-5-CONFIG_I: y", "%", true),
(
"mnemonic sub",
mnemonic,
"x %ETHPORT-SPEED-5-X: y",
"%",
true,
),
(
"mnemonic space",
mnemonic,
"x %LINK-3-UPDOWN : y",
"%",
true,
),
(
"mnemonic no sev",
mnemonic,
"x %SYS-CONFIG_I: y",
"%",
false,
),
("mnemonic bare", mnemonic, "100% done", "%", false),
(
"year first",
year_first,
": 2023 May 2 12:55:19 UTC:",
" May",
true,
),
(
"no year",
year_first,
"SGT: Jun 2 15:15:19 SGT",
" Jun",
false,
),
("no time", year_first, "in 2023 May the", " May", false),
(
"csv date",
csv_date,
"x,TRAFFIC,drop,2562,2024/12/02 18:26:37,y",
",TRAFFIC",
true,
),
(
"csv dashes",
csv_date,
"x,SYSTEM,gen,1,2024-12-02 18:26:37",
",SYSTEM",
true,
),
("csv no date", csv_date, "a,START,b,c,d", ",START", false),
("csv short", csv_date, "a,END,b", ",END", false),
(
"csv ids",
csv_ids,
r#"09/04 ,1,1000006,0,"TCP""#,
" ,",
true,
),
("csv text", csv_ids, "a ,b,c", " ,", false),
("action", action_status, "0 TCP_MISS/200 12", "TCP_", true),
("action none", action_status, "0 NONE/503 0", "NONE", true),
(
"action space",
action_status,
"200 TCP_NC_MISS GET",
"TCP_",
false,
),
(
"stamp",
colon_stamp,
"2023:04:28-00:00:04 host",
"2023",
true,
),
(
"stamp year only",
colon_stamp,
"2023:04 host",
"2023",
false,
),
];
for &(name, verify, line, literal, want) in rows {
let sig = Signature::builder()
.any_of([literal])
.verify(verify)
.build()
.unwrap();
let set = SignatureSet::new([&sig]).unwrap();
let at = line.find(literal).unwrap();
let alone = set.best(line.as_bytes(), &mut set.scratch()).is_some();
assert_eq!(alone, want, "{name} one span");
let pad: &[u8] = b"pad";
for (spans, s) in [([line.as_bytes(), pad], 0), ([pad, line.as_bytes()], 1)] {
let got = set.best_spans(&spans, &mut set.scratch());
assert_eq!(
got.map(|m| (m.span, m.at)),
want.then_some((s, at)),
"{name} span {s}"
);
}
}
}
type Source = (
&'static str,
u8,
&'static [&'static str],
bool,
Option<Verify>,
);
const SOURCES: [Source; 7] = [
("fw_a", 50, &["%VNDA-"], false, None),
("fw_b", 55, &["%VNDB-", "%VNDA-6-4300"], false, None),
("router", 10, &["%"], false, Some(mnemonic)),
("cef", 5, &["CEF:0|", "CEF:1|"], false, None),
("adc", 50, &["-PPE-"], false, None),
("netfilter", 50, &["IN=", " OUT=", " SRC="], true, None),
("vpn", 55, &["VpnTag:"], false, None),
];
const HEADERS: [(&str, u8, &str, &str); 3] = [
("dns", 60, "Acme", "Dns"),
("adc", 57, "Acme", "Adc"),
("waf", 56, "Acme", "Adc"),
];
struct Detector {
set: SignatureSet,
sources: Vec<(&'static str, u8)>,
headers: Vec<(&'static str, u8, &'static str, &'static str)>,
}
impl Detector {
fn new(candidates: &[&str]) -> Self {
let keep = |s: &str| candidates.is_empty() || candidates.contains(&s);
let mut sigs = Vec::new();
let mut sources = Vec::new();
for &(source, priority, markers, every, verify) in SOURCES.iter().filter(|s| keep(s.0)) {
let b = Signature::builder().priority(priority);
let b = if every {
b.all_of(markers)
} else {
b.any_of(markers)
};
let b = match verify {
Some(v) => b.verify(v),
None => b,
};
sigs.push(b.verify_cap(None).build().unwrap());
sources.push((source, priority));
}
let headers: Vec<_> = HEADERS.iter().copied().filter(|h| keep(h.0)).collect();
if !headers.is_empty() {
sigs.push(
Signature::builder()
.any_of(["CEF:", "LEEF:"])
.every_hit(true)
.build()
.unwrap(),
);
}
Self {
set: SignatureSet::new(&sigs).unwrap(),
sources,
headers,
}
}
fn header(&self, hay: &[u8], mut offer: impl FnMut(u8, usize)) {
let open = if hay.starts_with(b"CEF:") { 4 } else { 5 };
let mut fields = hay[open..].splitn(4, |&b| b == b'|');
let (Some(version), Some(vendor), Some(product), Some(_)) =
(fields.next(), fields.next(), fields.next(), fields.next())
else {
return;
};
if version.is_empty() || !version.iter().all(|b| b.is_ascii_digit() || *b == b'.') {
return;
}
for (j, &(_, p, v, pr)) in self.headers.iter().enumerate() {
if vendor.eq_ignore_ascii_case(v.as_bytes())
&& product.eq_ignore_ascii_case(pr.as_bytes())
{
offer(p, self.set.len() + j);
}
}
}
fn detect(&self, body: &[u8], head: &[u8]) -> Option<&'static str> {
let spans = [body, head];
let mut best: Option<(u8, usize)> = None;
let mut offer = |p: u8, i: usize| {
if best.is_none_or(|(bp, bi)| p > bp || (p == bp && i < bi)) {
best = Some((p, i));
}
};
self.set
.for_each_match_spans(&spans, &mut self.set.scratch(), |m| {
match self.sources.get(m.index) {
Some(&(_, priority)) => offer(priority, m.index),
None => self.header(&spans[m.span][m.at..], &mut offer),
}
});
best.map(|(_, i)| match self.sources.get(i) {
Some(&(name, _)) => name,
None => self.headers[i - self.set.len()].0,
})
}
}
type Row<'a> = (
&'a str,
&'a [&'a str],
String,
&'a str,
Option<&'a str>,
bool,
);
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 23 cases")]
fn a_detector_over_body_and_head_names_the_source() {
let fw_a = "%VNDA-6-302013: Built inbound TCP connection 1 for outside:1.2.3.4/80";
let cef = |vendor: &str, product: &str| format!("CEF:0|{vendor}|{product}|1.0|100|x|5|src=1");
let rows: Vec<Row<'_>> = vec![
("fw_a", &[], fw_a.into(), "", Some("fw_a"), false),
(
"fw_a out, fw_b alone",
&["fw_b"],
fw_a.into(),
"",
None,
false,
),
(
"fw_a out, router has it",
&["fw_b", "router"],
fw_a.into(),
"",
Some("router"),
false,
),
(
"fw_b owns its marker",
&[],
"%VNDB-6-430003: x".into(),
"",
Some("fw_b"),
false,
),
(
"fw_b wins a shared id",
&[],
"%VNDA-6-430003: x".into(),
"",
Some("fw_b"),
false,
),
(
"router catch-all",
&[],
"Jan 1 r: %SYS-5-CONFIG_I: Configured".into(),
"",
Some("router"),
false,
),
(
"router needs a severity",
&[],
"100% sure".into(),
"",
None,
false,
),
(
"cef vendor and product",
&[],
cef("Acme", "Dns"),
"",
Some("dns"),
true,
),
("cef case", &[], cef("ACME", "dns"), "", Some("dns"), true),
(
"cef unknown pair",
&[],
cef("Other", "Widget"),
"",
Some("cef"),
false,
),
(
"cef pair goes to adc",
&[],
cef("Acme", "Adc"),
"",
Some("adc"),
true,
),
(
"cef pair to waf without adc",
&["waf"],
cef("Acme", "Adc"),
"",
Some("waf"),
true,
),
(
"a key set needs every key",
&[],
"IN=eth0 OUT= SRC=1.2.3.4".into(),
"",
Some("netfilter"),
false,
),
(
"a key set missing one",
&[],
"IN=eth0 SRC=1.2.3.4".into(),
"",
None,
false,
),
("empty", &[], String::new(), "", None, false),
(
"a marker in the head",
&[],
"x".into(),
" web01 VpnTag: - ",
Some("vpn"),
false,
),
(
"a key set across both",
&[],
"IN=eth0 OUT=eth1".into(),
" SRC=1.2.3.4",
Some("netfilter"),
false,
),
(
"a key short across both",
&[],
"IN=eth0".into(),
" SRC=1",
None,
false,
),
(
"a key in both counts once",
&[],
"IN=a OUT=b".into(),
"IN=c",
None,
false,
),
(
"a verify in the head",
&[],
"100%".into(),
" %SYS-5-X: y",
Some("router"),
false,
),
(
"an id split between them",
&[],
"x %SYS-5".into(),
"-X: y",
None,
false,
),
(
"a marker split between them",
&[],
"IN=a SRC=b O".into(),
"UT=c",
None,
false,
),
(
"a cef header in the head",
&[],
"x".into(),
" CEF:0|Acme|Dns|1|",
Some("dns"),
true,
),
(
"a later cef header names it",
&[],
format!("{} {}", cef("Other", "Widget"), cef("Acme", "Dns")),
"",
Some("dns"),
true,
),
(
"a header in the head after one in the body",
&[],
cef("Other", "Widget"),
" CEF:0|Acme|Dns|1|",
Some("dns"),
true,
),
(
"a verify past the default cap names nothing",
&[],
"%".repeat(20),
"",
None,
false,
),
];
for (name, candidates, body, head, want, by_header) in rows {
let d = Detector::new(candidates);
let (body, head) = (body.as_bytes(), head.as_bytes());
assert_eq!(d.detect(body, head), want, "{name}");
if !by_header {
let best = d.set.best_spans(&[body, head], &mut d.set.scratch());
let got = best.and_then(|m| d.sources.get(m.index)).map(|s| s.0);
assert_eq!(got, want, "{name} best_spans");
}
}
}
fn pooled(sig: &Signature, spans: &[&[u8]]) -> bool {
let reads: Vec<&[u8]> = spans
.iter()
.copied()
.filter(|s| {
sig.anchored.is_empty() || sig.anchored.iter().any(|a| starts_with(s, a, sig.folded))
})
.collect();
let mut rest = sig.clone();
rest.all_of.clear();
let head = |s: &[u8]| s.len().min(sig.within.unwrap_or(usize::MAX));
!sig.is_literal_free()
&& reads.iter().any(|s| rest.may_match(s))
&& sig
.all_of
.iter()
.all(|f| reads.iter().any(|s| f.find(&s[..head(s)]).is_some()))
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1024))]
#[test]
fn one_span_is_the_one_span_call(
specs in prop::collection::vec((spec_strategy(), any::<bool>()), 1..16),
span in mixed_span(),
) {
let sigs: Vec<Signature> = specs.iter().map(|(s, f)| build_spec(s, *f, false)).collect();
let set = SignatureSet::new(&sigs).unwrap();
let mut scratch = set.scratch();
let want = matches(&set, &span, &mut scratch);
prop_assert_eq!(&matches_spans(&set, &[span.as_slice()], &mut scratch), &want);
prop_assert_eq!(set.best_spans(&[span.as_slice()], &mut scratch), set.best(&span, &mut scratch));
let index = |ms: &[SignatureMatch]| ms.iter().map(|m| m.index).collect::<Vec<_>>();
let padded = matches_spans(&set, &[span.as_slice(), &b""[..]], &mut scratch);
prop_assert_eq!(index(&padded), index(&want));
}
#[test]
fn several_spans_pool_all_of_and_verify_in_their_own_span(
specs in prop::collection::vec((spec_strategy(), any::<bool>()), 1..16),
spans in prop::collection::vec(mixed_span(), 2..4),
) {
let sigs: Vec<Signature> = specs.iter().map(|(s, f)| build_spec(s, *f, false)).collect();
let set = SignatureSet::new(&sigs).unwrap();
let spans: Vec<&[u8]> = spans.iter().map(Vec::as_slice).collect();
let mut scratch = set.scratch();
for order in [spans.clone(), spans.iter().rev().copied().collect()] {
let got = matches_spans(&set, &order, &mut scratch);
let fired: Vec<usize> = got.iter().map(|m| m.index).collect();
let want: Vec<usize> = (0..sigs.len()).filter(|&i| pooled(&sigs[i], &order)).collect();
prop_assert_eq!(&fired, &want);
for m in got {
let sig = &sigs[m.index];
let span = order[m.span];
let reads = sig.anchored.is_empty()
|| sig.anchored.iter().any(|a| starts_with(span, a, sig.folded));
prop_assert!(reads, "signature {} fired from a span it doesn't read", m.index);
if sig.any_of.is_empty() {
prop_assert_eq!(m.at, 0);
} else {
let end = span.len().min(sig.within.unwrap_or(usize::MAX));
let hit = sig.any_of.iter().any(|f| {
span.get(m.at..end)
.is_some_and(|rest| starts_with(rest, f.bytes(), sig.folded))
});
prop_assert!(hit, "signature {} at {} is no any_of hit", m.index, m.at);
}
}
}
}
}
fn every_hit_model(sig: &Signature, spans: &[&[u8]]) -> Vec<(usize, usize)> {
if !pooled(sig, spans) {
return Vec::new();
}
let mut out = Vec::new();
for (s, span) in spans.iter().enumerate() {
if !(sig.anchored.is_empty()
|| sig
.anchored
.iter()
.any(|a| starts_with(span, a, sig.folded)))
{
continue;
}
let end = span.len().min(sig.within.unwrap_or(usize::MAX));
for at in 0..end {
let hit = sig
.any_of
.iter()
.any(|f| starts_with(&span[at..end], f.bytes(), sig.folded));
if hit && sig.verify.is_none_or(|v| v(span, at)) {
out.push((s, at));
}
}
}
out
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1024))]
#[test]
fn every_hit_and_the_verify_cap_agree_with_the_model(
specs in prop::collection::vec(
(
spec_strategy(),
any::<bool>(),
any::<bool>(),
prop::sample::select(vec![None, Some(0), Some(1), Some(MAX_VERIFY)]),
),
1..16,
),
spans in prop::collection::vec(mixed_span(), 1..4),
) {
let sigs: Vec<Signature> = specs
.iter()
.map(|(spec, folded, every, cap)| {
let mut s = build_spec(spec, *folded, false);
s.every_hit = *every;
s.verify_cap = *cap;
s
})
.collect();
let set = SignatureSet::new(&sigs).unwrap();
let spans: Vec<&[u8]> = spans.iter().map(Vec::as_slice).collect();
let mut scratch = set.scratch();
let got = matches_spans(&set, &spans, &mut scratch);
let mut fired: Vec<usize> = got.iter().map(|m| m.index).collect();
fired.dedup();
let want: Vec<usize> = (0..sigs.len()).filter(|&i| pooled(&sigs[i], &spans)).collect();
prop_assert_eq!(&fired, &want);
for (i, sig) in sigs.iter().enumerate() {
let hits: Vec<(usize, usize)> =
got.iter().filter(|m| m.index == i).map(|m| (m.span, m.at)).collect();
if !sig.every_hit || sig.any_of.is_empty() {
prop_assert!(hits.len() <= 1, "signature {} reported {} hits", i, hits.len());
} else if sig.verify_cap.is_none() {
prop_assert_eq!(&hits, &every_hit_model(sig, &spans), "signature {}", i);
}
}
let one = matches(&set, spans[0], &mut scratch);
prop_assert_eq!(&one, &matches_spans(&set, &spans[..1], &mut scratch));
let mut fired: Vec<usize> = one.iter().map(|m| m.index).collect();
fired.dedup();
let alone: Vec<usize> = (0..sigs.len())
.filter(|&i| !sigs[i].is_literal_free() && sigs[i].may_match(spans[0]))
.collect();
prop_assert_eq!(fired, alone);
}
}