use std::{collections::BTreeSet, sync::Arc};
pub const MAX_CPES_PER_OS: usize = 50;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OsFingerprint {
name: Arc<str>,
family: Option<Arc<str>>,
generation: Option<Arc<str>>,
vendor: Option<Arc<str>>,
accuracy: u8,
kernel: Option<Arc<str>>,
detail_accuracy: Option<u8>,
cpe: BTreeSet<Arc<str>>,
evidence: Option<Arc<str>>,
}
impl OsFingerprint {
pub fn new(name: impl Into<Arc<str>>, accuracy: u8) -> Self {
Self {
name: name.into(),
family: None,
generation: None,
vendor: None,
accuracy: accuracy.min(100),
kernel: None,
detail_accuracy: None,
cpe: BTreeSet::new(),
evidence: None,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn family(&self) -> Option<&str> {
self.family.as_deref()
}
pub fn generation(&self) -> Option<&str> {
self.generation.as_deref()
}
pub fn vendor(&self) -> Option<&str> {
self.vendor.as_deref()
}
pub fn accuracy(&self) -> u8 {
self.accuracy
}
pub fn kernel(&self) -> Option<&str> {
self.kernel.as_deref()
}
#[must_use]
pub fn with_kernel(mut self, kernel: impl Into<Arc<str>>) -> Self {
self.kernel = Some(kernel.into());
self
}
pub fn detail_accuracy(&self) -> Option<u8> {
self.detail_accuracy
}
pub fn with_detail_accuracy(mut self, accuracy: u8) -> Self {
self.detail_accuracy = Some(accuracy.min(100));
self
}
pub fn with_family(mut self, family: impl Into<Arc<str>>) -> Self {
self.family = Some(family.into());
self
}
pub fn with_generation(mut self, generation: impl Into<Arc<str>>) -> Self {
self.generation = Some(generation.into());
self
}
pub fn with_vendor(mut self, vendor: impl Into<Arc<str>>) -> Self {
self.vendor = Some(vendor.into());
self
}
pub fn with_evidence(mut self, evidence: impl Into<Arc<str>>) -> Self {
self.evidence = Some(evidence.into());
self
}
pub fn evidence(&self) -> Option<&str> {
self.evidence.as_deref()
}
pub fn add_cpe(&mut self, cpe: impl Into<Arc<str>>) {
if self.cpe.len() < MAX_CPES_PER_OS {
self.cpe.insert(cpe.into());
}
}
pub fn cpes(&self) -> &BTreeSet<Arc<str>> {
&self.cpe
}
pub fn is_highly_confident(&self) -> bool {
self.accuracy >= 85
}
pub fn merge(&mut self, other: OsFingerprint) {
let OsFingerprint {
name,
family,
generation,
vendor,
accuracy,
kernel,
detail_accuracy,
cpe,
evidence,
} = other;
if accuracy > self.accuracy {
self.name = name;
self.accuracy = accuracy;
self.family = family.or(self.family.take());
self.generation = generation.or(self.generation.take());
self.vendor = vendor.or(self.vendor.take());
self.kernel = kernel.or(self.kernel.take());
self.detail_accuracy = detail_accuracy.or(self.detail_accuracy.take());
self.evidence = evidence.or(self.evidence.take());
} else if accuracy == self.accuracy {
self.evidence = if self.name == name {
join_evidence(self.evidence.take(), evidence)
} else {
self.evidence.take().or(evidence)
};
self.family = self.family.take().or(family);
self.generation = self.generation.take().or(generation);
self.vendor = self.vendor.take().or(vendor);
self.kernel = self.kernel.take().or(kernel);
self.detail_accuracy = self.detail_accuracy.take().or(detail_accuracy);
}
for cpe in cpe {
if self.cpe.len() >= MAX_CPES_PER_OS {
break;
}
self.cpe.insert(cpe);
}
}
}
const SEPARATOR: &str = " | ";
const MAX_EVIDENCE_LEN: usize = 512;
fn join_evidence(existing: Option<Arc<str>>, incoming: Option<Arc<str>>) -> Option<Arc<str>> {
match (existing, incoming) {
(Some(existing), Some(incoming)) => Some(join_readings(&existing, &incoming).into()),
(existing, incoming) => existing.or(incoming),
}
}
pub(super) fn join_readings(existing: &str, incoming: &str) -> String {
let mut parts: Vec<&str> = Vec::new();
for part in existing.split(SEPARATOR).chain(incoming.split(SEPARATOR)) {
if parts.iter().any(|kept| kept.starts_with(part)) {
continue;
}
parts.retain(|kept| !part.starts_with(kept));
parts.push(part);
}
let mut length = 0usize;
parts.retain(|part| {
let cost = part.len() + if length == 0 { 0 } else { SEPARATOR.len() };
let room = length + cost <= MAX_EVIDENCE_LEN;
if room {
length += cost;
}
room
});
parts.join(SEPARATOR)
}
impl std::fmt::Display for OsFingerprint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let family = self.family.as_deref().unwrap_or(&self.name);
write!(f, "{family} [{}%]", self.accuracy)?;
let names_a_release = &*self.name != family || self.generation.is_some();
if names_a_release {
write!(f, " · {}", self.name)?;
if let Some(generation) = &self.generation {
write!(f, " {generation}")?;
}
if let Some(accuracy) = self.detail_accuracy {
write!(f, " [{accuracy}%]")?;
}
}
if let Some(kernel) = &self.kernel {
write!(f, " · kernel {kernel}")?;
if let Some(accuracy) = self.detail_accuracy {
write!(f, " [{accuracy}%]")?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
#[test]
fn two_readings_of_one_system_are_both_kept() {
let mut passive = OsFingerprint::new("Linux", 65)
.with_evidence("syn-ack hops>=64 opts=M,S,T,N,W win=65160=45x1448 ws=7");
passive.merge(OsFingerprint::new("Linux", 65).with_evidence(
"syn-ack hops>=64 opts=M,S,T,N,W win=65160=45x1448 ws=7 \
id=zero isn=hashed ts=ticking",
));
let evidence = passive.evidence().expect("evidence survives");
assert!(
evidence.contains("isn=hashed"),
"the series reading is the one that cannot be got back: {evidence}"
);
}
#[test]
fn a_finding_shows_the_family_the_release_and_the_kernel_apart() {
let os = OsFingerprint::new("Debian", 93)
.with_family("Linux")
.with_generation("12")
.with_kernel("6.1.0")
.with_detail_accuracy(69);
assert_eq!(
os.to_string(),
"Linux [93%] · Debian 12 [69%] · kernel 6.1.0 [69%]"
);
}
#[test]
fn a_family_alone_renders_as_a_family_alone() {
let os = OsFingerprint::new("Linux", 65).with_family("Linux");
assert_eq!(os.to_string(), "Linux [65%]");
}
#[test]
fn a_kernel_without_a_release_is_still_reported() {
let os = OsFingerprint::new("Linux", 84)
.with_family("Linux")
.with_kernel("6.1.0")
.with_detail_accuracy(55);
assert_eq!(os.to_string(), "Linux [84%] · kernel 6.1.0 [55%]");
}
#[test]
fn a_tie_between_two_names_does_not_borrow_the_losers_reasoning() {
let mut linux = OsFingerprint::new("Linux", 65).with_evidence("a Linux-shaped reply");
linux.merge(OsFingerprint::new("Windows", 65).with_evidence("a Windows-shaped reply"));
assert_eq!(linux.name(), "Linux");
assert_eq!(linux.evidence(), Some("a Linux-shaped reply"));
}
#[test]
fn the_same_reading_twice_is_recorded_once() {
let mut host = OsFingerprint::new("Linux", 65).with_evidence("syn-ack hops>=64");
host.merge(OsFingerprint::new("Linux", 65).with_evidence("syn-ack hops>=64"));
assert_eq!(host.evidence(), Some("syn-ack hops>=64"));
}
#[test]
fn a_long_accumulation_is_cut_between_readings_not_inside_one() {
let reading = |n: usize| format!("reading {n} {}", "x".repeat(60));
let mut host = OsFingerprint::new("Linux", 65).with_evidence(reading(0));
for n in 1..40 {
host.merge(OsFingerprint::new("Linux", 65).with_evidence(reading(n)));
}
let evidence = host.evidence().expect("evidence survives");
assert!(evidence.len() <= MAX_EVIDENCE_LEN, "{}", evidence.len());
for part in evidence.split(SEPARATOR) {
assert!(
part.starts_with("reading ") && part.ends_with('x'),
"a reading was cut in half: {part:?}"
);
}
}
use super::*;
#[test]
fn an_accuracy_above_100_is_clamped_rather_than_kept() {
assert_eq!(OsFingerprint::new("Linux", 200).accuracy(), 100);
assert_eq!(OsFingerprint::new("Linux", 100).accuracy(), 100);
}
#[test]
fn high_confidence_starts_at_85() {
assert!(OsFingerprint::new("Linux", 85).is_highly_confident());
assert!(!OsFingerprint::new("Linux", 84).is_highly_confident());
}
#[test]
fn the_more_accurate_finding_names_the_host() {
let mut banner = OsFingerprint::new("Linux", 50);
banner.merge(OsFingerprint::new("Ubuntu", 90));
assert_eq!(banner.name(), "Ubuntu");
assert_eq!(banner.accuracy(), 90);
}
#[test]
fn a_tie_keeps_the_incumbent_and_fills_only_its_gaps() {
let mut first = OsFingerprint::new("Linux", 80).with_family("Unix-like");
first.merge(
OsFingerprint::new("Linux", 80)
.with_family("Something else")
.with_generation("5.15.0"),
);
assert_eq!(first.family(), Some("Unix-like"), "already recorded");
assert_eq!(first.generation(), Some("5.15.0"), "a gap, so filled");
}
#[test]
fn a_more_accurate_finding_takes_the_identity_but_not_at_the_cost_of_cpes() {
let mut banner = OsFingerprint::new("Linux", 40).with_vendor("Canonical");
banner.add_cpe("cpe:/o:canonical:ubuntu_linux");
let mut stack = OsFingerprint::new("Ubuntu 22.04", 90);
stack.add_cpe("cpe:/o:canonical:ubuntu_linux:22.04");
banner.merge(stack);
assert_eq!(banner.name(), "Ubuntu 22.04", "the surer name wins");
assert_eq!(banner.accuracy(), 90);
assert_eq!(
banner.vendor(),
Some("Canonical"),
"and a field the surer finding left empty is not erased"
);
assert_eq!(banner.cpes().len(), 2, "both identifiers still apply");
}
#[test]
fn the_cpe_list_is_bounded_by_both_routes_into_it() {
let mut os = OsFingerprint::new("Windows", 100);
for i in 0..MAX_CPES_PER_OS * 2 {
os.add_cpe(format!("cpe:/o:ident:{i}"));
}
assert_eq!(os.cpes().len(), MAX_CPES_PER_OS);
let mut other = OsFingerprint::new("Windows", 100);
for i in 0..MAX_CPES_PER_OS {
other.add_cpe(format!("cpe:/o:other:{i}"));
}
os.merge(other);
assert_eq!(os.cpes().len(), MAX_CPES_PER_OS);
}
}