1use std::collections::HashSet;
4use std::path::{Component, Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::ast::{CorrelationRule, FilterRule, FilterRuleTarget, LogSource, SigmaRule};
9use crate::diagnostic::CollectionDiagnostic;
10
11use super::error::RulesetError;
12use super::spec::RulesetSpec;
13
14#[derive(Debug, Clone, Default)]
16pub struct ResolveOptions {
17 pub confine_to: Option<PathBuf>,
20}
21
22#[derive(Debug, Clone, PartialEq)]
24pub struct Candidate {
25 pub doc: CandidateDoc,
27 pub origin: RuleOrigin,
29}
30
31#[derive(Debug, Clone, PartialEq)]
33pub enum CandidateDoc {
34 Detection(SigmaRule),
36 Correlation(CorrelationRule),
38 Filter(FilterRule),
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct RuleOrigin {
45 pub source: usize,
47 pub root: PathBuf,
49 pub file: PathBuf,
51 pub ordinal: usize,
53}
54
55#[derive(Debug, Clone, PartialEq)]
57pub struct SourceFile {
58 pub source: usize,
60 pub path: PathBuf,
62 pub relative: PathBuf,
65 pub sha256_input: Vec<u8>,
67}
68
69#[derive(Debug, Clone, Default)]
71pub struct LoadedSources {
72 pub candidates: Vec<Candidate>,
74 pub files: Vec<SourceFile>,
76 pub diagnostics: Vec<CollectionDiagnostic>,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub enum DocumentKind {
84 Detection,
86 Correlation,
88 Filter,
90}
91
92impl DocumentKind {
93 pub fn as_str(&self) -> &'static str {
95 match self {
96 Self::Detection => "detection",
97 Self::Correlation => "correlation",
98 Self::Filter => "filter",
99 }
100 }
101}
102
103impl Candidate {
104 pub fn kind(&self) -> DocumentKind {
106 match self.doc {
107 CandidateDoc::Detection(_) => DocumentKind::Detection,
108 CandidateDoc::Correlation(_) => DocumentKind::Correlation,
109 CandidateDoc::Filter(_) => DocumentKind::Filter,
110 }
111 }
112
113 pub fn id(&self) -> Option<&str> {
115 match &self.doc {
116 CandidateDoc::Detection(rule) => rule.id.as_deref(),
117 CandidateDoc::Correlation(rule) => rule.id.as_deref(),
118 CandidateDoc::Filter(rule) => rule.id.as_deref(),
119 }
120 }
121
122 pub fn name(&self) -> Option<&str> {
124 match &self.doc {
125 CandidateDoc::Detection(rule) => rule.name.as_deref(),
126 CandidateDoc::Correlation(rule) => rule.name.as_deref(),
127 CandidateDoc::Filter(rule) => rule.name.as_deref(),
128 }
129 }
130
131 pub fn title(&self) -> &str {
133 match &self.doc {
134 CandidateDoc::Detection(rule) => &rule.title,
135 CandidateDoc::Correlation(rule) => &rule.title,
136 CandidateDoc::Filter(rule) => &rule.title,
137 }
138 }
139
140 pub fn logsource(&self) -> Option<&LogSource> {
142 match &self.doc {
143 CandidateDoc::Detection(rule) => Some(&rule.logsource),
144 CandidateDoc::Correlation(_) => None,
145 CandidateDoc::Filter(rule) => rule.logsource.as_ref(),
146 }
147 }
148
149 pub fn tags(&self) -> &[String] {
151 match &self.doc {
152 CandidateDoc::Detection(rule) => &rule.tags,
153 CandidateDoc::Correlation(rule) => &rule.tags,
154 CandidateDoc::Filter(rule) => &rule.tags,
155 }
156 }
157
158 pub fn level(&self) -> Option<crate::ast::Level> {
160 match &self.doc {
161 CandidateDoc::Detection(rule) => rule.level,
162 CandidateDoc::Correlation(rule) => rule.level,
163 CandidateDoc::Filter(rule) => rule.level,
164 }
165 }
166
167 pub fn status(&self) -> Option<crate::ast::Status> {
169 match &self.doc {
170 CandidateDoc::Detection(rule) => rule.status,
171 CandidateDoc::Correlation(rule) => rule.status,
172 CandidateDoc::Filter(rule) => rule.status,
173 }
174 }
175
176 pub fn referenced_rules(&self) -> &[String] {
178 match &self.doc {
179 CandidateDoc::Correlation(rule) => &rule.rules,
180 _ => &[],
181 }
182 }
183
184 pub fn filter_targets(&self) -> Option<&[String]> {
186 match &self.doc {
187 CandidateDoc::Filter(rule) => match &rule.rules {
188 FilterRuleTarget::Any => None,
189 FilterRuleTarget::Specific(targets) => Some(targets),
190 },
191 _ => None,
192 }
193 }
194}
195
196pub fn load_sources(
199 spec: &RulesetSpec,
200 opts: &ResolveOptions,
201) -> Result<LoadedSources, RulesetError> {
202 let mut loaded = LoadedSources::default();
203
204 for (source_index, source) in spec.sources.iter().enumerate() {
205 if !source.exists() {
206 return Err(RulesetError::MissingSource {
207 ruleset: None,
208 path: source.clone(),
209 });
210 }
211 let root = if source.is_dir() {
212 source.clone()
213 } else {
214 source
215 .parent()
216 .map(Path::to_path_buf)
217 .unwrap_or_else(|| PathBuf::from("."))
218 };
219
220 let mut paths = Vec::new();
221 if source.is_dir() {
222 let mut visited = HashSet::new();
225 crate::walk::collect_yaml_files(&root, &root, None, &mut paths, &mut visited).map_err(
226 |e| RulesetError::Io {
227 ruleset: None,
228 path: root.clone(),
229 source: std::io::Error::other(e.to_string()),
230 },
231 )?;
232 } else {
233 paths.push(source.clone());
234 }
235
236 for path in paths {
237 let canonical = path.canonicalize().map_err(|e| RulesetError::Io {
238 ruleset: None,
239 path: path.clone(),
240 source: e,
241 })?;
242 confine(&canonical, opts)?;
243
244 let bytes = std::fs::read(&path).map_err(|e| RulesetError::Io {
245 ruleset: None,
246 path: path.clone(),
247 source: e,
248 })?;
249 let text = String::from_utf8_lossy(&bytes);
250 let relative = relative_to(&path, &root);
251 let mut collection = match crate::parse_sigma_yaml(&text) {
252 Ok(collection) => collection,
253 Err(e) => {
254 loaded
255 .diagnostics
256 .push(CollectionDiagnostic::file(&path, &e));
257 continue;
258 }
259 };
260 for diagnostic in &mut collection.diagnostics {
261 diagnostic.path = Some(path.clone());
262 }
263 loaded.diagnostics.extend(collection.diagnostics);
264
265 loaded.files.push(SourceFile {
266 source: source_index,
267 path: path.clone(),
268 relative: relative.clone(),
269 sha256_input: bytes,
270 });
271
272 for (ordinal, rule) in collection.rules.into_iter().enumerate() {
273 loaded.candidates.push(Candidate {
274 doc: CandidateDoc::Detection(rule),
275 origin: RuleOrigin {
276 source: source_index,
277 root: root.clone(),
278 file: relative.clone(),
279 ordinal,
280 },
281 });
282 }
283 for (ordinal, rule) in collection.correlations.into_iter().enumerate() {
284 loaded.candidates.push(Candidate {
285 doc: CandidateDoc::Correlation(rule),
286 origin: RuleOrigin {
287 source: source_index,
288 root: root.clone(),
289 file: relative.clone(),
290 ordinal,
291 },
292 });
293 }
294 for (ordinal, rule) in collection.filters.into_iter().enumerate() {
295 loaded.candidates.push(Candidate {
296 doc: CandidateDoc::Filter(rule),
297 origin: RuleOrigin {
298 source: source_index,
299 root: root.clone(),
300 file: relative.clone(),
301 ordinal,
302 },
303 });
304 }
305 }
306 }
307
308 Ok(loaded)
309}
310
311pub(crate) fn confine(path: &Path, opts: &ResolveOptions) -> Result<(), RulesetError> {
313 let Some(root) = &opts.confine_to else {
314 return Ok(());
315 };
316 let root = root.canonicalize().map_err(|e| RulesetError::Io {
317 ruleset: None,
318 path: root.clone(),
319 source: e,
320 })?;
321 if path.starts_with(&root) {
322 Ok(())
323 } else {
324 Err(RulesetError::Confinement {
325 ruleset: None,
326 path: path.to_path_buf(),
327 })
328 }
329}
330
331pub(crate) fn relative_to(path: &Path, root: &Path) -> PathBuf {
333 let relative = path.strip_prefix(root).unwrap_or(path);
334 let mut out = PathBuf::new();
335 for component in relative.components() {
336 match component {
337 Component::Normal(part) => out.push(part),
338 Component::CurDir => {}
339 Component::ParentDir => out.push(".."),
340 Component::RootDir | Component::Prefix(_) => {}
341 }
342 }
343 let text = out
344 .components()
345 .filter_map(|component| match component {
346 Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
347 _ => None,
348 })
349 .collect::<Vec<_>>()
350 .join("/");
351 PathBuf::from(text)
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 fn write(path: &Path, contents: &str) {
359 if let Some(parent) = path.parent() {
360 std::fs::create_dir_all(parent).unwrap();
361 }
362 std::fs::write(path, contents).unwrap();
363 }
364
365 fn rule(id: &str, title: &str) -> String {
366 format!(
367 "title: {title}\nid: {id}\nlogsource:\n product: linux\ndetection:\n selection:\n Field: value\n condition: selection\n"
368 )
369 }
370
371 #[test]
372 fn walks_nested_directories_in_sorted_order() {
373 let dir = tempfile::tempdir().unwrap();
374 let root = dir.path();
375 write(&root.join("rules/b.yml"), &rule("b", "B"));
376 write(&root.join("rules/a/z.yml"), &rule("z", "Z"));
377 write(&root.join("rules/a/a.yml"), &rule("a", "A"));
378 write(&root.join("rules/.hidden/c.yml"), &rule("c", "C"));
379
380 let spec = RulesetSpec {
381 sources: vec![root.join("rules")],
382 ..Default::default()
383 };
384 let loaded = load_sources(&spec, &ResolveOptions::default()).unwrap();
385 let files: Vec<String> = loaded
386 .files
387 .iter()
388 .map(|f| f.relative.to_string_lossy().into_owned())
389 .collect();
390 assert_eq!(files, ["a/a.yml", "a/z.yml", "b.yml"], "{files:?}");
391 assert_eq!(loaded.candidates.len(), 3);
392 assert_eq!(loaded.candidates[0].origin.ordinal, 0);
393 assert_eq!(loaded.candidates[1].origin.ordinal, 0);
394 assert_eq!(loaded.candidates[2].origin.ordinal, 0);
395 }
396
397 #[test]
398 fn overlapping_sources_load_the_same_files_in_either_order() {
399 let dir = tempfile::tempdir().unwrap();
400 let root = dir.path();
401 write(&root.join("rules/windows/w.yml"), &rule("w", "W"));
402 write(&root.join("rules/l.yml"), &rule("l", "L"));
403 for sources in [
404 vec![root.join("rules"), root.join("rules/windows")],
405 vec![root.join("rules/windows"), root.join("rules")],
406 ] {
407 let spec = RulesetSpec {
408 sources,
409 ..Default::default()
410 };
411 let loaded = load_sources(&spec, &ResolveOptions::default()).unwrap();
412 let per_source: Vec<usize> = (0..2)
413 .map(|index| {
414 loaded
415 .candidates
416 .iter()
417 .filter(|c| c.origin.source == index)
418 .count()
419 })
420 .collect();
421 let windows_first = spec.sources[0].ends_with("windows");
422 let expected = if windows_first { [1, 2] } else { [2, 1] };
423 assert_eq!(per_source, expected, "{:?}", spec.sources);
424 }
425 }
426
427 #[test]
428 fn reads_a_file_source_with_any_extension() {
429 let dir = tempfile::tempdir().unwrap();
430 let path = dir.path().join("rule.txt");
431 write(&path, &rule("x", "X"));
432 let spec = RulesetSpec {
433 sources: vec![path.clone()],
434 ..Default::default()
435 };
436 let loaded = load_sources(&spec, &ResolveOptions::default()).unwrap();
437 assert_eq!(loaded.candidates.len(), 1);
438 assert_eq!(loaded.candidates[0].origin.file, PathBuf::from("rule.txt"));
439 assert_eq!(loaded.candidates[0].origin.root, dir.path());
440 }
441
442 #[test]
443 fn symlink_loop_terminates() {
444 #[cfg(unix)]
445 {
446 let dir = tempfile::tempdir().unwrap();
447 let root = dir.path().join("rules");
448 write(&root.join("a.yml"), &rule("a", "A"));
449 std::os::unix::fs::symlink(&root, root.join("loop")).unwrap();
450 let spec = RulesetSpec {
451 sources: vec![root],
452 ..Default::default()
453 };
454 let loaded = load_sources(&spec, &ResolveOptions::default()).unwrap();
455 assert_eq!(loaded.candidates.len(), 1);
456 }
457 }
458
459 #[test]
460 fn missing_source_errors() {
461 let spec = RulesetSpec {
462 sources: vec![PathBuf::from("/definitely/not/here")],
463 ..Default::default()
464 };
465 let error = load_sources(&spec, &ResolveOptions::default()).unwrap_err();
466 assert!(
467 matches!(error, RulesetError::MissingSource { .. }),
468 "{error}"
469 );
470 }
471
472 #[test]
473 fn multi_document_files_get_per_kind_ordinals() {
474 let dir = tempfile::tempdir().unwrap();
475 let path = dir.path().join("rules.yml");
476 write(
477 &path,
478 &format!(
479 "{}\n---\n{}\n---\ntitle: Filter\nlogsource:\n product: linux\nfilter:\n rules: any\n selection:\n Field: value\n condition: selection\n",
480 rule("a", "A"),
481 rule("b", "B")
482 ),
483 );
484 let spec = RulesetSpec {
485 sources: vec![path],
486 ..Default::default()
487 };
488 let loaded = load_sources(&spec, &ResolveOptions::default()).unwrap();
489 assert_eq!(loaded.candidates.len(), 3);
490 assert_eq!(loaded.candidates[0].origin.ordinal, 0);
491 assert_eq!(loaded.candidates[1].origin.ordinal, 1);
492 assert_eq!(loaded.candidates[2].origin.ordinal, 0);
493 assert_eq!(loaded.candidates[2].kind(), DocumentKind::Filter);
494 }
495
496 #[test]
497 fn parse_diagnostics_keep_paths() {
498 let dir = tempfile::tempdir().unwrap();
499 let path = dir.path().join("broken.yml");
500 write(&path, "title: Broken\nlogsource: {}\ndetection: {}\n");
501 let spec = RulesetSpec {
502 sources: vec![path.clone()],
503 ..Default::default()
504 };
505 let loaded = load_sources(&spec, &ResolveOptions::default()).unwrap();
506 assert!(!loaded.diagnostics.is_empty());
507 assert_eq!(loaded.diagnostics[0].path.as_deref(), Some(path.as_path()));
508 }
509
510 #[test]
511 fn confinement_rejects_outside_and_symlink_escape() {
512 let dir = tempfile::tempdir().unwrap();
513 let inside = dir.path().join("inside");
514 let outside = dir.path().join("outside");
515 std::fs::create_dir_all(&inside).unwrap();
516 std::fs::create_dir_all(&outside).unwrap();
517 write(&outside.join("r.yml"), &rule("x", "X"));
518
519 let opts = ResolveOptions {
520 confine_to: Some(inside.clone()),
521 };
522 let spec = RulesetSpec {
523 sources: vec![outside.clone()],
524 ..Default::default()
525 };
526 let error = load_sources(&spec, &opts).unwrap_err();
527 assert!(matches!(error, RulesetError::Confinement { .. }), "{error}");
528
529 #[cfg(unix)]
530 {
531 std::os::unix::fs::symlink(&outside, inside.join("link")).unwrap();
532 let spec = RulesetSpec {
533 sources: vec![inside.join("link")],
534 ..Default::default()
535 };
536 let error = load_sources(&spec, &opts).unwrap_err();
537 assert!(matches!(error, RulesetError::Confinement { .. }), "{error}");
538 }
539 }
540}