use std::collections::HashMap;
use std::net::IpAddr;
use tokio::sync::mpsc::UnboundedSender;
use crate::config::limits;
use crate::config::{ProbeTuning, ZondConfig};
use crate::model::exclusion::Exclusions;
use crate::model::ip::range::{IpRange, Ipv6Range};
use crate::model::ip::scoped::ZoneMap;
use crate::model::ip::set::IpSet;
use crate::model::port::Protocol;
use crate::model::technique::TcpScanTechnique;
use crate::report::ScannerKind;
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::connect::{
ConnectPortScanner, ConnectScanner, ConnectUdpPortScanner,
};
use crate::scanner::strategy::local::{LocalScanner, Scope};
use crate::scanner::strategy::ports::{
IdlePortScanner, SctpPortScanner, TcpPortScanner, UdpPortScanner,
};
use crate::scanner::strategy::routed::RoutedScanner;
use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
use crate::system::interface::Link;
use crate::system::interface::{self, RoutedTarget};
use crate::system::neighbor_cache;
use crate::system::privilege::Privilege;
use crate::{counted, info, warn};
#[derive(Debug, Clone)]
pub struct RefusedStep {
pub scanner: ScannerKind,
pub reason: String,
}
impl RefusedStep {
pub fn technique_needs_raw_sockets(technique: TcpScanTechnique) -> Self {
Self {
scanner: ScannerKind::for_raw_tcp(technique),
reason: format!(
"the {technique} technique needs raw sockets, which this process does \
not have, and a connect scan answers a different question - so no TCP \
port was probed"
),
}
}
pub fn sctp_needs_raw_sockets() -> Self {
Self {
scanner: ScannerKind::SctpPort,
reason: "the sctp ports named for this scan need raw sockets, which this process \
does not have, and there is no unprivileged init probe - so no sctp port \
was probed"
.to_string(),
}
}
pub fn sctp_not_in_an_idle_scan() -> Self {
Self {
scanner: ScannerKind::SctpPort,
reason: "an idle scan reads a third party's counter, which carries no sctp probe, \
and sending one directly would put this host's address on the target - so \
no sctp port was probed"
.to_string(),
}
}
pub(crate) fn technique_beyond_frames(technique: TcpScanTechnique, targets: u128) -> Self {
Self {
scanner: ScannerKind::for_raw_tcp(technique),
reason: format!(
"this process can send self-built frames and holds no raw socket, and {} \
out of a frame's reach; a connect scan answers a different question than \
the {technique} technique asks - so no TCP port on them was probed",
counted(targets, "target is", "targets are")
),
}
}
pub(crate) fn sctp_beyond_frames(targets: u128) -> Self {
Self {
scanner: ScannerKind::SctpPort,
reason: format!(
"this process can send self-built frames and holds no raw socket, and {} \
out of a frame's reach; there is no unprivileged init probe - so no sctp \
port on them was probed",
counted(targets, "target is", "targets are")
),
}
}
pub(crate) fn pass_beyond_frames(scanner: ScannerKind, pass: &str, hosts: u128) -> Self {
Self {
scanner,
reason: format!(
"this process can send self-built frames and holds no raw socket, and {} \
out of a frame's reach - so {pass} left {} alone",
counted(hosts, "host is", "hosts are"),
if hosts == 1 { "it" } else { "them" },
),
}
}
pub(crate) fn idle_zombie_excluded(zombie: IpAddr) -> Self {
Self {
scanner: ScannerKind::Idle,
reason: format!(
"the idle scan's zombie {zombie} is excluded, and the scan reads its counter \
by probing it again and again - and scanning the target under this host's \
own address instead would betray the scan, so no TCP port was probed"
),
}
}
pub fn idle_needs_privilege() -> Self {
Self {
scanner: ScannerKind::Idle,
reason: "an idle scan forges the source address of its probes, which needs \
a self-built frame this process cannot open without privilege - and \
scanning the target under this host's own address instead would \
betray the scan, so no TCP port was probed"
.to_owned(),
}
}
pub fn routed_range_not_enumerable(range: &Ipv6Range) -> Self {
Self {
scanner: ScannerKind::Routed,
reason: format!(
"{}: too large to probe one address at a time, and routed IPv6 has \
no other strategy yet. Give specific addresses or a smaller prefix.",
describe(range)
),
}
}
pub fn unprivileged_range_not_enumerable(range: &Ipv6Range) -> Self {
Self {
scanner: ScannerKind::Connect,
reason: format!(
"{}: too large to probe one address at a time, and an unprivileged \
scan has no other strategy. Run with root to sweep a segment this \
size, or give specific addresses or a smaller prefix.",
describe(range)
),
}
}
pub fn link_local_port_target_needs_an_interface(range: &Ipv6Range) -> Self {
let target = name(range);
Self {
scanner: ScannerKind::SynPort,
reason: format!(
"{target} is link-local and names no interface, so it names a \
different machine on every segment this host is on. Say which: \
{}%en0, naming the interface the segment is reached through.",
range.start_addr()
),
}
}
pub fn link_local_port_target_names_two_segments(range: &Ipv6Range) -> Self {
let target = name(range);
Self {
scanner: ScannerKind::SynPort,
reason: format!(
"{target} was named on two interfaces at once, and each is a \
different machine. Scan one segment at a time."
),
}
}
pub fn local_range_needs_a_sweep(range: &Ipv6Range) -> Self {
Self {
scanner: ScannerKind::Local,
reason: format!(
"{}: too large to probe one address at a time, and this scan is \
not sweeping the segment. The all-nodes solicitation reaches a \
prefix this size in one packet - scan the segment rather than \
the range, or give specific addresses.",
describe(range)
),
}
}
}
fn withhold_unwalkable(targets: &mut IpSet) -> Vec<Ipv6Range> {
let unwalkable: Vec<Ipv6Range> = targets
.v6()
.iter()
.filter(|range| !interface::is_enumerable(range))
.copied()
.collect();
if unwalkable.is_empty() {
return unwalkable;
}
let mut kept = IpSet::new();
for range in targets.v4() {
kept.push_v4_range(*range);
}
for range in targets.v6() {
if interface::is_enumerable(range) {
kept.push_v6_range(*range);
}
}
kept.canonicalize();
*targets = kept;
unwalkable
}
impl From<RefusedStep> for crate::report::Refusal {
fn from(step: RefusedStep) -> Self {
Self::new(step.scanner, step.reason)
}
}
fn name(range: &Ipv6Range) -> String {
match range.start_addr() == range.end_addr() {
true => range.start_addr().to_string(),
false => format!("{}-{}", range.start_addr(), range.end_addr()),
}
}
fn describe(range: &Ipv6Range) -> String {
format!(
"{}-{} is {} addresses",
range.start_addr(),
range.end_addr(),
range.len()
)
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DiscoveryStep {
Local {
interface: Box<Link>,
targets: IpSet,
scope: Scope,
},
Routed {
targets: Vec<RoutedTarget>,
},
RoutedSctp {
targets: Vec<RoutedTarget>,
port: u16,
},
Connect {
targets: IpSet,
},
}
impl DiscoveryStep {
pub fn kind(&self) -> ScannerKind {
match self {
Self::Local { .. } => ScannerKind::Local,
Self::Routed { .. } => ScannerKind::Routed,
Self::RoutedSctp { .. } => ScannerKind::RoutedSctp,
Self::Connect { .. } => ScannerKind::Connect,
}
}
pub fn target_count(&self) -> u128 {
match self {
Self::Local { targets, .. } | Self::Connect { targets } => targets.len(),
Self::Routed { targets } | Self::RoutedSctp { targets, .. } => targets.len() as u128,
}
}
pub fn into_scanner(
self,
ctx: ScanContext,
dns_tx: Option<UnboundedSender<IpAddr>>,
tuning: ProbeTuning,
) -> Result<Box<dyn HostScanner>, StrategyError> {
match self {
Self::Local {
interface,
targets,
scope,
} => Ok(Box::new(LocalScanner::new(
*interface,
targets,
ctx,
dns_tx,
scope,
tuning.retry,
)?)),
Self::Routed { targets } => {
Ok(Box::new(RoutedScanner::new(targets, ctx, dns_tx, tuning)?))
}
Self::RoutedSctp { targets, port } => Ok(Box::new(RoutedScanner::over_sctp(
targets, ctx, dns_tx, tuning, port,
)?)),
Self::Connect { targets } => {
Ok(Box::new(ConnectScanner::new(targets, ctx, &tuning.evasion)))
}
}
}
}
#[derive(Debug, Clone)]
pub struct DiscoveryPlan {
steps: Vec<DiscoveryStep>,
refusals: Vec<RefusedStep>,
ours: IpSet,
}
impl DiscoveryPlan {
pub fn build(targets: IpSet, scope: Scope, exclusions: &Exclusions, forced: &[IpAddr]) -> Self {
let mut steps = Vec::new();
let mut refusals = Vec::new();
let interface::RoutedTargets {
mut local,
routed,
unmapped,
ours,
ambiguous,
unenumerable,
} = interface::map_ips_to_interfaces_forced(targets, forced);
for range in &ambiguous {
refusals.push(RefusedStep {
scanner: ScannerKind::Local,
reason: format!(
"{} is link-local, so it names a different machine on every \
segment. Say which: {}%<interface>.",
range.start_addr(),
range.start_addr()
),
});
}
for range in &unenumerable {
refusals.push(RefusedStep::routed_range_not_enumerable(range));
}
if matches!(scope, Scope::Sweep) {
include_swept_link(&mut local);
seed_from_neighbor_table(&mut local, exclusions);
}
for (interface, mut targets) in local {
for range in withhold_unwalkable(&mut targets) {
match scope {
Scope::Sweep => info!(
verbosity = 1,
"{} is swept by solicitation rather than walked",
describe(&range)
),
Scope::Targeted => {
refusals.push(RefusedStep::local_range_needs_a_sweep(&range))
}
}
}
if targets.is_empty() && matches!(scope, Scope::Targeted) {
continue;
}
if matches!(scope, Scope::Sweep) {
info!(
verbosity = 1,
"sweeping {}: {}",
interface.name(),
match targets.len() {
0 => "IPv6 neighbours only, having no IPv4 range to walk".to_string(),
count => counted(count, "address", "addresses"),
}
);
}
steps.push(DiscoveryStep::Local {
interface: Box::new(interface),
targets,
scope,
});
}
if !routed.is_empty() {
steps.push(DiscoveryStep::Routed { targets: routed });
}
if !unmapped.is_empty() {
steps.push(DiscoveryStep::Connect { targets: unmapped });
}
Self {
steps,
refusals,
ours,
}
}
pub fn also_over_sctp(&mut self, port: u16) {
let sctp: Vec<DiscoveryStep> = self
.steps
.iter()
.filter_map(|step| match step {
DiscoveryStep::Routed { targets } => Some(DiscoveryStep::RoutedSctp {
targets: targets.clone(),
port,
}),
_ => None,
})
.collect();
self.steps.extend(sctp);
}
pub(crate) fn withhold(&mut self, targets: &IpSet) -> IpSet {
let mut taken = IpSet::new();
if targets.is_empty() {
return taken;
}
for step in &mut self.steps {
match step {
DiscoveryStep::Local { targets: held, .. } => {
let mut kept = held.clone();
kept.subtract(targets);
let mut gone = held.clone();
gone.subtract(&kept);
for range in gone.v4() {
taken.push_v4_range(*range);
}
for range in gone.v6() {
taken.push_v6_range(*range);
}
*held = kept;
}
DiscoveryStep::Routed { targets: held }
| DiscoveryStep::RoutedSctp { targets: held, .. } => held.retain(|routed| {
let out = targets.contains(&routed.target);
if out {
taken.insert(routed.target);
}
!out
}),
DiscoveryStep::Connect { .. } => {}
}
}
self.steps.retain(|step| match step {
DiscoveryStep::Local {
interface,
targets,
scope,
} => {
!targets.is_empty() || (matches!(scope, Scope::Sweep) && interface.carries_frames())
}
DiscoveryStep::Routed { targets } | DiscoveryStep::RoutedSctp { targets, .. } => {
!targets.is_empty()
}
DiscoveryStep::Connect { .. } => true,
});
taken.canonicalize();
taken
}
pub(crate) fn connect_instead(&mut self, targets: &IpSet) -> IpSet {
let moved = self.withhold(targets);
if moved.is_empty() {
return moved;
}
let existing = self.steps.iter_mut().find_map(|step| match step {
DiscoveryStep::Connect { targets } => Some(targets),
_ => None,
});
match existing {
Some(held) => {
for range in moved.v4() {
held.push_v4_range(*range);
}
for range in moved.v6() {
held.push_v6_range(*range);
}
held.canonicalize();
}
None => self.steps.push(DiscoveryStep::Connect {
targets: moved.clone(),
}),
}
moved
}
pub fn steps(&self) -> &[DiscoveryStep] {
&self.steps
}
pub fn steps_mut(&mut self) -> &mut Vec<DiscoveryStep> {
&mut self.steps
}
pub fn ours(&self) -> &IpSet {
&self.ours
}
pub fn refusals(&self) -> &[RefusedStep] {
&self.refusals
}
pub fn into_steps(self) -> Vec<DiscoveryStep> {
self.steps
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PortScanStep {
RawTcp {
technique: TcpScanTechnique,
},
RawUdp,
RawSctp,
ConnectTcp,
ConnectUdp,
Idle {
zombie: IpAddr,
zombie_port: Option<u16>,
},
}
impl PortScanStep {
pub fn kind(&self) -> ScannerKind {
match self {
Self::RawTcp { technique } => ScannerKind::for_raw_tcp(*technique),
Self::RawUdp => ScannerKind::UdpPort,
Self::RawSctp => ScannerKind::SctpPort,
Self::ConnectTcp => ScannerKind::Connect,
Self::ConnectUdp => ScannerKind::ConnectUdp,
Self::Idle { .. } => ScannerKind::Idle,
}
}
pub fn protocol(&self) -> Protocol {
match self {
Self::RawTcp { .. } | Self::ConnectTcp | Self::Idle { .. } => Protocol::Tcp,
Self::RawUdp | Self::ConnectUdp => Protocol::Udp,
Self::RawSctp => Protocol::Sctp,
}
}
pub fn is_raw(&self) -> bool {
matches!(self, Self::RawTcp { .. } | Self::RawUdp | Self::RawSctp)
}
pub fn into_scanner(
self,
ctx: ScanContext,
target_count: usize,
tuning: ProbeTuning,
zones: ZoneMap,
) -> Result<Box<dyn PortScanner>, StrategyError> {
match self {
Self::RawTcp { technique } => Ok(Box::new(TcpPortScanner::new(
interface::SourceResolver::from_system()
.with_zones(zones)
.with_forced(tuning.send_source.clone()),
ctx,
technique,
target_count,
tuning,
)?)),
Self::RawUdp => Ok(Box::new(UdpPortScanner::new(
interface::SourceResolver::from_system()
.with_zones(zones)
.with_forced(tuning.send_source.clone()),
ctx,
target_count,
tuning,
)?)),
Self::RawSctp => Ok(Box::new(SctpPortScanner::new(
interface::SourceResolver::from_system()
.with_zones(zones)
.with_forced(tuning.send_source.clone()),
ctx,
target_count,
tuning,
)?)),
Self::ConnectTcp => Ok(Box::new(
ConnectPortScanner::new(
ctx,
limits::CONNECT_CONCURRENCY,
tuning.service_detection,
&tuning.evasion,
)
.with_zones(zones),
)),
Self::ConnectUdp => Ok(Box::new(
ConnectUdpPortScanner::with_detection(
ctx,
limits::CONNECT_CONCURRENCY,
&tuning.evasion,
tuning.service_detection,
)
.with_zones(zones),
)),
Self::Idle {
zombie,
zombie_port,
} => Ok(Box::new(IdlePortScanner::new(
ctx,
zombie,
zombie_port,
tuning,
)?)),
}
}
}
#[derive(Debug, Clone)]
pub struct PortScanPlan {
steps: Vec<PortScanStep>,
refusals: Vec<RefusedStep>,
refused: Vec<Protocol>,
technique: TcpScanTechnique,
}
impl PortScanPlan {
pub fn build(cfg: &ZondConfig, privilege: Privilege) -> Self {
let mut plan = Self {
steps: Vec::new(),
refusals: Vec::new(),
refused: Vec::new(),
technique: cfg.tcp_technique,
};
if let Some(idle) = &cfg.idle_scan {
if cfg.exclusions.excludes(&idle.zombie) {
plan.refuse(
Protocol::Tcp,
RefusedStep::idle_zombie_excluded(idle.zombie),
);
} else if privilege.is_raw() {
plan.steps.push(PortScanStep::Idle {
zombie: idle.zombie,
zombie_port: idle.zombie_port,
});
} else {
plan.refuse(Protocol::Tcp, RefusedStep::idle_needs_privilege());
}
return plan;
}
let raw = privilege.is_raw() && interface::SourceResolver::from_system().has_sources();
if privilege.is_raw() && !raw {
warn!("no usable network interface found; using TCP connect fallback");
}
if raw {
plan.steps.push(PortScanStep::RawTcp {
technique: cfg.tcp_technique,
});
plan.steps.push(PortScanStep::RawUdp);
} else if cfg.tcp_technique.has_connect_fallback() {
plan.steps.push(PortScanStep::ConnectTcp);
plan.steps.push(PortScanStep::ConnectUdp);
} else {
plan.refuse(
Protocol::Tcp,
RefusedStep::technique_needs_raw_sockets(cfg.tcp_technique),
);
plan.steps.push(PortScanStep::ConnectUdp);
}
plan
}
fn refuse(&mut self, protocol: Protocol, refusal: RefusedStep) {
self.refusals.push(refusal);
self.refused.push(protocol);
}
pub fn technique(&self) -> TcpScanTechnique {
self.technique
}
pub fn steps(&self) -> &[PortScanStep] {
&self.steps
}
pub fn steps_mut(&mut self) -> &mut Vec<PortScanStep> {
&mut self.steps
}
pub fn refusals(&self) -> &[RefusedStep] {
&self.refusals
}
pub fn into_steps(self) -> Vec<PortScanStep> {
self.steps
}
pub fn cover_sctp(&mut self, privilege: Privilege) {
if self
.steps
.iter()
.any(|step| matches!(step, PortScanStep::Idle { .. }))
{
self.refuse(Protocol::Sctp, RefusedStep::sctp_not_in_an_idle_scan());
return;
}
if privilege.is_raw() && interface::SourceResolver::from_system().has_sources() {
self.steps.push(PortScanStep::RawSctp);
} else {
self.refuse(Protocol::Sctp, RefusedStep::sctp_needs_raw_sockets());
}
}
pub(crate) fn refuses(&self, protocol: Protocol) -> bool {
self.refused.contains(&protocol)
}
pub fn covers(&self, protocol: Protocol) -> bool {
self.steps.iter().any(|step| step.protocol() == protocol)
}
}
fn include_swept_link(local: &mut HashMap<Link, IpSet>) {
let Some(link) = interface::lan_link() else {
return;
};
if local.keys().any(|intf| intf.name() == link.link.name()) {
return;
}
local.insert(link.link, IpSet::new());
}
fn seed_from_neighbor_table(local: &mut HashMap<Link, IpSet>, exclusions: &Exclusions) {
let table = neighbor_cache::ipv6_neighbors();
if !table.is_empty() {
seed_from_neighbor_table_with(local, &table, exclusions);
}
}
fn seed_from_neighbor_table_with(
local: &mut HashMap<Link, IpSet>,
table: &[neighbor_cache::Neighbor],
exclusions: &Exclusions,
) {
for (intf, targets) in local.iter_mut() {
let mut seeded = 0usize;
for addr in candidates_for(intf, table) {
if exclusions.excludes(&addr) {
info!(
verbosity = 2,
"neighbour {addr} is excluded, so it is not taken as a candidate"
);
continue;
}
let IpAddr::V6(addr) = addr else { continue };
let zone = addr.is_unicast_link_local().then_some(intf.index());
if let Ok(range) = Ipv6Range::scoped(addr, addr, zone) {
targets.insert_range(IpRange::V6(range));
seeded += 1;
}
}
if seeded > 0 {
targets.canonicalize();
info!(
verbosity = 1,
"took {} from the neighbour table as candidates on {}",
counted(seeded as u128, "IPv6 address", "IPv6 addresses"),
intf.name()
);
}
}
}
fn candidates_for(link: &Link, table: &[neighbor_cache::Neighbor]) -> Vec<IpAddr> {
let own: std::collections::HashSet<IpAddr> =
link.addresses().iter().map(|held| held.address()).collect();
table
.iter()
.filter(|entry| entry.interface_index == link.index())
.filter(|entry| !own.contains(&entry.ip))
.filter(|entry| match entry.ip {
IpAddr::V6(addr) => !addr.is_loopback() && !addr.is_unspecified(),
IpAddr::V4(_) => false,
})
.map(|entry| entry.ip)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn v6(addr: &str) -> IpAddr {
addr.parse().unwrap()
}
fn interface_with(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
use crate::system::interface::LinkAddress;
Link::new(name, index).with_addresses(
own.into_iter()
.map(|ip| LinkAddress::new(ip, if ip.is_ipv4() { 24 } else { 64 }))
.collect(),
)
}
fn entry(ip: &str, index: u32) -> neighbor_cache::Neighbor {
neighbor_cache::Neighbor {
ip: v6(ip),
mac: None,
interface_index: index,
}
}
fn framed(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
interface_with(index, name, own)
.with_mac(crate::model::mac::MacAddr::new(0x02, 0, 0, 0, 0, 0x10))
}
fn set_of(addresses: &[&str]) -> IpSet {
let mut set = IpSet::new();
for address in addresses {
set.insert(v6(address));
}
set
}
#[test]
fn what_a_frame_cannot_reach_moves_to_the_connect_step() {
let mut plan = DiscoveryPlan {
ours: IpSet::new(),
steps: vec![
DiscoveryStep::Local {
interface: Box::new(interface_with(20, "utun9", vec![v6("198.51.100.2")])),
targets: set_of(&["198.51.100.7"]),
scope: Scope::Targeted,
},
DiscoveryStep::Local {
interface: Box::new(framed(4, "en0", vec![v6("192.0.2.10")])),
targets: set_of(&["192.0.2.50"]),
scope: Scope::Targeted,
},
DiscoveryStep::Routed {
targets: vec![
RoutedTarget {
target: v6("203.0.113.23"),
source: v6("198.51.100.2"),
},
RoutedTarget {
target: v6("203.0.113.9"),
source: v6("192.0.2.10"),
},
],
},
],
refusals: Vec::new(),
};
let moved = plan.connect_instead(&set_of(&["198.51.100.7", "203.0.113.23"]));
assert_eq!(moved.len(), 2);
let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
assert_eq!(
kinds,
vec![
ScannerKind::Local,
ScannerKind::Routed,
ScannerKind::Connect
],
"the tunnel's local step is gone and a connect step has arrived"
);
match &plan.steps()[1] {
DiscoveryStep::Routed { targets } => {
assert_eq!(targets.len(), 1);
assert_eq!(targets[0].target, v6("203.0.113.9"));
}
other => panic!("expected the routed step, found {other:?}"),
}
match &plan.steps()[2] {
DiscoveryStep::Connect { targets } => assert_eq!(*targets, moved),
other => panic!("expected the connect step, found {other:?}"),
}
}
#[test]
fn a_sweeps_step_stays_on_a_framed_link_and_goes_on_a_tunnel() {
let mut plan = DiscoveryPlan {
ours: IpSet::new(),
steps: vec![
DiscoveryStep::Local {
interface: Box::new(framed(4, "en0", vec![v6("192.0.2.10")])),
targets: set_of(&["192.0.2.50"]),
scope: Scope::Sweep,
},
DiscoveryStep::Local {
interface: Box::new(interface_with(20, "utun9", vec![v6("198.51.100.2")])),
targets: set_of(&["198.51.100.7"]),
scope: Scope::Sweep,
},
],
refusals: Vec::new(),
};
plan.withhold(&set_of(&["192.0.2.50", "198.51.100.7"]));
assert_eq!(plan.steps().len(), 1);
match &plan.steps()[0] {
DiscoveryStep::Local {
interface, targets, ..
} => {
assert_eq!(interface.name(), "en0");
assert!(targets.is_empty());
}
other => panic!("expected the sweep's own step, found {other:?}"),
}
}
#[test]
fn withholding_leaves_the_connect_step_as_it_was() {
let mut plan = DiscoveryPlan {
ours: IpSet::new(),
steps: vec![DiscoveryStep::Connect {
targets: set_of(&["127.0.0.1"]),
}],
refusals: Vec::new(),
};
let taken = plan.withhold(&set_of(&["127.0.0.1"]));
assert!(taken.is_empty(), "nothing was taken from a frame step");
match &plan.steps()[0] {
DiscoveryStep::Connect { targets } => assert_eq!(*targets, set_of(&["127.0.0.1"])),
other => panic!("expected the connect step, found {other:?}"),
}
}
#[test]
fn an_sctp_sweep_is_added_to_the_routed_steps_alone() {
let mut plan = DiscoveryPlan {
ours: IpSet::new(),
steps: vec![
DiscoveryStep::Routed {
targets: vec![RoutedTarget {
target: v6("192.0.2.1"),
source: v6("192.0.2.9"),
}],
},
DiscoveryStep::Connect {
targets: IpSet::new(),
},
],
refusals: Vec::new(),
};
plan.also_over_sctp(3868);
let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
assert_eq!(
kinds,
vec![
ScannerKind::Routed,
ScannerKind::Connect,
ScannerKind::RoutedSctp
]
);
assert!(matches!(
plan.steps().last(),
Some(DiscoveryStep::RoutedSctp { port: 3868, .. })
));
}
#[test]
fn sctp_without_raw_sockets_is_refused_rather_than_substituted() {
let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
plan.cover_sctp(Privilege::Connect);
assert!(!plan.covers(Protocol::Sctp));
assert!(
plan.refusals()
.iter()
.any(|refusal| refusal.scanner == ScannerKind::SctpPort),
"the sctp ports went unprobed and nothing in the report said so"
);
}
#[test]
fn an_idle_scan_refuses_sctp_rather_than_probing_it_directly() {
let cfg = ZondConfig {
idle_scan: Some(crate::config::IdleScan::new(v6("192.0.2.9"))),
..ZondConfig::default()
};
let mut plan = PortScanPlan::build(&cfg, Privilege::Raw);
plan.cover_sctp(Privilege::Raw);
assert!(!plan.covers(Protocol::Sctp));
let refusal = plan
.refusals()
.iter()
.find(|refusal| refusal.scanner == ScannerKind::SctpPort)
.expect("the sctp ports are accounted for");
assert!(
refusal.reason.contains("idle"),
"the reason names something other than the idle scan: {}",
refusal.reason
);
}
#[test]
fn an_idle_scan_through_an_excluded_zombie_is_refused() {
let zombie = v6("192.0.2.9");
let mut forbidden = IpSet::new();
forbidden.insert(zombie);
let cfg = ZondConfig {
idle_scan: Some(crate::config::IdleScan::new(zombie)),
exclusions: Exclusions::new(forbidden),
..ZondConfig::default()
};
let plan = PortScanPlan::build(&cfg, Privilege::Raw);
assert!(
!plan
.steps()
.iter()
.any(|step| matches!(step, PortScanStep::Idle { .. })),
"an idle step would probe the excluded zombie"
);
assert!(
!plan.covers(Protocol::Tcp),
"and nothing stands in for it by probing the target directly"
);
let refusal = plan
.refusals()
.iter()
.find(|refusal| refusal.scanner == ScannerKind::Idle)
.expect("the refused scan is accounted for");
assert!(
refusal.reason.contains("192.0.2.9") && refusal.reason.contains("excluded"),
"the reason names the zombie and the exclusion: {}",
refusal.reason
);
}
fn v6_set(cidr: &str) -> IpSet {
crate::model::parse::ip::to_set(&[cidr], None, None).expect("a range")
}
#[test]
fn a_local_prefix_too_large_to_walk_is_withheld_from_the_targets() {
let mut targets = v6_set("2001:db8:1:1::/64");
assert_eq!(targets.len(), 1u128 << 64, "a /64, kept whole to here");
let withheld = withhold_unwalkable(&mut targets);
assert_eq!(withheld.len(), 1, "the prefix is taken out");
assert!(targets.is_empty(), "and nothing is left to walk");
}
#[test]
fn withholding_a_prefix_keeps_the_addresses_named_beside_it() {
let mut targets = crate::model::parse::ip::to_set(
&["2001:db8:1:1::/64", "2001:db8:2::1", "192.0.2.7"],
None,
None,
)
.expect("a mixed set");
let withheld = withhold_unwalkable(&mut targets);
assert_eq!(withheld.len(), 1);
assert_eq!(targets.len(), 2, "the literal and the IPv4 address survive");
}
#[test]
fn a_walkable_prefix_is_untouched() {
let mut targets = v6_set("2001:db8::/120");
let before = targets.len();
assert!(withhold_unwalkable(&mut targets).is_empty());
assert_eq!(targets.len(), before);
}
#[test]
fn seeding_skips_other_interfaces_our_own_addresses_and_loopback() {
let own = v6("2001:db8::50");
let intf = interface_with(7, "en0", vec![own]);
let table = vec![
entry("2001:db8::aa", 7),
entry("fe80::bb", 7),
entry("2001:db8::cc", 9),
entry("2001:db8::50", 7),
entry("::1", 7),
];
let seeded = candidates_for(&intf, &table);
assert_eq!(seeded, vec![v6("2001:db8::aa"), v6("fe80::bb")]);
}
#[test]
fn a_seeded_link_local_keeps_its_interface_and_a_global_does_not() {
let intf = interface_with(7, "en0", Vec::new());
let table = vec![entry("fe80::bb", 7), entry("2001:db8::aa", 7)];
let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);
seed_from_neighbor_table_with(&mut local, &table, &Exclusions::none());
let targets = local.into_values().next().unwrap();
let zones: Vec<Option<u32>> = targets.v6().iter().map(|range| range.zone()).collect();
assert!(
zones.contains(&Some(7)),
"the link-local needs its interface"
);
assert!(
zones.contains(&None),
"the global address needs no interface"
);
}
#[test]
fn an_unprivileged_plan_covers_both_protocols() {
let plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
assert!(plan.covers(Protocol::Tcp));
assert!(plan.covers(Protocol::Udp));
assert!(plan.refusals().is_empty());
}
#[test]
fn a_technique_the_fallback_cannot_express_is_refused_at_planning_time() {
let cfg = ZondConfig {
tcp_technique: TcpScanTechnique::Fin,
..ZondConfig::default()
};
let plan = PortScanPlan::build(&cfg, Privilege::Connect);
assert!(
!plan.covers(Protocol::Tcp),
"a connect scan cannot send a FIN and must not plan to"
);
assert!(plan.covers(Protocol::Udp), "the UDP half is unaffected");
assert_eq!(plan.refusals().len(), 1, "the caller has to be told");
assert_eq!(plan.refusals()[0].scanner, ScannerKind::TcpPort);
assert!(
plan.refusals()[0].reason.contains("fin"),
"the refusal has to name the technique: {}",
plan.refusals()[0].reason
);
assert!(
plan.refuses(Protocol::Tcp) && !plan.refuses(Protocol::Udp),
"and which protocol it leaves unprobed, for the router to count"
);
}
#[test]
fn a_step_reports_under_the_same_name_as_the_scanner_it_builds() {
use crate::scanner::session::ScanSession;
use crate::scanner::strategy::ports::TcpPortScanner;
use crate::transport::probe::{Emission, ProbeSender, ProbeTransport, SendError};
struct Unsendable;
impl ProbeSender for Unsendable {
fn send(
&self,
_: &[u8],
_: IpAddr,
_: IpAddr,
_: Option<u32>,
_emission: Emission,
) -> Result<(), SendError> {
Ok(())
}
}
let (_session, ctx) = ScanSession::new();
for technique in TcpScanTechnique::ALL {
let (_tx, rx) = tokio::sync::mpsc::channel(1024);
let scanner = TcpPortScanner::with_transport(
interface::SourceResolver::from_links(&[]),
ctx.clone(),
technique,
ProbeTransport::from_parts(Box::new(Unsendable), rx),
1,
);
assert_eq!(
PortScanStep::RawTcp { technique }.kind(),
scanner.kind(),
"a {technique} step and its scanner disagree about what to call themselves"
);
}
}
#[test]
fn every_raw_step_is_recognisable_as_one() {
for technique in TcpScanTechnique::ALL {
assert!(PortScanStep::RawTcp { technique }.is_raw(), "{technique}");
}
assert!(PortScanStep::RawUdp.is_raw());
assert!(!PortScanStep::ConnectTcp.is_raw());
assert!(!PortScanStep::ConnectUdp.is_raw());
}
#[test]
fn a_plan_remembers_the_technique_it_was_built_for() {
let cfg = ZondConfig {
tcp_technique: TcpScanTechnique::Ack,
..ZondConfig::default()
};
assert_eq!(
PortScanPlan::build(&cfg, Privilege::Connect).technique(),
TcpScanTechnique::Ack
);
}
#[test]
fn dropping_a_step_is_visible_in_what_the_plan_covers() {
let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
plan.steps_mut()
.retain(|step| step.protocol() != Protocol::Udp);
assert!(plan.covers(Protocol::Tcp));
assert!(!plan.covers(Protocol::Udp));
}
#[test]
fn a_swept_plan_does_not_take_an_excluded_neighbour_as_a_candidate() {
let intf = interface_with(7, "en0", Vec::new());
let table = vec![entry("2001:db8::aa", 7), entry("2001:dead::bb", 7)];
let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);
let mut forbidden = IpSet::new();
forbidden.insert_range("2001:db8::/64".parse().expect("a valid range"));
seed_from_neighbor_table_with(&mut local, &table, &Exclusions::new(forbidden));
let targets = local.into_values().next().expect("the one interface");
let carried: Vec<std::net::Ipv6Addr> = targets
.v6()
.iter()
.map(|range| range.start_addr())
.collect();
assert!(
!carried.contains(&"2001:db8::aa".parse().expect("literal")),
"an excluded neighbour must not become a target"
);
assert!(
carried.contains(&"2001:dead::bb".parse().expect("literal")),
"and everything else still is"
);
}
}