use std::collections::HashMap;
use std::net::IpAddr;
use pnet::datalink::NetworkInterface;
use tokio::sync::mpsc::UnboundedSender;
use crate::config::{ProbeTuning, ZondConfig};
use crate::model::ip::range::{IpRange, Ipv6Range};
use crate::model::ip::set::IpSet;
use crate::model::port::Protocol;
use crate::model::technique::TcpScanTechnique;
use crate::scanner::pacing::limits;
use crate::scanner::session::{ScanContext, ScannerKind};
use crate::scanner::strategy::connect::{
ConnectPortScanner, ConnectScanner, ConnectUdpPortScanner,
};
use crate::scanner::strategy::local::{LocalScanner, Scope};
use crate::scanner::strategy::routed::{RoutedScanner, TcpPortScanner, UdpPortScanner};
use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
use crate::system::interface::{self, RoutedTarget};
use crate::system::neighbors;
use crate::{info, warn};
#[derive(Debug, Clone)]
pub struct Refusal {
pub scanner: ScannerKind,
pub reason: String,
}
impl Refusal {
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 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)
),
}
}
}
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<NetworkInterface>,
targets: IpSet,
scope: Scope,
},
Routed {
targets: Vec<RoutedTarget>,
},
Connect {
targets: IpSet,
},
}
impl DiscoveryStep {
pub fn kind(&self) -> ScannerKind {
match self {
Self::Local { .. } => ScannerKind::Local,
Self::Routed { .. } => ScannerKind::Routed,
Self::Connect { .. } => ScannerKind::Connect,
}
}
pub fn target_count(&self) -> u128 {
match self {
Self::Local { targets, .. } | Self::Connect { targets } => targets.len(),
Self::Routed { 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::Connect { targets } => Ok(Box::new(ConnectScanner::new(targets, ctx))),
}
}
}
#[derive(Debug, Clone)]
pub struct DiscoveryPlan {
steps: Vec<DiscoveryStep>,
refusals: Vec<Refusal>,
}
impl DiscoveryPlan {
pub fn build(targets: IpSet, scope: Scope) -> Self {
let mut steps = Vec::new();
let mut refusals = Vec::new();
let interface::RoutedTargets {
mut local,
routed,
unmapped,
ambiguous,
unenumerable,
} = interface::map_ips_to_interfaces(targets);
for range in &ambiguous {
refusals.push(Refusal {
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(Refusal::routed_range_not_enumerable(range));
}
if matches!(scope, Scope::Sweep) {
include_swept_link(&mut local);
seed_from_neighbor_table(&mut local);
}
for (interface, targets) in local {
if targets.is_empty() && matches!(scope, Scope::Targeted) {
continue;
}
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 }
}
pub fn steps(&self) -> &[DiscoveryStep] {
&self.steps
}
pub fn steps_mut(&mut self) -> &mut Vec<DiscoveryStep> {
&mut self.steps
}
pub fn refusals(&self) -> &[Refusal] {
&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,
ConnectTcp,
ConnectUdp,
}
impl PortScanStep {
pub fn kind(&self) -> ScannerKind {
match self {
Self::RawTcp { technique } => ScannerKind::for_raw_tcp(*technique),
Self::RawUdp => ScannerKind::UdpPort,
Self::ConnectTcp => ScannerKind::Connect,
Self::ConnectUdp => ScannerKind::ConnectUdp,
}
}
pub fn protocol(&self) -> Protocol {
match self {
Self::RawTcp { .. } | Self::ConnectTcp => Protocol::Tcp,
Self::RawUdp | Self::ConnectUdp => Protocol::Udp,
}
}
pub fn is_raw(&self) -> bool {
matches!(self, Self::RawTcp { .. } | Self::RawUdp)
}
pub fn into_scanner(
self,
ctx: ScanContext,
target_count: usize,
tuning: ProbeTuning,
) -> Result<Box<dyn PortScanner>, StrategyError> {
match self {
Self::RawTcp { technique } => Ok(Box::new(TcpPortScanner::new(
interface::SourceResolver::from_system(),
ctx,
technique,
target_count,
tuning,
)?)),
Self::RawUdp => Ok(Box::new(UdpPortScanner::new(
interface::SourceResolver::from_system(),
ctx,
target_count,
tuning,
)?)),
Self::ConnectTcp => Ok(Box::new(ConnectPortScanner::new(
ctx,
limits::CONNECT_CONCURRENCY,
))),
Self::ConnectUdp => Ok(Box::new(ConnectUdpPortScanner::new(
ctx,
limits::CONNECT_CONCURRENCY,
))),
}
}
}
#[derive(Debug, Clone)]
pub struct PortScanPlan {
steps: Vec<PortScanStep>,
refusals: Vec<Refusal>,
technique: TcpScanTechnique,
}
impl PortScanPlan {
pub fn build(cfg: &ZondConfig, privileged: bool) -> Self {
let mut steps = Vec::new();
let mut refusals = Vec::new();
let raw = privileged && interface::SourceResolver::from_system().has_sources();
if privileged && !raw {
warn!("No usable network interface found; using TCP connect fallback");
}
if raw {
steps.push(PortScanStep::RawTcp {
technique: cfg.tcp_technique,
});
steps.push(PortScanStep::RawUdp);
} else if cfg.tcp_technique.finds_open_ports() {
steps.push(PortScanStep::ConnectTcp);
steps.push(PortScanStep::ConnectUdp);
} else {
refusals.push(Refusal::technique_needs_raw_sockets(cfg.tcp_technique));
steps.push(PortScanStep::ConnectUdp);
}
Self {
steps,
refusals,
technique: cfg.tcp_technique,
}
}
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) -> &[Refusal] {
&self.refusals
}
pub fn into_steps(self) -> Vec<PortScanStep> {
self.steps
}
pub fn covers(&self, protocol: Protocol) -> bool {
self.steps.iter().any(|step| step.protocol() == protocol)
}
}
fn include_swept_link(local: &mut HashMap<NetworkInterface, IpSet>) {
let Ok(Some(link)) = interface::get_lan_link() else {
return;
};
if local.keys().any(|intf| intf.name == link.interface.name) {
return;
}
info!(
verbosity = 1,
"Sweeping {} for IPv6 neighbours; it has no IPv4 range to walk", link.interface.name
);
local.insert(link.interface, IpSet::new());
}
fn seed_from_neighbor_table(local: &mut HashMap<NetworkInterface, IpSet>) {
let table = neighbors::ipv6_neighbors();
if !table.is_empty() {
seed_from_neighbor_table_with(local, &table);
}
}
fn seed_from_neighbor_table_with(
local: &mut HashMap<NetworkInterface, IpSet>,
table: &[neighbors::Neighbor],
) {
for (intf, targets) in local.iter_mut() {
let mut seeded = 0usize;
for addr in candidates_for(intf, table) {
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 {seeded} IPv6 address(es) from the neighbour table as candidates on {}",
intf.name
);
}
}
}
fn candidates_for(intf: &NetworkInterface, table: &[neighbors::Neighbor]) -> Vec<IpAddr> {
let own: std::collections::HashSet<IpAddr> = intf.ips.iter().map(|net| net.ip()).collect();
table
.iter()
.filter(|entry| entry.interface_index == intf.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>,
) -> pnet::datalink::NetworkInterface {
use pnet::ipnetwork::{IpNetwork, Ipv6Network};
pnet::datalink::NetworkInterface {
name: name.to_string(),
description: String::new(),
index,
mac: None,
ips: own
.into_iter()
.map(|ip| match ip {
IpAddr::V6(v6) => IpNetwork::V6(Ipv6Network::new(v6, 64).unwrap()),
IpAddr::V4(_) => unreachable!("test uses v6 only"),
})
.collect(),
flags: 0,
}
}
fn entry(ip: &str, index: u32) -> neighbors::Neighbor {
neighbors::Neighbor {
ip: v6(ip),
mac: None,
interface_index: index,
}
}
#[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);
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(), false);
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, false);
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
);
}
#[test]
fn a_step_reports_under_the_same_name_as_the_scanner_it_builds() {
use crate::scanner::session::ScanSession;
use crate::scanner::strategy::routed::TcpPortScanner;
use crate::transport::probe::{ProbeSender, ProbeTransport, SendError};
struct Unsendable;
impl ProbeSender for Unsendable {
fn send(&self, _: &[u8], _: IpAddr, _: IpAddr) -> Result<(), SendError> {
Ok(())
}
}
let (_session, ctx) = ScanSession::new();
for technique in TcpScanTechnique::ALL {
let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
let scanner = TcpPortScanner::with_transport(
interface::SourceResolver::from_interfaces(&[]),
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, false).technique(),
TcpScanTechnique::Ack
);
}
#[test]
fn dropping_a_step_is_visible_in_what_the_plan_covers() {
let mut plan = PortScanPlan::build(&ZondConfig::default(), false);
plan.steps_mut()
.retain(|step| step.protocol() != Protocol::Udp);
assert!(plan.covers(Protocol::Tcp));
assert!(!plan.covers(Protocol::Udp));
}
}