use std::net::IpAddr;
use std::time::Duration;
use thiserror::Error;
use crate::detect::manifest::{
Class, DEFAULT_MAX_BYTES, DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_MILLIS, DetectionManifest,
};
use crate::model::finding::{DetectionClass, DetectionId, Version};
use super::budget::Budget;
pub trait Capabilities: Send {
fn speak(&mut self, bytes: &[u8]) -> Result<Vec<u8>, CapError>;
fn resolve(&mut self, name: &str) -> Result<Vec<IpAddr>, CapError>;
fn now(&mut self) -> ScanInstant;
}
impl Capabilities for Box<dyn Capabilities> {
fn speak(&mut self, bytes: &[u8]) -> Result<Vec<u8>, CapError> {
(**self).speak(bytes)
}
fn resolve(&mut self, name: &str) -> Result<Vec<IpAddr>, CapError> {
(**self).resolve(name)
}
fn now(&mut self) -> ScanInstant {
(**self).now()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ScanInstant {
millis: u64,
}
impl ScanInstant {
pub const fn from_millis(millis: u64) -> Self {
Self { millis }
}
pub const fn millis(self) -> u64 {
self.millis
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Capability {
Speak,
Resolve,
Now,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum CapError {
#[error("the byte budget is exhausted")]
ByteBudgetExhausted,
#[error("the connection budget is exhausted")]
ConnectionBudgetExhausted,
#[error("the call was denied: {0}")]
Denied(String),
#[error("no file descriptor was free for the exchange's socket")]
OutOfDescriptors,
#[error("the exchange timed out")]
TimedOut,
#[error("the connection was refused")]
ConnectionRefused,
#[error("the connection was reset")]
Reset,
}
impl CapError {
pub(crate) fn is_fatal(&self) -> bool {
matches!(
self,
Self::ByteBudgetExhausted
| Self::ConnectionBudgetExhausted
| Self::Denied(_)
| Self::OutOfDescriptors
)
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Grant {
pub detection: DetectionId,
pub class: DetectionClass,
pub budget: Budget,
pub speak: bool,
pub resolve: bool,
}
const DEFAULT_FUEL: u64 = 10_000_000;
pub(crate) const DEFAULT_MAX_MEMORY: usize = 1_000_000;
impl Grant {
pub fn from_manifest(manifest: &DetectionManifest, content_hash: &str) -> Option<Self> {
let version = manifest.version.parse().unwrap_or(Version::new(0, 0, 0));
let detection = DetectionId::new(manifest.id.clone(), version, content_hash).ok()?;
let caps = &manifest.capabilities;
let active = !matches!(caps.class, Class::Passive | Class::Derived);
Some(Self {
detection,
class: caps.class.into_model(),
budget: Budget {
fuel: DEFAULT_FUEL,
deadline: Duration::from_millis(
caps.max_millis.map_or(DEFAULT_MAX_MILLIS, u64::from),
),
max_memory: DEFAULT_MAX_MEMORY,
max_bytes: caps.max_bytes.map_or(DEFAULT_MAX_BYTES, u64::from),
max_connections: caps
.max_connections
.map_or(DEFAULT_MAX_CONNECTIONS, u32::from),
},
speak: active && caps.speak.is_some(),
resolve: active && caps.resolve,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::manifest::{CapabilitySpec, Rule, Speak};
fn manifest(class: Class, speak: bool, resolve: bool) -> DetectionManifest {
DetectionManifest {
id: "test".into(),
version: "2.1.0".into(),
title: "test".into(),
when: Rule {
service: None,
services: Vec::new(),
port: None,
ports: Vec::new(),
protocol: None,
speaks: None,
},
capabilities: CapabilitySpec {
class,
speak: speak.then_some(Speak::Target),
resolve,
max_bytes: None,
max_millis: Some(500),
max_connections: None,
},
}
}
#[test]
fn a_passive_grant_is_served_no_network_verb_even_if_it_declared_one() {
let grant = Grant::from_manifest(&manifest(Class::Passive, true, true), "hash").unwrap();
assert!(!grant.speak, "a passive detection was served speak");
assert!(!grant.resolve, "a passive detection was served resolve");
assert_eq!(grant.class, DetectionClass::Passive);
}
#[test]
fn an_active_grant_exposes_the_verbs_it_declared_and_fills_the_budget() {
let grant =
Grant::from_manifest(&manifest(Class::ActiveBenign, true, false), "hash").unwrap();
assert!(grant.speak);
assert!(!grant.resolve);
assert_eq!(grant.detection.version(), Version::new(2, 1, 0));
assert_eq!(grant.budget.deadline, Duration::from_millis(500));
assert_eq!(grant.budget.max_bytes, DEFAULT_MAX_BYTES);
}
}