#![allow(dead_code)]
use super::authoring::{Reference, Severity};
use std::collections::BTreeMap;
use serde::{Deserialize, Deserializer};
use super::manifest::DetectionManifest;
pub const MAX_FLOW_STEPS: usize = 16;
pub const MAX_LOOP_ITEMS: usize = 64;
pub const SEED_VAR_HOST: &str = "host";
pub const SEED_VAR_PORT: &str = "port";
pub const SEED_VARS: &[&str] = &[SEED_VAR_HOST, SEED_VAR_PORT];
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FlowDetection {
pub detection: DetectionManifest,
#[serde(default)]
pub step: Vec<Step>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Step {
#[serde(default)]
pub when: Option<String>,
#[serde(default)]
pub for_each: Option<ForEach>,
#[serde(default)]
pub send: Option<String>,
#[serde(default, deserialize_with = "one_or_many")]
pub expect: Vec<MatchSpec>,
#[serde(default)]
pub until: Option<String>,
#[serde(default)]
pub bind: BTreeMap<String, MatchSpec>,
#[serde(default)]
pub on_no_match: OnNoMatch,
#[serde(default)]
pub finding: Vec<FindingSpec>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum MatchSpec {
Pattern(String),
Rule(Box<MatchDetail>),
}
impl MatchSpec {
pub fn pattern(&self) -> &str {
match self {
MatchSpec::Pattern(pattern) => pattern,
MatchSpec::Rule(rule) => &rule.pattern,
}
}
pub fn version_group(&self) -> Option<u8> {
match self {
MatchSpec::Pattern(_) => None,
MatchSpec::Rule(rule) => rule.version_group,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MatchDetail {
pub pattern: String,
#[serde(default)]
pub version_group: Option<u8>,
#[serde(default)]
pub product: Option<String>,
#[serde(default)]
pub vendor: Option<String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ForEach {
pub var: String,
#[serde(rename = "in")]
pub items: Vec<String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OnNoMatch {
#[default]
Halt,
Continue,
}
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FindingSpec {
#[serde(default)]
pub when: Option<String>,
pub severity: Severity,
#[serde(default)]
pub title: Option<String>,
pub summary: String,
#[serde(default)]
pub detail: Option<String>,
#[serde(default)]
pub confidence: Option<String>,
#[serde(default)]
pub references: Vec<Reference>,
#[serde(default)]
pub remediation: Option<String>,
#[serde(default)]
pub excerpt_from: Option<String>,
}
fn one_or_many<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum OneOrMany<T> {
One(T),
Many(Vec<T>),
}
Ok(match OneOrMany::deserialize(deserializer)? {
OneOrMany::One(one) => vec![one],
OneOrMany::Many(many) => many,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::manifest::{Class, Speak};
fn parse(toml: &str) -> FlowDetection {
toml::from_str(toml).expect("a valid flow parses")
}
#[test]
fn the_redis_example_parses_into_its_structure() {
let flow = parse(include_str!(
"../../../assets/detect/database/redis-unauth.toml"
));
assert_eq!(flow.detection.id, "redis-unauth-access");
assert_eq!(flow.detection.when.service.as_deref(), Some("redis"));
assert_eq!(flow.detection.capabilities.class, Class::ActiveBenign);
assert_eq!(flow.detection.capabilities.speak, Some(Speak::Target));
assert_eq!(flow.detection.capabilities.max_bytes, Some(8192));
assert_eq!(flow.step.len(), 1);
let step = &flow.step[0];
assert_eq!(step.send.as_deref(), Some("INFO\r\n"));
assert_eq!(
step.expect.len(),
1,
"the bare-string shorthand read as one rule"
);
assert!(step.bind.contains_key("version"));
assert_eq!(step.finding.len(), 1);
let finding = &step.finding[0];
assert_eq!(finding.when.as_deref(), Some("matched"));
assert_eq!(finding.severity, Severity::High);
assert_eq!(finding.references, vec![Reference::Cwe(306)]);
}
#[test]
fn a_bounded_loop_parses_its_var_and_items() {
let flow = parse(
r#"
[detection]
id = "loop"
version = "1.0.0"
title = "loop"
[detection.when]
protocol = "udp"
[detection.capabilities]
class = "active-benign"
speak = "target"
[[step]]
for_each = { var = "community", in = ["public", "private", "manager", "admin"] }
send = "{community}"
expect = "ok"
on_no_match = "continue"
[[step.finding]]
when = "matched"
severity = "high"
summary = "answered {community}"
"#,
);
assert_eq!(flow.detection.when.protocol.as_deref(), Some("udp"));
let step = &flow.step[0];
let for_each = step.for_each.as_ref().expect("a for_each loop");
assert_eq!(for_each.var, "community");
assert_eq!(for_each.items.len(), 4);
assert_eq!(step.on_no_match, OnNoMatch::Continue);
}
#[test]
fn a_bare_pattern_and_a_full_rule_both_read_as_a_match_rule() {
let pattern = MatchSpec::Pattern("^\\+PONG".to_string());
assert_eq!(pattern.pattern(), "^\\+PONG");
assert_eq!(pattern.version_group(), None);
let flow = parse(
r#"
[detection]
id = "x"
version = "1.0.0"
title = "x"
[detection.when]
service = "http"
[detection.capabilities]
class = "passive"
[[step]]
expect = { pattern = "Server: nginx", product = "nginx" }
"#,
);
let spec = &flow.step[0].expect[0];
assert_eq!(spec.pattern(), "Server: nginx");
let MatchSpec::Rule(detail) = spec else {
panic!("the table form reads as a full rule");
};
assert_eq!(detail.product.as_deref(), Some("nginx"));
}
}