1use std::cmp::Ordering;
28use std::collections::BTreeMap;
29use std::fmt;
30
31use goliath_ocsf::schema::{self, Attribute, Base, Class};
32use serde::{Deserialize, Deserializer, Serialize};
33
34use crate::error::MappingError;
35use crate::path::FieldPath;
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct MappingSet {
41 pub name: String,
43 pub version: u32,
46 pub mappings: Vec<SourceMapping>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(deny_unknown_fields)]
53pub struct SourceMapping {
54 pub logsource: LogSourceSelector,
56 #[serde(default)]
58 pub class: BTreeMap<FieldPath, ClassValue>,
59 #[serde(deserialize_with = "one_or_more_paths")]
62 pub fields: BTreeMap<String, Vec<FieldPath>>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct LogSourceSelector {
71 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub category: Option<String>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub product: Option<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub service: Option<String>,
80}
81
82impl LogSourceSelector {
83 pub fn selects(&self, logsource: &LogSourceSelector) -> bool {
85 let agrees = |wanted: &Option<String>, declared: &Option<String>| {
86 wanted.is_none() || wanted == declared
87 };
88 agrees(&self.category, &logsource.category)
89 && agrees(&self.product, &logsource.product)
90 && agrees(&self.service, &logsource.service)
91 }
92
93 fn specificity(&self) -> usize {
95 [&self.category, &self.product, &self.service]
96 .into_iter()
97 .filter(|key| key.is_some())
98 .count()
99 }
100}
101
102impl From<&goliath_sigma::LogSource> for LogSourceSelector {
103 fn from(logsource: &goliath_sigma::LogSource) -> Self {
104 Self {
105 category: logsource.category.clone(),
106 product: logsource.product.clone(),
107 service: logsource.service.clone(),
108 }
109 }
110}
111
112impl fmt::Display for LogSourceSelector {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 let keys = [
115 ("category", &self.category),
116 ("product", &self.product),
117 ("service", &self.service),
118 ];
119 let mut first = true;
120 for (name, value) in keys {
121 if let Some(value) = value {
122 if !first {
123 f.write_str(", ")?;
124 }
125 write!(f, "{name}: {value}")?;
126 first = false;
127 }
128 }
129 if first {
130 f.write_str("no log source")?;
131 }
132 Ok(())
133 }
134}
135
136impl SourceMapping {
137 fn check_schema(&self, index: usize) -> Result<(), MappingError> {
140 let class_uid = self.class.iter().find_map(|(path, value)| match value {
141 ClassValue::Integer(uid) if path.as_str() == "class_uid" => Some(*uid),
142 _ => None,
143 });
144 let Some(class_uid) = class_uid else {
145 return Ok(());
146 };
147 let class = u32::try_from(class_uid)
148 .ok()
149 .and_then(schema::class)
150 .ok_or(MappingError::UnknownClass {
151 index,
152 class_uid,
153 version: goliath_ocsf::SCHEMA_VERSION,
154 })?;
155 for (path, value) in &self.class {
156 let Some(attribute) = attribute(index, class, path)? else {
157 continue;
158 };
159 let fits = match value {
160 ClassValue::Integer(_) => matches!(attribute.base(), Base::Integer | Base::Long),
161 ClassValue::String(_) => attribute.base() == Base::String,
162 };
163 if !fits || attribute.is_array() {
164 return Err(MappingError::Type {
165 index,
166 path: path.as_str().to_owned(),
167 holds: holds(attribute),
168 value: match value {
169 ClassValue::Integer(value) => value.to_string(),
170 ClassValue::String(value) => format!("{value:?}"),
171 },
172 });
173 }
174 if let ClassValue::Integer(value) = value
175 && !attribute.enum_values().is_empty()
176 && !attribute.enum_values().contains(value)
177 {
178 return Err(MappingError::UnknownValue {
179 index,
180 path: path.as_str().to_owned(),
181 value: *value,
182 });
183 }
184 }
185 for path in self.fields.values().flatten() {
186 if let Some(attribute) = attribute(index, class, path)?
187 && attribute.base() == Base::Object
188 {
189 return Err(MappingError::Type {
190 index,
191 path: path.as_str().to_owned(),
192 holds: holds(attribute),
193 value: "a rule's value".to_owned(),
194 });
195 }
196 }
197 Ok(())
198 }
199}
200
201fn attribute(
204 index: usize,
205 class: &Class,
206 path: &FieldPath,
207) -> Result<Option<&'static Attribute>, MappingError> {
208 let found = class
209 .resolve(path.as_str())
210 .map_err(|source| MappingError::Attribute { index, source })?;
211 Ok((!found.free_form).then_some(found.attribute))
212}
213
214fn holds(attribute: &Attribute) -> String {
215 match (attribute.is_array(), attribute.base()) {
216 (true, _) => format!("an array of `{}`", attribute.type_name()),
217 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
218 (false, _) => format!("`{}`", attribute.type_name()),
219 }
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224#[serde(untagged)]
225pub enum ClassValue {
226 Integer(i64),
228 String(String),
230}
231
232impl MappingSet {
233 pub fn from_yaml(source: &str) -> Result<Self, MappingError> {
242 let set: Self = goliath_sigma::yaml::from_str(source)?;
243 set.check()?;
244 Ok(set)
245 }
246
247 fn check(&self) -> Result<(), MappingError> {
248 for (index, entry) in self.mappings.iter().enumerate() {
249 if entry.logsource.specificity() == 0 {
250 return Err(MappingError::EmptySelector { index });
251 }
252 if let Some(field) = entry.fields.iter().find(|(_, paths)| paths.is_empty()) {
253 return Err(MappingError::NoPaths {
254 index,
255 field: field.0.clone(),
256 });
257 }
258 if let Some(earlier) = self.mappings[..index]
259 .iter()
260 .position(|other| other.logsource == entry.logsource)
261 {
262 return Err(MappingError::DuplicateSelector { earlier, index });
263 }
264 entry.check_schema(index)?;
265 }
266 Ok(())
267 }
268
269 pub fn select(&self, logsource: &LogSourceSelector) -> Result<&SourceMapping, MappingError> {
279 let mut best: Option<&SourceMapping> = None;
280 let mut tied = false;
281
282 for entry in &self.mappings {
283 if !entry.logsource.selects(logsource) {
284 continue;
285 }
286 let specificity = entry.logsource.specificity();
287 match best.map(|current| current.logsource.specificity().cmp(&specificity)) {
288 None | Some(Ordering::Less) => {
289 best = Some(entry);
290 tied = false;
291 }
292 Some(Ordering::Equal) => tied = true,
293 Some(Ordering::Greater) => {}
294 }
295 }
296
297 match best {
298 None => Err(MappingError::NoMapping {
299 logsource: logsource.clone(),
300 }),
301 Some(_) if tied => Err(MappingError::Ambiguous {
302 logsource: logsource.clone(),
303 }),
304 Some(entry) => Ok(entry),
305 }
306 }
307}
308
309fn one_or_more_paths<'de, D: Deserializer<'de>>(
311 deserializer: D,
312) -> Result<BTreeMap<String, Vec<FieldPath>>, D::Error> {
313 #[derive(Deserialize)]
314 #[serde(untagged)]
315 enum OneOrMore {
316 One(FieldPath),
317 More(Vec<FieldPath>),
318 }
319
320 let raw = BTreeMap::<String, OneOrMore>::deserialize(deserializer)?;
321 Ok(raw
322 .into_iter()
323 .map(|(field, paths)| {
324 let paths = match paths {
325 OneOrMore::One(path) => vec![path],
326 OneOrMore::More(paths) => paths,
327 };
328 (field, paths)
329 })
330 .collect())
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 const SET: &str = r"
338name: test
339version: 3
340mappings:
341 - logsource: { product: windows }
342 fields:
343 User: actor.user.name
344 - logsource: { category: process_creation, product: windows }
345 class: { class_uid: 1007, activity_id: 1, device.os.type_id: 100 }
346 fields:
347 Image: [process.file.path, process.path]
348 CommandLine: process.cmd_line
349";
350
351 fn selector(category: Option<&str>, product: Option<&str>) -> LogSourceSelector {
352 LogSourceSelector {
353 category: category.map(str::to_owned),
354 product: product.map(str::to_owned),
355 service: None,
356 }
357 }
358
359 fn path(text: &str) -> FieldPath {
360 FieldPath::parse(text).expect("valid path")
361 }
362
363 #[test]
364 fn loads_single_and_multiple_paths() {
365 let set = MappingSet::from_yaml(SET).expect("valid set");
366 assert_eq!(set.version, 3);
367 let process = &set.mappings[1];
368 assert_eq!(
369 process.fields["Image"],
370 [path("process.file.path"), path("process.path")]
371 );
372 assert_eq!(process.fields["CommandLine"], [path("process.cmd_line")]);
373 assert_eq!(process.class[&path("class_uid")], ClassValue::Integer(1007));
374 }
375
376 #[test]
377 fn the_most_specific_entry_wins() {
378 let set = MappingSet::from_yaml(SET).expect("valid set");
379 let entry = set
380 .select(&selector(Some("process_creation"), Some("windows")))
381 .expect("selected");
382 assert!(entry.fields.contains_key("Image"));
383
384 let general = set
385 .select(&selector(Some("registry_set"), Some("windows")))
386 .expect("falls back to the product entry");
387 assert!(general.fields.contains_key("User"));
388 }
389
390 #[test]
391 fn keys_a_rule_declares_beyond_the_selector_do_not_prevent_selection() {
392 let set = MappingSet::from_yaml(SET).expect("valid set");
393 let mut logsource = selector(Some("process_creation"), Some("windows"));
394 logsource.service = Some("sysmon".to_owned());
395 assert!(set.select(&logsource).is_ok());
396 }
397
398 #[test]
399 fn an_unselected_log_source_is_an_error() {
400 let set = MappingSet::from_yaml(SET).expect("valid set");
401 assert!(matches!(
402 set.select(&selector(Some("process_creation"), Some("linux"))),
403 Err(MappingError::NoMapping { .. })
404 ));
405 }
406
407 #[test]
408 fn equally_specific_matches_are_ambiguous() {
409 let set = MappingSet::from_yaml(
410 r"
411name: test
412version: 1
413mappings:
414 - logsource: { product: windows }
415 fields: { A: a }
416 - logsource: { category: process_creation }
417 fields: { B: b }
418",
419 )
420 .expect("valid set");
421 assert!(matches!(
422 set.select(&selector(Some("process_creation"), Some("windows"))),
423 Err(MappingError::Ambiguous { .. })
424 ));
425 }
426
427 #[test]
428 fn rejects_unknown_keys() {
429 let typo = SET.replace("fields:\n User", "feilds:\n User");
430 assert!(matches!(
431 MappingSet::from_yaml(&typo),
432 Err(MappingError::Yaml(_))
433 ));
434 }
435
436 #[test]
437 fn rejects_an_entry_that_selects_everything() {
438 let source = "name: t\nversion: 1\nmappings:\n - logsource: {}\n fields: { A: a }\n";
439 assert_eq!(
440 MappingSet::from_yaml(source),
441 Err(MappingError::EmptySelector { index: 0 })
442 );
443 }
444
445 #[test]
446 fn rejects_a_field_with_no_paths() {
447 let source = "name: t\nversion: 1\nmappings:\n - logsource: { product: x }\n fields: { A: [] }\n";
448 assert!(matches!(
449 MappingSet::from_yaml(source),
450 Err(MappingError::NoPaths { index: 0, .. })
451 ));
452 }
453
454 #[test]
455 fn rejects_duplicate_selectors() {
456 let source = "name: t\nversion: 1\nmappings:\n - logsource: { product: x }\n fields: { A: a }\n - logsource: { product: x }\n fields: { B: b }\n";
457 assert_eq!(
458 MappingSet::from_yaml(source),
459 Err(MappingError::DuplicateSelector {
460 earlier: 0,
461 index: 1
462 })
463 );
464 }
465
466 #[test]
467 fn rejects_malformed_paths() {
468 let source = "name: t\nversion: 1\nmappings:\n - logsource: { product: x }\n fields: { A: a..b }\n";
469 assert!(matches!(
470 MappingSet::from_yaml(source),
471 Err(MappingError::Yaml(_))
472 ));
473 }
474
475 fn schema_error(replace: &str, with: &str) -> String {
476 assert_eq!(SET.matches(replace).count(), 1, "{replace}");
477 MappingSet::from_yaml(&SET.replace(replace, with))
478 .expect_err("the schema rejects it")
479 .to_string()
480 }
481
482 #[test]
483 fn checks_entries_against_the_ocsf_schema() {
484 assert_eq!(
485 schema_error(
486 "CommandLine: process.cmd_line",
487 "CommandLine: process.cmdline"
488 ),
489 "mapping 1: `process.cmdline`: object `process` has no attribute `cmdline`"
490 );
491 assert_eq!(
492 schema_error("class_uid: 1007", "class_uid: 1999"),
493 "mapping 1: OCSF 1.5.0 has no class 1999"
494 );
495 assert_eq!(
496 schema_error("activity_id: 1,", "activity_id: 42,"),
497 "mapping 1: 42 is not a defined value of `activity_id`"
498 );
499 assert_eq!(
500 schema_error("device.os.type_id: 100", "device.os.type_id: windows"),
501 "mapping 1: `device.os.type_id` holds `integer_t`, which cannot equal \"windows\""
502 );
503 assert_eq!(
504 schema_error("CommandLine: process.cmd_line", "CommandLine: process.file"),
505 "mapping 1: `process.file` holds an object `file`, which cannot equal a rule's value"
506 );
507 }
508
509 #[test]
510 fn schema_checks_allow_arrays_free_form_paths_and_classless_entries() {
511 let set = SET.replace(
513 "CommandLine: process.cmd_line",
514 "CommandLine: process.cmd_line
515 Technique: attacks.technique.uid
516 Hashes: unmapped.Hashes",
517 );
518 MappingSet::from_yaml(&set).expect("arrays and unmapped are fine");
519 let set = SET.replace("User: actor.user.name", "User: anything.at.all");
521 MappingSet::from_yaml(&set).expect("no class to check against");
522 }
523}