use crate::model::host::OsFingerprint;
use super::db::RuleDb;
use super::observation::{StackObservation, StackReply};
use super::signature::{OsDefinition, Provenance};
pub const MAX_STACK_ACCURACY: u8 = 70;
pub const MIN_REPORTABLE_ACCURACY: u8 = 40;
const MEASURED_ACCURACY: f32 = 65.0;
const PUBLISHED_ACCURACY: f32 = 50.0;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OsSource {
TcpStack,
HardwareVendor,
ServiceBanner,
Hostname,
}
#[derive(Debug, Clone, PartialEq)]
pub struct OsVerdict {
pub family: String,
pub vendor: Option<String>,
pub product: Option<String>,
pub version: Option<String>,
pub cpe: Option<String>,
pub accuracy: u8,
pub source: OsSource,
pub evidence: String,
}
impl OsVerdict {
pub fn as_evidence(&self) -> super::evidence::OsEvidence {
super::evidence::OsEvidence {
source: self.source,
family: self.family.clone(),
vendor: self.vendor.clone(),
product: self.product.clone(),
version: self.version.clone(),
cpe: self.cpe.clone(),
confidence: f32::from(self.accuracy) / 100.0,
evidence: self.evidence.clone(),
}
}
pub fn to_fingerprint(&self) -> OsFingerprint {
let name = self.product.clone().unwrap_or_else(|| self.family.clone());
let mut fingerprint = OsFingerprint::new(name, self.accuracy)
.with_family(&*self.family)
.with_evidence(&*self.evidence);
if let Some(vendor) = &self.vendor {
fingerprint = fingerprint.with_vendor(&**vendor);
}
if let Some(version) = &self.version {
fingerprint = fingerprint.with_generation(&**version);
}
if let Some(cpe) = &self.cpe {
fingerprint.add_cpe(&**cpe);
}
fingerprint
}
}
pub fn classify(db: &RuleDb, reply: &StackReply) -> Option<OsVerdict> {
let matched: Vec<&OsDefinition> = db.matching(reply).collect();
let (first, rest) = matched.split_first()?;
if rest.iter().any(|rule| rule.os.family != first.os.family) {
return None;
}
let agreed = |part: fn(&OsDefinition) -> &Option<String>| -> Option<String> {
let candidate = part(first).as_ref()?;
rest.iter()
.all(|rule| part(rule).as_deref() == Some(candidate.as_str()))
.then(|| candidate.clone())
};
let weight = matched
.iter()
.map(|rule| rule.weight)
.fold(f32::INFINITY, f32::min);
let base = if matched
.iter()
.all(|rule| rule.provenance == Provenance::Measured)
{
MEASURED_ACCURACY
} else {
PUBLISHED_ACCURACY
};
let accuracy = (base * weight).clamp(0.0, f32::from(MAX_STACK_ACCURACY)) as u8;
if accuracy < MIN_REPORTABLE_ACCURACY {
return None;
}
Some(OsVerdict {
family: first.os.family.clone(),
vendor: agreed(|rule| &rule.os.vendor),
product: agreed(|rule| &rule.os.product),
version: agreed(|rule| &rule.os.version),
cpe: agreed(|rule| &rule.os.cpe),
accuracy,
source: OsSource::TcpStack,
evidence: reply.summary(),
})
}
pub fn classify_reply(
ip: crate::model::capture::IpObservation,
segment: &[u8],
) -> Option<OsVerdict> {
let observed = StackObservation::from_tcp(ip, segment)?;
classify(RuleDb::global(), &observed.into())
}
pub fn classify_echo_reply(
ip: crate::model::capture::IpObservation,
message: &[u8],
sent_payload: &[u8],
) -> Option<OsVerdict> {
let observed = super::observation::EchoObservation::from_echo_reply(ip, message, sent_payload)?;
classify(RuleDb::global(), &observed.into())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::capture::{IpObservation, Ipv4Observation};
use crate::protocols::tcp::flags;
fn ip() -> IpObservation {
IpObservation::V4(Ipv4Observation {
ttl: 64,
identification: 0,
dont_fragment: true,
more_fragments: false,
dscp: 0,
ecn: 0,
})
}
fn segment(flag_byte: u8, window: u16, options: &[u8]) -> Vec<u8> {
let mut bytes = vec![0u8; 20 + options.len()];
bytes[0..2].copy_from_slice(&80u16.to_be_bytes());
bytes[2..4].copy_from_slice(&50_000u16.to_be_bytes());
bytes[4..8].copy_from_slice(&1u32.to_be_bytes());
bytes[12] = (((20 + options.len()) / 4) as u8) << 4;
bytes[13] = flag_byte;
bytes[14..16].copy_from_slice(&window.to_be_bytes());
bytes[20..].copy_from_slice(options);
bytes
}
const DEBIAN_BOOKWORM: [u8; 20] = [
0x02, 0x04, 0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a, 0xad, 0x58, 0xa5, 0xa7, 0x64, 0x48, 0x96,
0x12, 0x01, 0x03, 0x03, 0x07,
];
#[test]
fn a_recorded_linux_reply_is_named_linux() {
let verdict = classify_reply(
ip(),
&segment(flags::SYN | flags::ACK, 65_160, &DEBIAN_BOOKWORM),
)
.expect("a labelled Linux host is identified");
assert_eq!(verdict.family, "Linux");
assert_eq!(verdict.source, OsSource::TcpStack);
let fingerprint = verdict.to_fingerprint();
assert_eq!(fingerprint.name(), "Linux");
assert_eq!(fingerprint.family(), Some("Linux"));
}
#[test]
fn stack_evidence_alone_never_reaches_high_confidence() {
let verdict = classify_reply(
ip(),
&segment(flags::SYN | flags::ACK, 65_160, &DEBIAN_BOOKWORM),
)
.expect("a labelled Linux host is identified");
assert!(verdict.accuracy <= MAX_STACK_ACCURACY);
assert!(
!verdict.to_fingerprint().is_highly_confident(),
"one reply's shape is one observation, however many of its fields agree"
);
}
#[test]
fn a_shape_no_rule_describes_is_reported_as_nothing() {
let verdict = classify_reply(
ip(),
&segment(flags::SYN | flags::ACK, 12_345, &DEBIAN_BOOKWORM),
);
assert!(verdict.is_none());
}
#[test]
fn a_reset_names_nothing() {
assert!(classify_reply(ip(), &segment(flags::RST | flags::ACK, 0, &[])).is_none());
}
#[test]
fn rules_that_contradict_each_other_name_nothing() {
use super::super::signature::{
MatchRule, OsDefinition, OsIdentity, Predicate, Provenance, ReplyKind,
};
let rule = |family: &str| OsDefinition {
os: OsIdentity {
family: family.to_string(),
vendor: None,
product: None,
version: None,
cpe: None,
},
provenance: Provenance::Measured,
notes: None,
weight: 1.0,
r#match: MatchRule {
reply: ReplyKind::SynAck,
initial_hops: Some(Predicate {
equals: Some(64),
..Default::default()
}),
..Default::default()
},
example: Vec::new(),
};
let db = RuleDb::from_rules(vec![rule("Linux"), rule("Windows")]);
let observed = StackObservation::from_tcp(
ip(),
&segment(flags::SYN | flags::ACK, 65_160, &DEBIAN_BOOKWORM),
)
.unwrap()
.into();
assert_eq!(db.matching(&observed).count(), 2, "both rules match");
assert!(
classify(&db, &observed).is_none(),
"and the contradiction is reported as no answer, not as the heavier rule"
);
}
}
#[cfg(test)]
mod second_family {
use super::*;
use crate::model::capture::{IpObservation, Ipv4Observation};
use crate::protocols::tcp::flags;
fn darwin_options() -> Vec<u8> {
let mut options = vec![2, 4, 0x05, 0xb4]; options.push(1); options.extend_from_slice(&[3, 3, 6]); options.push(1); options.push(1); options.extend_from_slice(&[8, 10]); options.extend_from_slice(&0x1122_3344u32.to_be_bytes());
options.extend_from_slice(&0x5566_7788u32.to_be_bytes());
options.extend_from_slice(&[4, 2]); options.push(0); options.push(0); options
}
fn segment(flag_byte: u8, window: u16, options: &[u8]) -> Vec<u8> {
let mut bytes = vec![0u8; 20 + options.len()];
bytes[0..2].copy_from_slice(&22u16.to_be_bytes());
bytes[2..4].copy_from_slice(&50_000u16.to_be_bytes());
bytes[4..8].copy_from_slice(&1u32.to_be_bytes());
bytes[12] = (((20 + options.len()) / 4) as u8) << 4;
bytes[13] = flag_byte;
bytes[14..16].copy_from_slice(&window.to_be_bytes());
bytes[20..].copy_from_slice(options);
bytes
}
fn ip() -> IpObservation {
IpObservation::V4(Ipv4Observation {
ttl: 64,
identification: 0,
dont_fragment: true,
more_fragments: false,
dscp: 0,
ecn: 0,
})
}
#[tokio::test(flavor = "current_thread")]
async fn a_measured_darwin_reply_is_named_macos_and_not_linux() {
let observed = classify_reply(
ip(),
&segment(flags::SYN | flags::ACK, 65_535, &darwin_options()),
)
.expect("a labelled Mac is identified");
assert_eq!(observed.family, "macOS");
assert_eq!(observed.vendor.as_deref(), Some("Apple"));
assert_eq!(observed.accuracy, MEASURED_ACCURACY as u8);
}
#[test]
fn a_flat_window_is_not_read_as_a_multiple() {
let observed = StackObservation::from_tcp(
ip(),
&segment(flags::SYN | flags::ACK, 65_535, &darwin_options()),
)
.expect("the reply parses");
assert_eq!(observed.window, 65_535);
assert_eq!(observed.effective_mss(), Some(1448));
assert_eq!(
observed.window_in_units(),
Some((45, 375)),
"the derived figures exist, and describe the path rather than the sender"
);
}
}