use serde::{Deserialize, Serialize};
pub const MAX_RULE_WEIGHT: f32 = 2.0;
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Predicate<T> {
pub equals: Option<T>,
pub any_of: Option<Vec<T>>,
pub range: Option<[T; 2]>,
}
impl<T> Predicate<T> {
pub fn forms_set(&self) -> usize {
usize::from(self.equals.is_some())
+ usize::from(self.any_of.is_some())
+ usize::from(self.range.is_some())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReplyKind {
#[default]
SynAck,
Reset,
EchoReply,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Provenance {
Measured,
#[default]
Published,
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OsIdentity {
pub family: Option<String>,
#[serde(default)]
pub device: Option<String>,
pub vendor: Option<String>,
pub product: Option<String>,
pub version: Option<String>,
pub cpe: Option<String>,
}
impl OsIdentity {
pub fn label(&self) -> &str {
self.family
.as_deref()
.or(self.device.as_deref())
.unwrap_or("unnamed")
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MatchRule {
pub reply: ReplyKind,
pub initial_hops: Option<Predicate<u8>>,
pub dont_fragment: Option<Predicate<bool>>,
pub option_layout: Option<Predicate<String>>,
pub window: Option<Predicate<u16>>,
pub window_units: Option<Predicate<u16>>,
pub window_remainder: Option<Predicate<u16>>,
pub window_scale: Option<Predicate<u8>>,
pub mss: Option<Predicate<u16>>,
pub timestamps: Option<Predicate<bool>>,
pub sack_permitted: Option<Predicate<bool>>,
pub identifier_class: Option<Predicate<String>>,
pub sequence_class: Option<Predicate<String>>,
pub clock_class: Option<Predicate<String>>,
pub echo_code: Option<Predicate<u8>>,
pub echo_payload_intact: Option<Predicate<bool>>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Example {
pub source: String,
pub reply: ReplyKind,
pub remaining_hops: u8,
pub dont_fragment: bool,
#[serde(default)]
pub option_layout: String,
#[serde(default)]
pub window: Option<u16>,
pub mss: Option<u16>,
pub window_scale: Option<u8>,
#[serde(default)]
pub timestamps: bool,
#[serde(default)]
pub sack_permitted: bool,
#[serde(default)]
pub echo_code: u8,
#[serde(default = "yes")]
pub echo_payload_intact: bool,
#[serde(default)]
pub identifier_class: Option<String>,
#[serde(default)]
pub sequence_class: Option<String>,
#[serde(default)]
pub clock_class: Option<String>,
}
impl Example {
pub fn records_a_series(&self) -> bool {
self.identifier_class.is_some()
|| self.sequence_class.is_some()
|| self.clock_class.is_some()
}
}
fn yes() -> bool {
true
}
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OsDefinition {
pub os: OsIdentity,
#[serde(default)]
pub provenance: Provenance,
#[serde(default)]
pub notes: Option<String>,
#[serde(default = "default_weight")]
pub weight: f32,
pub r#match: MatchRule,
#[serde(default)]
pub example: Vec<Example>,
}
impl OsDefinition {
pub fn new(os: OsIdentity, r#match: MatchRule) -> Self {
Self {
os,
provenance: Provenance::default(),
notes: None,
weight: default_weight(),
r#match,
example: Vec::new(),
}
}
}
fn default_weight() -> f32 {
1.0
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PredicateDefect {
NoForm,
SeveralForms(usize),
EmptyAnyOf,
BackwardsRange,
}
impl std::fmt::Display for PredicateDefect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PredicateDefect::NoForm => {
f.write_str("sets none of equals/any_of/range, so it can never match")
}
PredicateDefect::SeveralForms(count) => write!(
f,
"sets {count} of equals/any_of/range; exactly one is allowed"
),
PredicateDefect::EmptyAnyOf => {
f.write_str("has an empty any_of, so it can never match")
}
PredicateDefect::BackwardsRange => f.write_str(
"has a range whose low bound is above its high bound, so it can never match",
),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum RuleError {
Unidentified,
VersionWithoutProduct,
Weight(f32),
Predicate {
field: &'static str,
defect: PredicateDefect,
},
NoPredicates,
ExampleWithoutSeries(String),
ExampleWithoutWindow(ReplyKind),
}
impl std::fmt::Display for RuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RuleError::Unidentified => f.write_str("names neither a family nor a device class"),
RuleError::VersionWithoutProduct => {
f.write_str("states a version without a product to version")
}
RuleError::Weight(value) => {
write!(f, "has weight {value}, outside 0..={MAX_RULE_WEIGHT}")
}
RuleError::Predicate { field, defect } => write!(f, "predicate `{field}` {defect}"),
RuleError::NoPredicates => {
f.write_str("states no predicates, so it would match every reply of its kind")
}
RuleError::ExampleWithoutSeries(source) => write!(
f,
"reads a series and its example ({source}) recorded none, so nothing \
checks the rule against it"
),
RuleError::ExampleWithoutWindow(reply) => write!(
f,
"has a {reply:?} example with no window; only an echo example may omit one"
),
}
}
}
impl std::error::Error for RuleError {}
impl<T: PartialOrd> Predicate<T> {
pub fn defect(&self) -> Option<PredicateDefect> {
match self.forms_set() {
1 => {}
0 => return Some(PredicateDefect::NoForm),
several => return Some(PredicateDefect::SeveralForms(several)),
}
if self.any_of.as_ref().is_some_and(Vec::is_empty) {
return Some(PredicateDefect::EmptyAnyOf);
}
if let Some([low, high]) = &self.range
&& low > high
{
return Some(PredicateDefect::BackwardsRange);
}
None
}
}
impl MatchRule {
pub fn validate(&self) -> Result<(), RuleError> {
let mut stated = 0usize;
macro_rules! check {
($($field:ident),* $(,)?) => {$(
if let Some(predicate) = &self.$field {
stated += 1;
if let Some(defect) = predicate.defect() {
return Err(RuleError::Predicate {
field: stringify!($field),
defect,
});
}
}
)*};
}
check!(
initial_hops,
dont_fragment,
option_layout,
window,
window_units,
window_remainder,
window_scale,
mss,
timestamps,
sack_permitted,
echo_code,
echo_payload_intact,
identifier_class,
sequence_class,
clock_class,
);
match stated {
0 => Err(RuleError::NoPredicates),
_ => Ok(()),
}
}
}
impl OsDefinition {
pub fn validate(&self) -> Result<(), RuleError> {
let named = |part: &Option<String>| {
part.as_deref()
.is_some_and(|value| !value.trim().is_empty())
};
if !named(&self.os.family) && !named(&self.os.device) {
return Err(RuleError::Unidentified);
}
if self.os.version.is_some() && self.os.product.is_none() {
return Err(RuleError::VersionWithoutProduct);
}
if !(0.0..=MAX_RULE_WEIGHT).contains(&self.weight) || !self.weight.is_finite() {
return Err(RuleError::Weight(self.weight));
}
self.r#match.validate()?;
for example in &self.example {
if example.reply != ReplyKind::EchoReply && example.window.is_none() {
return Err(RuleError::ExampleWithoutWindow(example.reply));
}
}
let reads_a_series = self.r#match.identifier_class.is_some()
|| self.r#match.sequence_class.is_some()
|| self.r#match.clock_class.is_some();
if reads_a_series && let Some(example) = self.example.iter().find(|e| !e.records_a_series())
{
return Err(RuleError::ExampleWithoutSeries(example.source.clone()));
}
Ok(())
}
}