1use std::fmt;
9use std::net::IpAddr;
10
11use crate::ast::{ConditionExpr, Detection, DetectionItem, Modifier, Quantifier, SelectorPattern};
12use crate::emit::modifier_str;
13use crate::error::{Result, SigmaParserError};
14use crate::value::SigmaValue;
15
16use Modifier::*;
17
18const STRING_OPERATORS: [Modifier; 3] = [Contains, StartsWith, EndsWith];
19const NUMERIC_COMPARISONS: [Modifier; 4] = [Gt, Gte, Lt, Lte];
20const TIMESTAMP_PARTS: [Modifier; 6] = [Minute, Hour, Day, Week, Month, Year];
21const UTF16_ENCODINGS: [Modifier; 3] = [Wide, Utf16, Utf16be];
22const VALUE_TRANSFORMS: [Modifier; 7] =
23 [Base64, Base64Offset, Wide, Utf16, Utf16be, WindAsh, Expand];
24const REGEX_FLAGS: [Modifier; 3] = [IgnoreCase, Multiline, DotAll];
25const STRING_ONLY: [Modifier; 14] = [
26 Contains,
27 StartsWith,
28 EndsWith,
29 Base64,
30 Base64Offset,
31 Wide,
32 Utf16,
33 Utf16be,
34 WindAsh,
35 Re,
36 Cidr,
37 Expand,
38 FieldRef,
39 Cased,
40];
41
42pub fn check_modifiers(modifiers: &[Modifier]) -> std::result::Result<(), String> {
58 let has = |m: Modifier| modifiers.contains(&m);
59 let present = |set: &[Modifier]| -> Vec<&'static str> {
60 set.iter()
61 .copied()
62 .filter(|m| has(*m))
63 .map(modifier_str)
64 .collect()
65 };
66 let numeric = NUMERIC_COMPARISONS.iter().any(|m| has(*m));
67 let timestamp = TIMESTAMP_PARTS.iter().any(|m| has(*m));
68 let fieldref_conflicts = has(Re)
70 || has(Cidr)
71 || has(Exists)
72 || numeric
73 || timestamp
74 || present(&STRING_OPERATORS).len() > 1;
75
76 let mut operators = present(&[Contains, StartsWith, EndsWith, Re, Cidr, Exists]);
77 if has(FieldRef) && fieldref_conflicts {
78 operators.push("fieldref");
79 }
80 operators.extend(present(&NUMERIC_COMPARISONS));
81 operators.extend(
82 modifiers
83 .iter()
84 .filter(|m| TIMESTAMP_PARTS.contains(m))
85 .map(|m| modifier_str(*m)),
86 );
87 if has(Cased) && (has(Re) || has(Cidr) || has(Exists) || numeric || timestamp) {
88 operators.push("cased");
89 }
90 if has(FieldRef)
91 && !fieldref_conflicts
92 && let Some(name) = string_operator_before_fieldref(modifiers)
93 {
94 return Err(format!("|{name} must follow |fieldref"));
95 }
96 if operators.len() > 1 {
97 return Err(format!(
98 "at most one operator may be set per field; got |{}",
99 operators.join(", |")
100 ));
101 }
102
103 let encodings = present(&UTF16_ENCODINGS);
104 if encodings.len() > 1 {
105 return Err(format!(
106 "|wide, |utf16, and |utf16be are mutually exclusive UTF-16 encodings; got |{}",
107 encodings.join(", |")
108 ));
109 }
110 if has(Base64) && has(Base64Offset) {
111 return Err(
112 "|base64 and |base64offset are mutually exclusive base64 strategies; pick one".into(),
113 );
114 }
115
116 let non_string_operator =
117 has(Re) || has(Cidr) || has(Exists) || has(FieldRef) || numeric || timestamp;
118 let transforms = present(&VALUE_TRANSFORMS);
119 if non_string_operator && !transforms.is_empty() {
120 return Err(format!(
121 "value transformations |{} only apply to string match operators (default eq, \
122 contains, startswith, endswith) and cannot be combined with the operator that \
123 is also set on this field",
124 transforms.join(", |")
125 ));
126 }
127
128 let flags = present(®EX_FLAGS);
129 if !has(Re) && !flags.is_empty() {
130 return Err(format!(
131 "regex flag modifiers |{} have no effect without |re; case sensitivity for \
132 substring or equality matching is controlled by |cased (or its absence, which \
133 keeps the default case-insensitive behavior)",
134 flags.join(", |")
135 ));
136 }
137 if let Some(re_at) = modifiers.iter().position(|m| *m == Re)
138 && modifiers[..re_at].iter().any(|m| REGEX_FLAGS.contains(m))
139 {
140 return Err("regex flag modifiers |i, |m, and |s must follow |re".into());
141 }
142
143 Ok(())
144}
145
146fn string_operator_before_fieldref(modifiers: &[Modifier]) -> Option<&'static str> {
149 let fieldref_at = modifiers.iter().position(|m| *m == FieldRef)?;
150 modifiers[..fieldref_at]
151 .iter()
152 .find(|m| STRING_OPERATORS.contains(m))
153 .map(|m| modifier_str(*m))
154}
155
156pub fn check_cidr(cidr: &str) -> std::result::Result<(), String> {
169 let invalid = |reason: &str| format!("invalid CIDR expression '{cidr}': {reason}");
170 let (addr, prefix) = cidr
171 .split_once('/')
172 .ok_or_else(|| invalid("expected address/prefix"))?;
173 let addr: IpAddr = addr.parse().map_err(|_| invalid("invalid IP address"))?;
174 let (bits, width) = match addr {
175 IpAddr::V4(a) => (u128::from(u32::from(a)), 32),
176 IpAddr::V6(a) => (u128::from(a), 128),
177 };
178 let prefix: u32 = prefix
179 .parse()
180 .ok()
181 .filter(|p| *p <= width)
182 .ok_or_else(|| invalid("invalid prefix length"))?;
183 let host_mask = u128::MAX.checked_shr(128 - width + prefix).unwrap_or(0);
184 if bits & host_mask != 0 {
185 return Err(invalid("host bits set"));
186 }
187 Ok(())
188}
189
190pub fn check_regex(pattern: &str) -> std::result::Result<(), String> {
206 if regex_syntax::Parser::new().parse(pattern).is_ok() {
207 return Ok(());
208 }
209 fancy_regex::Regex::new(pattern)
210 .map(drop)
211 .map_err(|e| e.to_string())
212}
213
214pub fn exists_flag(value: &SigmaValue) -> Option<bool> {
216 match value {
217 SigmaValue::Bool(b) => Some(*b),
218 SigmaValue::String(_)
219 | SigmaValue::Integer(_)
220 | SigmaValue::Float(_)
221 | SigmaValue::Null => None,
222 }
223}
224
225pub fn check_detection_item(item: &DetectionItem) -> Result<()> {
228 let modifiers = &item.field.modifiers;
229 let has = |m: Modifier| modifiers.contains(&m);
230 let subject = match &item.field.name {
231 Some(name) => format!("field '{name}'"),
232 None => "keyword".to_string(),
233 };
234 let invalid = |msg: String| SigmaParserError::InvalidValue(format!("{subject}: {msg}"));
235
236 check_modifiers(modifiers)
237 .map_err(|e| SigmaParserError::InvalidModifiers(format!("{subject}: {e}")))?;
238
239 if has(Exists) {
240 if item.field.name.is_none() {
241 return Err(invalid("|exists must be applied to a field".into()));
242 }
243 return match item.values.as_slice() {
244 [SigmaValue::Bool(_)] => Ok(()),
245 _ => Err(invalid(
246 "|exists takes a single boolean value, true or false".into(),
247 )),
248 };
249 }
250 if has(All) && item.values.is_empty() {
251 return Err(SigmaParserError::InvalidModifiers(format!(
252 "{subject}: |all requires at least one value"
253 )));
254 }
255 if item.values.is_empty() && item.field.name.is_none() {
256 return Err(invalid(
257 "an empty value list must be bound to a field".into(),
258 ));
259 }
260
261 let numeric = NUMERIC_COMPARISONS
262 .iter()
263 .chain(&TIMESTAMP_PARTS)
264 .copied()
265 .find(|m| has(*m));
266 let string_only = STRING_ONLY.iter().copied().find(|m| has(*m));
267 let base64 = has(Base64) || has(Base64Offset);
268 let utf16 = UTF16_ENCODINGS.iter().any(|m| has(*m));
269
270 for value in &item.values {
271 if let Some(m) = numeric {
272 if !is_numeric(value) {
273 return Err(invalid(format!(
274 "|{} requires a numeric value, got {}",
275 modifier_str(m),
276 describe(value)
277 )));
278 }
279 continue;
280 }
281 let Some(m) = string_only else { continue };
282 let SigmaValue::String(s) = value else {
283 return Err(invalid(format!(
284 "|{} requires a string value, got {}",
285 modifier_str(m),
286 describe(value)
287 )));
288 };
289 if has(Re) {
290 check_regex(&s.original)
291 .map_err(|e| invalid(format!("invalid regular expression: {e}")))?;
292 }
293 if has(Cidr) {
294 check_cidr(&s.as_plain().unwrap_or_else(|| s.original.clone())).map_err(invalid)?;
295 }
296 if has(FieldRef) && s.contains_wildcards() {
297 return Err(invalid(
298 "a field reference must not contain wildcards".into(),
299 ));
300 }
301 if base64 && s.contains_wildcards() {
302 return Err(invalid(
303 "|base64 and |base64offset do not support wildcards; escape * and ? as \\* and \\? to match them literally".into(),
304 ));
305 }
306 if utf16 && !base64 && !s.original.is_ascii() {
307 return Err(invalid(
308 "|wide, |utf16, and |utf16be without |base64 or |base64offset require an ASCII value".into(),
309 ));
310 }
311 }
312 Ok(())
313}
314
315fn is_numeric(value: &SigmaValue) -> bool {
316 matches!(value, SigmaValue::Integer(_) | SigmaValue::Float(_))
317}
318
319fn describe(value: &SigmaValue) -> String {
320 match value {
321 SigmaValue::String(s) => format!("'{s}'"),
322 other => other.to_string(),
323 }
324}
325
326pub(crate) fn check_detection(name: &str, detection: &Detection) -> Result<()> {
329 let invalid = |msg: &str| SigmaParserError::InvalidDetection(format!("'{name}' {msg}"));
330 match detection {
331 Detection::AllOf(items) if items.is_empty() => Err(invalid("is empty")),
332 Detection::AllOf(_) => Ok(()),
333 Detection::AnyOf(subs) | Detection::And(subs) => {
334 if subs.is_empty() {
335 return Err(invalid("is empty"));
336 }
337 subs.iter().try_for_each(|d| check_detection(name, d))
338 }
339 Detection::Keywords(values) => {
340 if values.is_empty() {
341 return Err(invalid("is empty"));
342 }
343 if values.iter().any(|v| matches!(v, SigmaValue::Null)) {
344 return Err(invalid(
345 "uses null as a keyword; keywords match text anywhere in the event",
346 ));
347 }
348 Ok(())
349 }
350 Detection::ArrayMatch { body, .. } => check_detection(name, body),
351 Detection::Conditional { named, condition } => {
352 for (sub_name, sub) in named {
353 check_detection(sub_name, sub)?;
354 }
355 let names: Vec<&str> = named.keys().map(String::as_str).collect();
356 check_condition(condition, &names)
357 }
358 }
359}
360
361pub(crate) fn check_condition(expr: &ConditionExpr, names: &[&str]) -> Result<()> {
364 match unresolved_references(expr, names).first() {
365 None => Ok(()),
366 Some(unresolved) => Err(SigmaParserError::InvalidDetection(unresolved.to_string())),
367 }
368}
369
370pub(crate) enum Unresolved<'a> {
372 Identifier(&'a str),
374 Selector {
376 quantifier: &'a Quantifier,
377 pattern: &'a SelectorPattern,
378 },
379}
380
381impl fmt::Display for Unresolved<'_> {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 match self {
384 Unresolved::Identifier(id) => {
385 write!(
386 f,
387 "condition references unknown detection identifier '{id}'"
388 )
389 }
390 Unresolved::Selector {
391 quantifier,
392 pattern,
393 } => write!(
394 f,
395 "selector '{quantifier} of {pattern}' matches no detection identifier"
396 ),
397 }
398 }
399}
400
401pub(crate) fn unresolved_references<'a>(
403 expr: &'a ConditionExpr,
404 names: &[&str],
405) -> Vec<Unresolved<'a>> {
406 let mut out = Vec::new();
407 collect_unresolved(expr, names, &mut out);
408 out
409}
410
411fn collect_unresolved<'a>(expr: &'a ConditionExpr, names: &[&str], out: &mut Vec<Unresolved<'a>>) {
412 match expr {
413 ConditionExpr::And(exprs) | ConditionExpr::Or(exprs) => {
414 exprs.iter().for_each(|e| collect_unresolved(e, names, out))
415 }
416 ConditionExpr::Not(inner) => collect_unresolved(inner, names, out),
417 ConditionExpr::Identifier(id) => {
418 if !names.contains(&id.as_str()) {
419 out.push(Unresolved::Identifier(id));
420 }
421 }
422 ConditionExpr::Selector {
423 quantifier,
424 pattern,
425 } => {
426 if !names.iter().any(|n| pattern.matches_detection_name(n)) {
427 out.push(Unresolved::Selector {
428 quantifier,
429 pattern,
430 });
431 }
432 }
433 }
434}