use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use crate::error::MappingError;
use crate::path::FieldPath;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MappingSet {
pub name: String,
pub version: u32,
pub mappings: Vec<SourceMapping>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceMapping {
pub logsource: LogSourceSelector,
#[serde(default)]
pub class: BTreeMap<FieldPath, ClassValue>,
#[serde(deserialize_with = "one_or_more_paths")]
pub fields: BTreeMap<String, Vec<FieldPath>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LogSourceSelector {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub product: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub service: Option<String>,
}
impl LogSourceSelector {
pub fn selects(&self, logsource: &LogSourceSelector) -> bool {
let agrees = |wanted: &Option<String>, declared: &Option<String>| {
wanted.is_none() || wanted == declared
};
agrees(&self.category, &logsource.category)
&& agrees(&self.product, &logsource.product)
&& agrees(&self.service, &logsource.service)
}
fn specificity(&self) -> usize {
[&self.category, &self.product, &self.service]
.into_iter()
.filter(|key| key.is_some())
.count()
}
}
impl From<&goliath_sigma::LogSource> for LogSourceSelector {
fn from(logsource: &goliath_sigma::LogSource) -> Self {
Self {
category: logsource.category.clone(),
product: logsource.product.clone(),
service: logsource.service.clone(),
}
}
}
impl fmt::Display for LogSourceSelector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let keys = [
("category", &self.category),
("product", &self.product),
("service", &self.service),
];
let mut first = true;
for (name, value) in keys {
if let Some(value) = value {
if !first {
f.write_str(", ")?;
}
write!(f, "{name}: {value}")?;
first = false;
}
}
if first {
f.write_str("no log source")?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ClassValue {
Integer(i64),
String(String),
}
impl MappingSet {
pub fn from_yaml(source: &str) -> Result<Self, MappingError> {
let set: Self = goliath_sigma::yaml::from_str(source)?;
set.check()?;
Ok(set)
}
fn check(&self) -> Result<(), MappingError> {
for (index, entry) in self.mappings.iter().enumerate() {
if entry.logsource.specificity() == 0 {
return Err(MappingError::EmptySelector { index });
}
if let Some(field) = entry.fields.iter().find(|(_, paths)| paths.is_empty()) {
return Err(MappingError::NoPaths {
index,
field: field.0.clone(),
});
}
if let Some(earlier) = self.mappings[..index]
.iter()
.position(|other| other.logsource == entry.logsource)
{
return Err(MappingError::DuplicateSelector { earlier, index });
}
}
Ok(())
}
pub fn select(&self, logsource: &LogSourceSelector) -> Result<&SourceMapping, MappingError> {
let mut best: Option<&SourceMapping> = None;
let mut tied = false;
for entry in &self.mappings {
if !entry.logsource.selects(logsource) {
continue;
}
let specificity = entry.logsource.specificity();
match best.map(|current| current.logsource.specificity().cmp(&specificity)) {
None | Some(Ordering::Less) => {
best = Some(entry);
tied = false;
}
Some(Ordering::Equal) => tied = true,
Some(Ordering::Greater) => {}
}
}
match best {
None => Err(MappingError::NoMapping {
logsource: logsource.clone(),
}),
Some(_) if tied => Err(MappingError::Ambiguous {
logsource: logsource.clone(),
}),
Some(entry) => Ok(entry),
}
}
}
fn one_or_more_paths<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<BTreeMap<String, Vec<FieldPath>>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum OneOrMore {
One(FieldPath),
More(Vec<FieldPath>),
}
let raw = BTreeMap::<String, OneOrMore>::deserialize(deserializer)?;
Ok(raw
.into_iter()
.map(|(field, paths)| {
let paths = match paths {
OneOrMore::One(path) => vec![path],
OneOrMore::More(paths) => paths,
};
(field, paths)
})
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
const SET: &str = r"
name: test
version: 3
mappings:
- logsource: { product: windows }
fields:
User: actor.user.name
- logsource: { category: process_creation, product: windows }
class: { class_uid: 1007, activity_id: 1, device.os.type_id: 100 }
fields:
Image: [process.file.path, process.path]
CommandLine: process.cmd_line
";
fn selector(category: Option<&str>, product: Option<&str>) -> LogSourceSelector {
LogSourceSelector {
category: category.map(str::to_owned),
product: product.map(str::to_owned),
service: None,
}
}
fn path(text: &str) -> FieldPath {
FieldPath::parse(text).expect("valid path")
}
#[test]
fn loads_single_and_multiple_paths() {
let set = MappingSet::from_yaml(SET).expect("valid set");
assert_eq!(set.version, 3);
let process = &set.mappings[1];
assert_eq!(
process.fields["Image"],
[path("process.file.path"), path("process.path")]
);
assert_eq!(process.fields["CommandLine"], [path("process.cmd_line")]);
assert_eq!(process.class[&path("class_uid")], ClassValue::Integer(1007));
}
#[test]
fn the_most_specific_entry_wins() {
let set = MappingSet::from_yaml(SET).expect("valid set");
let entry = set
.select(&selector(Some("process_creation"), Some("windows")))
.expect("selected");
assert!(entry.fields.contains_key("Image"));
let general = set
.select(&selector(Some("registry_set"), Some("windows")))
.expect("falls back to the product entry");
assert!(general.fields.contains_key("User"));
}
#[test]
fn keys_a_rule_declares_beyond_the_selector_do_not_prevent_selection() {
let set = MappingSet::from_yaml(SET).expect("valid set");
let mut logsource = selector(Some("process_creation"), Some("windows"));
logsource.service = Some("sysmon".to_owned());
assert!(set.select(&logsource).is_ok());
}
#[test]
fn an_unselected_log_source_is_an_error() {
let set = MappingSet::from_yaml(SET).expect("valid set");
assert!(matches!(
set.select(&selector(Some("process_creation"), Some("linux"))),
Err(MappingError::NoMapping { .. })
));
}
#[test]
fn equally_specific_matches_are_ambiguous() {
let set = MappingSet::from_yaml(
r"
name: test
version: 1
mappings:
- logsource: { product: windows }
fields: { A: a }
- logsource: { category: process_creation }
fields: { B: b }
",
)
.expect("valid set");
assert!(matches!(
set.select(&selector(Some("process_creation"), Some("windows"))),
Err(MappingError::Ambiguous { .. })
));
}
#[test]
fn rejects_unknown_keys() {
let typo = SET.replace("fields:\n User", "feilds:\n User");
assert!(matches!(
MappingSet::from_yaml(&typo),
Err(MappingError::Yaml(_))
));
}
#[test]
fn rejects_an_entry_that_selects_everything() {
let source = "name: t\nversion: 1\nmappings:\n - logsource: {}\n fields: { A: a }\n";
assert_eq!(
MappingSet::from_yaml(source),
Err(MappingError::EmptySelector { index: 0 })
);
}
#[test]
fn rejects_a_field_with_no_paths() {
let source = "name: t\nversion: 1\nmappings:\n - logsource: { product: x }\n fields: { A: [] }\n";
assert!(matches!(
MappingSet::from_yaml(source),
Err(MappingError::NoPaths { index: 0, .. })
));
}
#[test]
fn rejects_duplicate_selectors() {
let source = "name: t\nversion: 1\nmappings:\n - logsource: { product: x }\n fields: { A: a }\n - logsource: { product: x }\n fields: { B: b }\n";
assert_eq!(
MappingSet::from_yaml(source),
Err(MappingError::DuplicateSelector {
earlier: 0,
index: 1
})
);
}
#[test]
fn rejects_malformed_paths() {
let source = "name: t\nversion: 1\nmappings:\n - logsource: { product: x }\n fields: { A: a..b }\n";
assert!(matches!(
MappingSet::from_yaml(source),
Err(MappingError::Yaml(_))
));
}
}