#![allow(dead_code)]
use std::sync::OnceLock;
use super::schema::HostDetection;
use super::stage::LoadedHostDetection;
const EMBEDDED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/detect_host.bin"));
static DB: OnceLock<HostDb> = OnceLock::new();
pub(crate) struct HostDb {
detections: Vec<LoadedHostDetection>,
}
impl HostDb {
pub(crate) fn global() -> &'static HostDb {
DB.get_or_init(HostDb::from_embedded)
}
pub(crate) fn from_embedded() -> HostDb {
HostDb {
detections: embedded_hosts(),
}
}
pub(crate) fn from_detections(detections: Vec<LoadedHostDetection>) -> HostDb {
HostDb { detections }
}
pub(crate) fn detections(&self) -> &[LoadedHostDetection] {
&self.detections
}
}
pub(crate) fn embedded_hosts() -> Vec<LoadedHostDetection> {
let sources: Vec<(String, String)> =
bincode::deserialize(EMBEDDED).expect("embedded host database failed to deserialize");
sources
.into_iter()
.map(|(content_hash, source)| {
let detection: HostDetection = toml::from_str(&source).expect(
"an embedded host detection was validated at build but did not re-parse at runtime",
);
LoadedHostDetection::new(detection, content_hash)
})
.collect()
}
pub(crate) fn compile_host_source(
toml: &str,
content_hash: &str,
) -> Result<LoadedHostDetection, String> {
use crate::detect::flow::validate::{RESERVED_ID_PREFIX, is_version_triple};
let detection: HostDetection = toml::from_str(toml).map_err(|error| error.to_string())?;
let manifest = &detection.detection;
if manifest.id.trim().is_empty() {
return Err("a host detection needs a non-empty id".to_string());
}
if manifest.id.starts_with(RESERVED_ID_PREFIX) {
return Err(format!(
"a host detection id `{}` claims the reserved `{RESERVED_ID_PREFIX}` namespace",
manifest.id
));
}
if !is_version_triple(&manifest.version) {
return Err(format!(
"a host detection has version `{}`, not a major.minor.patch triple",
manifest.version
));
}
if detection.finding.is_empty() {
return Err("a host detection draws no finding, so it can conclude nothing".to_string());
}
if detection.detection.host.ports_open.is_empty()
&& detection.detection.host.services.is_empty()
{
return Err(
"a host detection has an empty gate, which would fire on every host".to_string(),
);
}
Ok(LoadedHostDetection::new(detection, content_hash))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_embedded_corpus_loads_and_carries_the_domain_controller_detection() {
let db = HostDb::global();
assert!(!db.detections().is_empty(), "the host corpus is empty");
assert!(
db.detections()
.iter()
.any(|detection| detection.id() == "domain-controller"),
"the domain-controller detection did not ship"
);
}
}