#![allow(dead_code)]
use std::sync::OnceLock;
use crate::model::finding::Finding;
use super::schema::FlowDetection;
use super::{FlowSeed, Probe, run};
const EMBEDDED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/detect_flows.bin"));
static DB: OnceLock<FlowDb> = OnceLock::new();
pub(crate) struct CompiledFlow {
flow: FlowDetection,
content_hash: String,
}
impl CompiledFlow {
pub(crate) fn flow(&self) -> &FlowDetection {
&self.flow
}
pub(crate) fn content_hash(&self) -> &str {
&self.content_hash
}
pub(crate) fn run(&self, seed: &FlowSeed, probe: &mut dyn Probe) -> Vec<Finding> {
run(&self.flow, &self.content_hash, seed, probe)
}
}
pub(crate) struct FlowDb {
flows: Vec<CompiledFlow>,
}
impl FlowDb {
pub(crate) fn global() -> &'static FlowDb {
DB.get_or_init(FlowDb::from_embedded)
}
pub(crate) fn flows(&self) -> impl Iterator<Item = &CompiledFlow> {
self.flows.iter()
}
pub(crate) fn from_embedded() -> FlowDb {
FlowDb {
flows: embedded_flows(),
}
}
pub(crate) fn from_flows(flows: Vec<CompiledFlow>) -> Self {
Self { flows }
}
}
impl CompiledFlow {
pub(crate) fn from_parts(flow: FlowDetection, content_hash: String) -> Self {
Self { flow, content_hash }
}
}
#[cfg(test)]
pub(crate) fn shipped_flow(id: &str) -> FlowDetection {
embedded_flows()
.into_iter()
.map(|compiled| compiled.flow)
.find(|flow| flow.detection.id == id)
.unwrap_or_else(|| panic!("the corpus ships no flow with the id '{id}'"))
}
pub(crate) fn embedded_flows() -> Vec<CompiledFlow> {
let sources: Vec<(String, String)> =
bincode::deserialize(EMBEDDED).expect("embedded flow database failed to deserialize");
sources
.into_iter()
.map(|(content_hash, source)| {
let flow = toml::from_str(&source)
.expect("an embedded flow was validated at build but did not re-parse at runtime");
CompiledFlow { flow, content_hash }
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_embedded_corpus_loads_and_every_flow_carries_a_content_hash() {
let flows: Vec<&CompiledFlow> = FlowDb::global().flows().collect();
assert!(!flows.is_empty(), "the flow corpus is empty");
for flow in flows {
let hash = flow.content_hash();
assert_eq!(hash.len(), 64, "content hash is not a SHA-256: {hash:?}");
assert!(hash.bytes().all(|byte| byte.is_ascii_hexdigit()));
}
}
#[test]
fn the_corpus_ships_the_classes_it_is_known_to_ship() {
use crate::detect::manifest::Class;
let blessed = [
("couchdb-writable", Class::ActiveMutating),
("elasticsearch-writable", Class::ActiveMutating),
("etcd-writable", Class::ActiveMutating),
("ftp-anon-writable", Class::ActiveMutating),
("grafana-path-traversal", Class::Exploit),
("memcached-writable", Class::ActiveMutating),
("mqtt-anon-publish", Class::ActiveMutating),
("redis-config-writable", Class::ActiveMutating),
("redis-writable", Class::ActiveMutating),
("tftp-writable", Class::ActiveMutating),
("webdav-writable", Class::ActiveMutating),
];
let mut exceptions: Vec<(String, Class)> = FlowDb::global()
.flows()
.map(|flow| {
(
flow.flow().detection.id.clone(),
flow.flow().detection.capabilities.class,
)
})
.filter(|(_, class)| *class != Class::ActiveBenign)
.collect();
exceptions.sort_by(|a, b| a.0.cmp(&b.0));
let exceptions: Vec<(&str, Class)> = exceptions
.iter()
.map(|(id, class)| (id.as_str(), *class))
.collect();
assert_eq!(
exceptions, blessed,
"a detection ships a class other than active-benign that is not blessed \
here: a class above the default is silent by default or intrusive, so \
adding or changing one is a security decision and must be listed"
);
}
#[test]
fn a_flow_stamps_its_content_hash_on_the_findings_it_produces() {
let redis = FlowDb::global()
.flows()
.find(|flow| flow.flow().detection.id == "redis-unauth-access")
.expect("the redis flow is in the corpus");
struct Canned(Vec<u8>);
impl Probe for Canned {
fn speak(&mut self, _bytes: &[u8]) -> Option<Vec<u8>> {
Some(self.0.clone())
}
}
let seed = FlowSeed::new("192.0.2.10", 6379);
let findings = redis.run(
&seed,
&mut Canned(b"# Server\r\nredis_version:7.2.4".to_vec()),
);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].detection().content_hash(), redis.content_hash());
assert_eq!(findings[0].detection().content_hash().len(), 64);
}
}