1use std::collections::BTreeMap;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8use crate::ast::{Level, Status};
9
10#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
13#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
14pub struct RulesetSpec {
15 #[serde(default, skip_serializing_if = "Option::is_none")]
17 pub description: Option<String>,
18 pub sources: Vec<PathBuf>,
20 #[serde(default, skip_serializing_if = "Vec::is_empty")]
22 pub include: Vec<RuleSelector>,
23 #[serde(default, skip_serializing_if = "Vec::is_empty")]
25 pub exclude: Vec<RuleSelector>,
26 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub dependencies: Option<String>,
30 #[serde(default, skip_serializing_if = "Vec::is_empty")]
32 pub overlays: Vec<OverlayEntry>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub stale_overlays: Option<String>,
36 #[serde(default, skip_serializing_if = "Vec::is_empty")]
38 pub pipelines: Vec<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub output: Option<PathBuf>,
42 #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
44 pub unknown: BTreeMap<String, serde_json::Value>,
45}
46
47#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
50#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
51pub struct RuleSelector {
52 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub id: Vec<String>,
55 #[serde(default, skip_serializing_if = "Vec::is_empty")]
57 pub name: Vec<String>,
58 #[serde(default, skip_serializing_if = "Vec::is_empty")]
60 pub title: Vec<String>,
61 #[serde(default, skip_serializing_if = "Vec::is_empty")]
63 pub tags: Vec<String>,
64 #[serde(default, skip_serializing_if = "Vec::is_empty")]
66 pub level: Vec<String>,
67 #[serde(default, skip_serializing_if = "Vec::is_empty")]
69 pub status: Vec<String>,
70 #[serde(default, skip_serializing_if = "Vec::is_empty")]
72 pub kind: Vec<String>,
73 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 pub path: Vec<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub logsource: Option<LogsourceSelector>,
80 #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
82 pub unknown: BTreeMap<String, serde_json::Value>,
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
87#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
88pub struct LogsourceSelector {
89 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 pub product: Vec<String>,
92 #[serde(default, skip_serializing_if = "Vec::is_empty")]
94 pub category: Vec<String>,
95 #[serde(default, skip_serializing_if = "Vec::is_empty")]
97 pub service: Vec<String>,
98 #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
100 pub unknown: BTreeMap<String, serde_json::Value>,
101}
102
103#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
106#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
107pub struct OverlayEntry {
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub id: Option<String>,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub file: Option<PathBuf>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub dir: Option<PathBuf>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub set: Option<OverlayPatch>,
120 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub append: Option<OverlayPatch>,
123 #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
125 pub unknown: BTreeMap<String, serde_json::Value>,
126}
127
128#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
130#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
131pub struct OverlayPatch {
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub level: Option<String>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub status: Option<String>,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub description: Option<String>,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub author: Option<String>,
144 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub tags: Option<Vec<String>>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub references: Option<Vec<String>>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub falsepositives: Option<Vec<String>>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub fields: Option<Vec<String>>,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub custom_attributes: Option<BTreeMap<String, serde_json::Value>>,
159 #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
161 pub unknown: BTreeMap<String, serde_json::Value>,
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum DependencyPolicy {
167 Error,
169 Include,
171 Drop,
173}
174
175impl DependencyPolicy {
176 pub fn parse(value: &str) -> Result<Self, String> {
178 match value {
179 "error" => Ok(Self::Error),
180 "include" => Ok(Self::Include),
181 "drop" => Ok(Self::Drop),
182 other => Err(format!(
183 "invalid dependencies policy '{other}'; expected error, include, or drop"
184 )),
185 }
186 }
187
188 pub fn as_str(&self) -> &'static str {
190 match self {
191 Self::Error => "error",
192 Self::Include => "include",
193 Self::Drop => "drop",
194 }
195 }
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub enum StaleOverlayPolicy {
201 Error,
203 Warn,
205}
206
207impl StaleOverlayPolicy {
208 pub fn parse(value: &str) -> Result<Self, String> {
210 match value {
211 "error" => Ok(Self::Error),
212 "warn" => Ok(Self::Warn),
213 other => Err(format!(
214 "invalid stale_overlays policy '{other}'; expected error or warn"
215 )),
216 }
217 }
218
219 pub fn as_str(&self) -> &'static str {
221 match self {
222 Self::Error => "error",
223 Self::Warn => "warn",
224 }
225 }
226}
227
228pub fn validate_ruleset_name(name: &str) -> Result<(), String> {
230 let mut chars = name.chars();
231 match chars.next() {
232 Some(c) if c.is_ascii_lowercase() => {}
233 _ => {
234 return Err(format!(
235 "invalid ruleset name '{name}': must start with a-z"
236 ));
237 }
238 }
239 if name.len() > 64 {
240 return Err(format!(
241 "invalid ruleset name '{name}': at most 64 characters"
242 ));
243 }
244 if !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-') {
245 return Err(format!(
246 "invalid ruleset name '{name}': use only a-z, 0-9, '_' and '-'"
247 ));
248 }
249 Ok(())
250}
251
252pub(crate) const SET_KEYS: &[&str] = &[
253 "level",
254 "status",
255 "description",
256 "author",
257 "tags",
258 "references",
259 "falsepositives",
260 "fields",
261 "custom_attributes",
262];
263pub(crate) const APPEND_KEYS: &[&str] = &[
264 "tags",
265 "references",
266 "falsepositives",
267 "fields",
268 "custom_attributes",
269];
270
271pub fn validate_spec(name: &str, spec: &RulesetSpec) -> Vec<String> {
274 let mut problems = Vec::new();
275
276 if let Err(e) = validate_ruleset_name(name) {
277 problems.push(e);
278 }
279 if spec.sources.is_empty() {
280 problems.push(format!("ruleset '{name}': sources must not be empty"));
281 }
282 if let Some(policy) = &spec.dependencies
283 && let Err(e) = DependencyPolicy::parse(policy)
284 {
285 problems.push(format!("ruleset '{name}': {e}"));
286 }
287 if let Some(policy) = &spec.stale_overlays
288 && let Err(e) = StaleOverlayPolicy::parse(policy)
289 {
290 problems.push(format!("ruleset '{name}': {e}"));
291 }
292 for key in spec.unknown.keys() {
293 problems.push(format!(
294 "ruleset '{name}': unknown key '{key}'{}",
295 suggestion(
296 key,
297 &[
298 "description",
299 "sources",
300 "include",
301 "exclude",
302 "dependencies",
303 "overlays",
304 "stale_overlays",
305 "pipelines",
306 "output",
307 ]
308 )
309 ));
310 }
311 for pipeline in &spec.pipelines {
312 if pipeline.trim().is_empty() {
313 problems.push(format!(
314 "ruleset '{name}': pipelines must not contain an empty name"
315 ));
316 }
317 }
318
319 for (index, selector) in spec.include.iter().enumerate() {
320 validate_selector(
321 name,
322 selector,
323 true,
324 &format!("include[{index}]"),
325 &mut problems,
326 );
327 }
328 for (index, selector) in spec.exclude.iter().enumerate() {
329 validate_selector(
330 name,
331 selector,
332 false,
333 &format!("exclude[{index}]"),
334 &mut problems,
335 );
336 }
337 for (index, entry) in spec.overlays.iter().enumerate() {
338 validate_overlay_entry(name, entry, &format!("overlays[{index}]"), &mut problems);
339 }
340
341 problems
342}
343
344fn validate_selector(
345 ruleset: &str,
346 selector: &RuleSelector,
347 is_include: bool,
348 at: &str,
349 problems: &mut Vec<String>,
350) {
351 if selector.id.is_empty()
352 && selector.name.is_empty()
353 && selector.title.is_empty()
354 && selector.tags.is_empty()
355 && selector.level.is_empty()
356 && selector.status.is_empty()
357 && selector.kind.is_empty()
358 && selector.path.is_empty()
359 && selector.logsource.is_none()
360 {
361 problems.push(format!("ruleset '{ruleset}': {at} sets no key"));
362 }
363 for key in selector.unknown.keys() {
364 problems.push(format!(
365 "ruleset '{ruleset}': {at} has unknown key '{key}'{}",
366 suggestion(
367 key,
368 &[
369 "id",
370 "name",
371 "title",
372 "tags",
373 "level",
374 "status",
375 "kind",
376 "logsource",
377 "path",
378 ]
379 )
380 ));
381 }
382 for value in &selector.level {
383 if value.parse::<Level>().is_err() {
384 problems.push(format!(
385 "ruleset '{ruleset}': {at}.level has unknown level '{value}'"
386 ));
387 }
388 }
389 for value in &selector.status {
390 if value.parse::<Status>().is_err() {
391 problems.push(format!(
392 "ruleset '{ruleset}': {at}.status has unknown status '{value}'"
393 ));
394 }
395 }
396 for value in &selector.kind {
397 if !matches!(value.as_str(), "detection" | "correlation" | "filter") {
398 problems.push(format!(
399 "ruleset '{ruleset}': {at}.kind has unknown kind '{value}'"
400 ));
401 }
402 if is_include && value == "filter" {
403 problems.push(format!(
404 "ruleset '{ruleset}': {at}.kind must not include 'filter'; filters follow their targets"
405 ));
406 }
407 }
408 for value in &selector.title {
409 if let Err(e) = globset::GlobBuilder::new(value)
410 .case_insensitive(true)
411 .build()
412 {
413 problems.push(format!(
414 "ruleset '{ruleset}': {at}.title has invalid glob '{value}': {e}"
415 ));
416 }
417 }
418 for value in &selector.tags {
419 if let Err(e) = globset::GlobBuilder::new(value)
420 .case_insensitive(true)
421 .build()
422 {
423 problems.push(format!(
424 "ruleset '{ruleset}': {at}.tags has invalid glob '{value}': {e}"
425 ));
426 }
427 }
428 for value in &selector.path {
429 if let Err(e) = globset::GlobBuilder::new(value)
430 .literal_separator(true)
431 .build()
432 {
433 problems.push(format!(
434 "ruleset '{ruleset}': {at}.path has invalid glob '{value}': {e}"
435 ));
436 }
437 }
438 if let Some(logsource) = &selector.logsource {
439 if logsource.product.is_empty()
440 && logsource.category.is_empty()
441 && logsource.service.is_empty()
442 {
443 problems.push(format!("ruleset '{ruleset}': {at}.logsource sets no key"));
444 }
445 for key in logsource.unknown.keys() {
446 problems.push(format!(
447 "ruleset '{ruleset}': {at}.logsource has unknown key '{key}'{}",
448 suggestion(key, &["product", "category", "service"])
449 ));
450 }
451 }
452}
453
454fn validate_overlay_entry(
455 ruleset: &str,
456 entry: &OverlayEntry,
457 at: &str,
458 problems: &mut Vec<String>,
459) {
460 for key in entry.unknown.keys() {
461 problems.push(format!(
462 "ruleset '{ruleset}': {at} has unknown key '{key}'{}",
463 suggestion(key, &["id", "file", "dir", "set", "append"])
464 ));
465 }
466 let forms = [
467 entry.id.is_some(),
468 entry.file.is_some(),
469 entry.dir.is_some(),
470 ]
471 .into_iter()
472 .filter(|set| *set)
473 .count();
474 if forms != 1 {
475 problems.push(format!(
476 "ruleset '{ruleset}': {at} must set exactly one of id, file, or dir"
477 ));
478 return;
479 }
480 if entry.file.is_some() || entry.dir.is_some() {
481 if entry.set.is_some() || entry.append.is_some() {
482 problems.push(format!(
483 "ruleset '{ruleset}': {at} must not combine file or dir with set or append"
484 ));
485 }
486 return;
487 }
488 if entry.set.is_none() && entry.append.is_none() {
489 problems.push(format!(
490 "ruleset '{ruleset}': {at} needs at least one of set or append"
491 ));
492 }
493 if let Some(patch) = &entry.set {
494 validate_patch(ruleset, patch, at, "set", SET_KEYS, problems);
495 for value in patch.level.iter() {
496 if value.parse::<Level>().is_err() {
497 problems.push(format!(
498 "ruleset '{ruleset}': {at}.set has unknown level '{value}'"
499 ));
500 }
501 }
502 for value in patch.status.iter() {
503 if value.parse::<Status>().is_err() {
504 problems.push(format!(
505 "ruleset '{ruleset}': {at}.set has unknown status '{value}'"
506 ));
507 }
508 }
509 }
510 if let Some(patch) = &entry.append {
511 validate_patch(ruleset, patch, at, "append", APPEND_KEYS, problems);
512 if patch.level.is_some() {
513 problems.push(format!(
514 "ruleset '{ruleset}': {at}.append cannot set 'level'; use set"
515 ));
516 }
517 if patch.status.is_some() {
518 problems.push(format!(
519 "ruleset '{ruleset}': {at}.append cannot set 'status'; use set"
520 ));
521 }
522 if patch.description.is_some() {
523 problems.push(format!(
524 "ruleset '{ruleset}': {at}.append cannot set 'description'; use set"
525 ));
526 }
527 if patch.author.is_some() {
528 problems.push(format!(
529 "ruleset '{ruleset}': {at}.append cannot set 'author'; use set"
530 ));
531 }
532 }
533}
534
535const ENGINE_CORRELATION_KEYS: &[&str] = &["rsigma.window", "rsigma.gap"];
538
539pub(crate) fn validate_patch(
544 ruleset: &str,
545 patch: &OverlayPatch,
546 at: &str,
547 form: &str,
548 allowed: &[&str],
549 problems: &mut Vec<String>,
550) {
551 for key in patch.unknown.keys() {
552 problems.push(format!(
553 "ruleset '{ruleset}': {at}.{form} has unknown key '{key}'{}",
554 suggestion(key, allowed)
555 ));
556 }
557 let empty = patch.level.is_none()
558 && patch.status.is_none()
559 && patch.description.is_none()
560 && patch.author.is_none()
561 && patch.tags.is_none()
562 && patch.references.is_none()
563 && patch.falsepositives.is_none()
564 && patch.fields.is_none()
565 && patch
566 .custom_attributes
567 .as_ref()
568 .is_none_or(BTreeMap::is_empty)
569 && patch.unknown.is_empty();
570 if empty {
571 problems.push(format!("ruleset '{ruleset}': {at}.{form} is empty"));
572 }
573 for key in patch.custom_attributes.iter().flat_map(BTreeMap::keys) {
574 let reserved = [
575 crate::parser::STANDARD_RULE_KEYS,
576 crate::parser::STANDARD_CORRELATION_KEYS,
577 crate::parser::STANDARD_FILTER_KEYS,
578 ENGINE_CORRELATION_KEYS,
579 ]
580 .iter()
581 .any(|keys| keys.contains(&key.as_str()));
582 if reserved {
583 problems.push(format!(
584 "ruleset '{ruleset}': {at}.{form}.custom_attributes cannot set '{key}', a standard Sigma or engine key"
585 ));
586 }
587 }
588}
589
590pub(crate) fn suggestion(key: &str, known: &[&str]) -> String {
592 let mut best: Option<(usize, &str)> = None;
593 for candidate in known {
594 let distance = edit_distance(key, candidate);
595 if distance <= 2 && best.is_none_or(|(d, _)| distance < d) {
596 best = Some((distance, candidate));
597 }
598 }
599 match best {
600 Some((_, candidate)) => format!(" (did you mean '{candidate}'?)"),
601 None => String::new(),
602 }
603}
604
605fn edit_distance(a: &str, b: &str) -> usize {
606 let a: Vec<char> = a.chars().collect();
607 let b: Vec<char> = b.chars().collect();
608 let mut previous: Vec<usize> = (0..=b.len()).collect();
609 for (i, ca) in a.iter().enumerate() {
610 let mut current = vec![i + 1; b.len() + 1];
611 for (j, cb) in b.iter().enumerate() {
612 let substitution = previous[j] + usize::from(ca != cb);
613 current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
614 }
615 previous = current;
616 }
617 previous[b.len()]
618}
619
620#[cfg(test)]
621mod tests {
622 use super::*;
623
624 #[test]
625 fn validates_names() {
626 assert!(validate_ruleset_name("linux_edge").is_ok());
627 assert!(validate_ruleset_name("a").is_ok());
628 assert!(validate_ruleset_name("Linux").is_err());
629 assert!(validate_ruleset_name("9lives").is_err());
630 assert!(validate_ruleset_name("has space").is_err());
631 }
632
633 #[test]
634 fn reports_unknown_keys_with_suggestion() {
635 let spec: RulesetSpec =
636 yaml_serde::from_str("sources: [rules]\ninclude:\n - tag: [attack.t1059]\n").unwrap();
637 let problems = validate_spec("test", &spec);
638 assert!(
639 problems
640 .iter()
641 .any(|p| p.contains("unknown key 'tag'") && p.contains("did you mean 'tags'")),
642 "{problems:?}"
643 );
644 }
645
646 #[test]
647 fn rejects_empty_sources_and_selectors() {
648 let spec = RulesetSpec::default();
649 let problems = validate_spec("test", &spec);
650 assert!(
651 problems
652 .iter()
653 .any(|p| p.contains("sources must not be empty"))
654 );
655
656 let spec = RulesetSpec {
657 sources: vec![PathBuf::from("rules")],
658 include: vec![RuleSelector::default()],
659 ..Default::default()
660 };
661 let problems = validate_spec("test", &spec);
662 assert!(problems.iter().any(|p| p.contains("sets no key")));
663 }
664
665 #[test]
666 fn rejects_filter_in_include() {
667 let spec = RulesetSpec {
668 sources: vec![PathBuf::from("rules")],
669 include: vec![RuleSelector {
670 kind: vec!["filter".into()],
671 ..Default::default()
672 }],
673 ..Default::default()
674 };
675 let problems = validate_spec("test", &spec);
676 assert!(
677 problems
678 .iter()
679 .any(|p| p.contains("must not include 'filter'"))
680 );
681 }
682
683 #[test]
684 fn rejects_invalid_glob_and_enum() {
685 let spec = RulesetSpec {
686 sources: vec![PathBuf::from("rules")],
687 include: vec![RuleSelector {
688 tags: vec!["[".into()],
689 level: vec!["severe".into()],
690 ..Default::default()
691 }],
692 dependencies: Some("ignore".into()),
693 ..Default::default()
694 };
695 let problems = validate_spec("test", &spec);
696 assert!(problems.iter().any(|p| p.contains("invalid glob")));
697 assert!(problems.iter().any(|p| p.contains("unknown level")));
698 assert!(problems.iter().any(|p| p.contains("dependencies policy")));
699 }
700
701 #[test]
702 fn rejects_malformed_overlay_entries() {
703 let spec = RulesetSpec {
704 sources: vec![PathBuf::from("rules")],
705 overlays: vec![
706 OverlayEntry::default(),
707 OverlayEntry {
708 id: Some("x".into()),
709 file: Some(PathBuf::from("y.yml")),
710 ..Default::default()
711 },
712 OverlayEntry {
713 file: Some(PathBuf::from("y.yml")),
714 set: Some(OverlayPatch::default()),
715 ..Default::default()
716 },
717 OverlayEntry {
718 id: Some("x".into()),
719 ..Default::default()
720 },
721 OverlayEntry {
722 id: Some("x".into()),
723 append: Some(OverlayPatch {
724 level: Some("high".into()),
725 ..Default::default()
726 }),
727 ..Default::default()
728 },
729 ],
730 ..Default::default()
731 };
732 let problems = validate_spec("test", &spec);
733 assert!(
734 problems
735 .iter()
736 .any(|p| p.contains("exactly one of id, file, or dir"))
737 );
738 assert!(problems.iter().any(|p| p.contains("must not combine")));
739 assert!(
740 problems
741 .iter()
742 .any(|p| p.contains("at least one of set or append"))
743 );
744 assert!(problems.iter().any(|p| p.contains("cannot set 'level'")));
745 }
746
747 #[test]
748 fn rejects_empty_patches() {
749 let spec: RulesetSpec = yaml_serde::from_str(
750 "sources: [rules]\noverlays:\n - id: x\n set: {}\n - id: y\n append:\n custom_attributes: {}\n",
751 )
752 .unwrap();
753 let problems = validate_spec("test", &spec);
754 assert!(
755 problems
756 .iter()
757 .any(|p| p.ends_with("overlays[0].set is empty")),
758 "{problems:?}"
759 );
760 assert!(
761 problems
762 .iter()
763 .any(|p| p.ends_with("overlays[1].append is empty")),
764 "{problems:?}"
765 );
766 }
767
768 #[test]
769 fn rejects_custom_attributes_that_shadow_standard_keys() {
770 for key in [
771 "title",
772 "id",
773 "level",
774 "logsource",
775 "detection",
776 "correlation",
777 "filter",
778 "custom_attributes",
779 "rsigma.window",
780 "rsigma.gap",
781 ] {
782 let spec: RulesetSpec = yaml_serde::from_str(&format!(
783 "sources: [rules]\noverlays:\n - id: x\n set:\n custom_attributes:\n {key}: v\n - id: y\n append:\n custom_attributes:\n {key}: [v]\n"
784 ))
785 .unwrap();
786 let problems = validate_spec("test", &spec);
787 let shadowing = problems
788 .iter()
789 .filter(|p| p.contains(&format!("custom_attributes cannot set '{key}'")))
790 .count();
791 assert_eq!(shadowing, 2, "{key}: {problems:?}");
792 }
793
794 let spec: RulesetSpec = yaml_serde::from_str(
795 "sources: [rules]\noverlays:\n - id: x\n set:\n custom_attributes:\n rsigma.suppress: 5m\n team: blue\n",
796 )
797 .unwrap();
798 assert!(validate_spec("test", &spec).is_empty());
799 }
800}