use std::hash::{Hash, Hasher};
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
use crate::model::exclusion::Exclusions;
use crate::model::ip::set::IpSet;
use crate::model::target::TargetMap;
use crate::model::technique::TcpScanTechnique;
use crate::record::{PlanRecord, wire};
use crate::scanner::report::ScanKind;
#[derive(Debug, Clone)]
pub struct Plan(Resolved);
#[derive(Debug, Clone)]
enum Resolved {
Discovery { addresses: IpSet, sweep: bool },
PortScan {
targets: TargetMap,
technique: TcpScanTechnique,
},
}
impl Plan {
pub fn discovery(addresses: &IpSet, exclusions: &Exclusions, sweep: bool) -> Self {
let mut addresses = addresses.clone();
exclusions.withhold(&mut addresses);
addresses.canonicalize();
Self(Resolved::Discovery { addresses, sweep })
}
pub fn port_scan(
targets: &TargetMap,
exclusions: &Exclusions,
technique: TcpScanTechnique,
) -> Self {
let mut targets = targets.clone();
exclusions.withhold_targets(&mut targets);
Self(Resolved::PortScan { targets, technique })
}
pub fn kind(&self) -> ScanKind {
match self.0 {
Resolved::Discovery { .. } => ScanKind::Discovery,
Resolved::PortScan { .. } => ScanKind::PortScan,
}
}
pub fn total_targets(&self) -> u128 {
match &self.0 {
Resolved::Discovery { addresses, .. } => addresses.len(),
Resolved::PortScan { targets, .. } => targets.gross_targets().unwrap_or_default(),
}
}
pub fn addresses(&self) -> Option<&IpSet> {
match &self.0 {
Resolved::Discovery { addresses, .. } => Some(addresses),
Resolved::PortScan { .. } => None,
}
}
pub fn targets(&self) -> Option<&TargetMap> {
match &self.0 {
Resolved::PortScan { targets, .. } => Some(targets),
Resolved::Discovery { .. } => None,
}
}
pub fn technique(&self) -> Option<TcpScanTechnique> {
match &self.0 {
Resolved::PortScan { technique, .. } => Some(*technique),
Resolved::Discovery { .. } => None,
}
}
pub fn sweeps_the_segment(&self) -> bool {
matches!(self.0, Resolved::Discovery { sweep: true, .. })
}
pub fn record(&self) -> PlanRecord {
match &self.0 {
Resolved::Discovery { addresses, .. } => PlanRecord::from(addresses),
Resolved::PortScan { targets, .. } => PlanRecord::from(targets),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PlanFingerprint(u64);
impl PlanFingerprint {
pub fn of(plan: &Plan, privileged: bool) -> Self {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
wire::scan_kind_name(plan.kind()).hash(&mut hasher);
privileged.hash(&mut hasher);
match &plan.0 {
Resolved::Discovery { addresses, sweep } => {
sweep.hash(&mut hasher);
hash_addresses(addresses, &mut hasher);
}
Resolved::PortScan { targets, technique } => {
technique.hash(&mut hasher);
targets.units.len().hash(&mut hasher);
for unit in &targets.units {
hash_addresses(unit.ips(), &mut hasher);
let ports = unit.ports().to_vec();
ports.len().hash(&mut hasher);
for (port, protocol) in ports {
port.hash(&mut hasher);
protocol.hash(&mut hasher);
}
}
}
}
plan.total_targets().hash(&mut hasher);
Self(hasher.finish())
}
}
fn hash_addresses(ips: &IpSet, hasher: &mut impl Hasher) {
ips.v4().len().hash(hasher);
for range in ips.v4() {
range.start_addr().hash(hasher);
range.end_addr().hash(hasher);
}
ips.v6().len().hash(hasher);
for range in ips.v6() {
range.start_addr().hash(hasher);
range.end_addr().hash(hasher);
range.zone().hash(hasher);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
pub journal_version: u32,
pub id: String,
pub engine_version: String,
pub created_at: SystemTime,
#[serde(default)]
pub kind: String,
pub plan: PlanFingerprint,
#[serde(default)]
pub targets: PlanRecord,
#[serde(default)]
pub technique: String,
#[serde(default)]
pub sweep: bool,
#[serde(default)]
pub privileged: bool,
pub total_targets: u128,
pub summary: String,
}
impl Manifest {
pub fn new(
id: impl Into<String>,
plan: &Plan,
privileged: bool,
summary: impl Into<String>,
) -> Self {
Self {
journal_version: super::JOURNAL_VERSION,
id: id.into(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
created_at: SystemTime::now(),
kind: wire::scan_kind_name(plan.kind()).to_owned(),
plan: PlanFingerprint::of(plan, privileged),
targets: plan.record(),
technique: plan
.technique()
.map(|technique| technique.name().to_owned())
.unwrap_or_default(),
sweep: plan.sweeps_the_segment(),
privileged,
total_targets: plan.total_targets(),
summary: summary.into(),
}
}
pub fn kind(&self) -> ScanKind {
wire::scan_kind(&self.kind).unwrap_or(ScanKind::PortScan)
}
pub fn recorded(&self) -> Plan {
Plan(match self.kind() {
ScanKind::Discovery => Resolved::Discovery {
addresses: self.targets.addresses(),
sweep: self.sweep,
},
_ => Resolved::PortScan {
targets: TargetMap::from(&self.targets),
technique: self.technique(),
},
})
}
pub fn technique(&self) -> TcpScanTechnique {
self.technique.parse().unwrap_or_default()
}
pub fn covers(&self, plan: &Plan, privileged: bool) -> Result<(), PlanChanged> {
let found = PlanFingerprint::of(plan, privileged);
if found == self.plan {
return Ok(());
}
Err(PlanChanged {
expected: self.plan,
found,
expected_targets: self.total_targets,
found_targets: plan.total_targets(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PlanChanged {
pub expected: PlanFingerprint,
pub found: PlanFingerprint,
pub expected_targets: u128,
pub found_targets: u128,
}
impl std::fmt::Display for PlanChanged {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"this journal was written against a different plan, so its recorded \
positions would name different targets"
)?;
if self.expected_targets != self.found_targets {
write!(
f,
" ({} targets then, {} now)",
self.expected_targets, self.found_targets
)?;
} else {
write!(
f,
" (the same {} targets, differently arranged, or a different \
technique or privilege level)",
self.expected_targets
)?;
}
Ok(())
}
}
impl std::error::Error for PlanChanged {}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::ip::set::IpSet;
use crate::model::port::PortSet;
use crate::model::target::TargetSet;
fn plan(pairs: &[(&str, &str)]) -> TargetMap {
let mut map = TargetMap::new();
for (range, ports) in pairs {
map.add_unit(TargetSet::new(
range.parse::<IpSet>().expect("a range"),
ports.parse::<PortSet>().expect("ports"),
));
}
map
}
fn ports(map: &TargetMap) -> Plan {
Plan::port_scan(map, &Exclusions::none(), TcpScanTechnique::Syn)
}
fn print(map: &TargetMap) -> PlanFingerprint {
PlanFingerprint::of(&ports(map), true)
}
fn addresses(written: &str) -> IpSet {
written.parse().expect("a range")
}
fn sweeping(ips: &IpSet, sweep: bool) -> Plan {
Plan::discovery(ips, &Exclusions::none(), sweep)
}
#[test]
fn the_same_plan_fingerprints_the_same() {
let a = plan(&[("192.0.2.1-192.0.2.10", "80,443")]);
let b = plan(&[("192.0.2.1-192.0.2.10", "80,443")]);
assert_eq!(print(&a), print(&a), "not stable within one value");
assert_eq!(print(&a), print(&b), "not stable across equal values");
}
#[test]
fn any_change_that_renumbers_targets_changes_the_fingerprint() {
let base = plan(&[("192.0.2.1-192.0.2.10", "80,443")]);
let original = print(&base);
for (what, changed) in [
(
"a port added",
plan(&[("192.0.2.1-192.0.2.10", "80,443,8080")]),
),
("a port removed", plan(&[("192.0.2.1-192.0.2.10", "80")])),
(
"the range widened",
plan(&[("192.0.2.1-192.0.2.20", "80,443")]),
),
(
"the range narrowed",
plan(&[("192.0.2.1-192.0.2.5", "80,443")]),
),
(
"a unit added",
plan(&[("192.0.2.1-192.0.2.10", "80,443"), ("198.51.100.1", "22")]),
),
] {
assert_ne!(
original,
print(&changed),
"{what} left the fingerprint alone"
);
}
}
#[test]
fn the_order_of_the_ports_is_part_of_the_plan() {
let ascending = plan(&[("192.0.2.1", "80,443")]);
let descending = plan(&[("192.0.2.1", "443,80")]);
let same_order =
ascending.units[0].ports().to_vec() == descending.units[0].ports().to_vec();
assert_eq!(
print(&ascending) == print(&descending),
same_order,
"the fingerprint must follow the enumeration, whichever way the set orders it"
);
}
#[test]
fn the_shape_of_the_units_is_not_flattened_away() {
let split = plan(&[
("192.0.2.1-192.0.2.5", "80"),
("192.0.2.6-192.0.2.10", "80"),
]);
let joined = plan(&[("192.0.2.1-192.0.2.10", "80")]);
assert_eq!(
split.gross_targets().unwrap(),
joined.gross_targets().unwrap(),
"the same ten targets either way, which is what makes this the trap"
);
assert_ne!(
print(&split),
print(&joined),
"two units enumerate differently from one"
);
}
#[test]
fn privilege_and_technique_are_part_of_the_plan() {
let map = plan(&[("192.0.2.1-192.0.2.10", "80,443")]);
assert_ne!(
PlanFingerprint::of(&ports(&map), true),
PlanFingerprint::of(&ports(&map), false),
"privilege decides which question the probes answered"
);
assert_ne!(
PlanFingerprint::of(&ports(&map), true),
PlanFingerprint::of(
&Plan::port_scan(&map, &Exclusions::none(), TcpScanTechnique::Fin),
true
),
"a technique decides what silence means"
);
}
#[test]
fn a_manifest_covers_its_own_plan_and_refuses_another() {
let original = plan(&[("192.0.2.1-192.0.2.10", "80,443")]);
let manifest = Manifest::new(
"01J8Z5Q7VN",
&ports(&original),
true,
"192.0.2.1-192.0.2.10 on 2 ports",
);
assert_eq!(manifest.total_targets, 20);
assert_eq!(manifest.kind(), ScanKind::PortScan);
assert!(manifest.covers(&ports(&original), true).is_ok());
let widened = plan(&[("192.0.2.1-192.0.2.20", "80,443")]);
let refused = manifest
.covers(&ports(&widened), true)
.expect_err("a widened plan renumbers every position past the first host");
assert_eq!(refused.expected_targets, 20);
assert_eq!(refused.found_targets, 40);
assert!(
refused.to_string().contains("20 targets then, 40 now"),
"{refused}"
);
}
#[test]
fn a_sweep_is_never_the_same_plan_as_a_port_scan() {
let ips = addresses("192.0.2.1-192.0.2.10");
let map = plan(&[("192.0.2.1-192.0.2.10", "80")]);
assert_ne!(
PlanFingerprint::of(&sweeping(&ips, false), true),
print(&map),
"the same ten addresses, asked two different questions"
);
let manifest = Manifest::new("01J8Z5Q7VN", &sweeping(&ips, false), true, "");
assert_eq!(manifest.kind(), ScanKind::Discovery);
assert_eq!(manifest.total_targets, 10, "a sweep counts addresses");
assert!(
manifest.covers(&ports(&map), true).is_err(),
"a sweep's journal must not accept a port scan's plan"
);
}
#[test]
fn a_segment_sweep_is_not_a_targeted_pass() {
let ips = addresses("192.0.2.1-192.0.2.10");
assert_ne!(
PlanFingerprint::of(&sweeping(&ips, true), true),
PlanFingerprint::of(&sweeping(&ips, false), true)
);
}
#[test]
fn a_sweeps_addresses_survive_the_round_trip() {
let ips = addresses("192.0.2.1-192.0.2.10,2001:db8::1");
let manifest = Manifest::new("01J8Z5Q7VN", &sweeping(&ips, false), true, "");
assert_eq!(
manifest.recorded().addresses().map(IpSet::len),
Some(ips.len())
);
assert!(
manifest
.covers(
&sweeping(
&manifest.recorded().addresses().cloned().unwrap_or_default(),
false
),
true
)
.is_ok(),
"a plan rebuilt from the record must fingerprint as the original"
);
}
#[test]
fn a_link_local_plan_comes_back_in_the_order_it_was_counted() {
let mut ips = IpSet::new();
for (zone, last) in [(9u32, 4u16), (3, 6), (7, 2)] {
ips.insert_range(crate::model::ip::range::IpRange::V6(
crate::model::ip::range::Ipv6Range::scoped(
"fe80::1".parse().expect("an address"),
format!("fe80::{last}").parse().expect("an address"),
Some(zone),
)
.expect("a range"),
));
}
ips.canonicalize();
let manifest = Manifest::new("01J8Z5Q7VN", &sweeping(&ips, false), true, "");
let recovered = manifest
.recorded()
.addresses()
.cloned()
.expect("a sweep's plan");
assert_eq!(
recovered.iter().collect::<Vec<_>>(),
ips.iter().collect::<Vec<_>>(),
"the same addresses in the same order, so positions still mean what they did"
);
assert!(
manifest.covers(&sweeping(&recovered, false), true).is_ok(),
"and the plan rebuilt from the record fingerprints as the original"
);
}
#[test]
fn a_refusal_over_an_equal_count_says_so_rather_than_reporting_a_change() {
let map = plan(&[("192.0.2.1-192.0.2.10", "80,443")]);
let manifest = Manifest::new("01J8Z5Q7VN", &ports(&map), true, "");
let refused = manifest
.covers(
&Plan::port_scan(&map, &Exclusions::none(), TcpScanTechnique::Fin),
true,
)
.expect_err("a different technique is a different plan");
assert_eq!(refused.expected_targets, refused.found_targets);
let message = refused.to_string();
assert!(message.contains("differently arranged"), "{message}");
assert!(!message.contains("then,"), "{message}");
}
}