mod discovery;
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use pnet::datalink::{MacAddr, NetworkInterface};
use pnet::packet::ethernet::EthernetPacket;
use tokio::sync::mpsc::UnboundedSender;
use tokio::time::Interval;
use crate::core::models::deadline::{AdaptiveDeadline, AdaptiveDeadlineConfig};
use crate::core::models::ip::set::IpSet;
use crate::core::models::timer::ScanBudget;
use crate::core::session::ScanContext;
use crate::network::channel::{self, EthernetHandle};
use crate::network::mac::IntoCoreMac;
use crate::protocols::{self as protocol, ethernet};
use crate::scanner::NetworkExplorer;
use crate::system::interface::NetworkInterfaceExtension;
use crate::{error, info};
use discovery::{ArpProtocol, DiscoveryProtocol, Icmpv6Protocol, PendingProbes, ProtocolMatch};
#[derive(Debug, thiserror::Error)]
pub enum LocalScannerError {
#[error("interface has no mac address")]
NoMacAddress,
#[error("unmapped RTT source: {0}")]
UnmappedRttSource(IpAddr),
#[error("packet originated from this host")]
SelfSourcedPacket,
#[error("{0} is not in the scanned range")]
AddressOutOfRange(IpAddr),
}
const DEADLINE_CONFIG: AdaptiveDeadlineConfig = AdaptiveDeadlineConfig::new(
ScanBudget::new(
Duration::from_millis(2_000),
Duration::from_millis(20),
Duration::from_millis(15_000),
),
ScanBudget::new(
Duration::from_millis(800),
Duration::from_millis(7),
Duration::from_millis(5_000),
),
Duration::from_millis(250),
Duration::from_millis(2_000),
4.0,
20,
);
const SEND_INTERVAL: Duration = Duration::from_micros(1000);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
Sweep,
Targeted,
}
struct SourceIdentity {
mac: MacAddr,
ipv4: Option<Ipv4Addr>,
link_local_ipv6: Option<Ipv6Addr>,
}
impl SourceIdentity {
fn resolve(intf: &NetworkInterface, ip_set: &IpSet) -> Result<Self, LocalScannerError> {
let mac = intf.mac.ok_or(LocalScannerError::NoMacAddress)?;
let mut ipv4 = None;
for net in intf.get_ipv4_nets() {
if ipv4.is_none() && !net.ip().is_loopback() {
ipv4 = Some(net.ip());
}
if ip_set
.v4()
.iter()
.any(|range| net.contains(range.start_addr))
{
ipv4 = Some(net.ip());
break;
}
}
let link_local_ipv6 = intf
.get_ipv6_nets()
.into_iter()
.find(|net| net.ip().is_unicast_link_local())
.map(|net| net.ip());
Ok(Self {
mac,
ipv4,
link_local_ipv6,
})
}
}
pub struct LocalScanner {
ctx: ScanContext,
ip_set: IpSet,
identity: SourceIdentity,
eth_handle: EthernetHandle,
deadline: AdaptiveDeadline,
protocols: Vec<Box<dyn DiscoveryProtocol>>,
pending_probes: PendingProbes,
dns_tx: Option<UnboundedSender<IpAddr>>,
mac_to_ip: HashMap<MacAddr, IpAddr>,
scope: Scope,
responded: HashSet<IpAddr>,
}
#[async_trait]
impl NetworkExplorer for LocalScanner {
async fn discover_hosts(mut self: Box<Self>) -> anyhow::Result<()> {
let mut packet_iter = protocol::eth_packet_iter(
&self.identity.mac,
&self.identity.ipv4,
&self.identity.link_local_ipv6,
&self.ip_set,
matches!(self.scope, Scope::Sweep),
)?;
let mut sending_finished = false;
let mut send_interval: Interval = tokio::time::interval(SEND_INTERVAL);
loop {
if sending_finished && (self.should_stop() || self.all_targets_responded()) {
break;
}
let next_tick = self.deadline.time_until_next_tick();
tokio::select! {
pkt = self.eth_handle.rx.recv() => {
match pkt {
Some(bytes) => _ = self.process_eth_packet(&bytes),
None => break,
}
}
_ = send_interval.tick(), if !sending_finished => {
match packet_iter.next() {
Some((packet, ip)) => {
self.pending_probes.insert(ip, Instant::now());
self.eth_handle.tx.send_to(&packet, None);
},
None => {
sending_finished = true;
},
}
}
_ = tokio::time::sleep(next_tick), if sending_finished => {}
}
}
Ok(())
}
}
impl LocalScanner {
pub fn new(
intf: NetworkInterface,
ip_set: IpSet,
ctx: ScanContext,
dns_tx: Option<UnboundedSender<IpAddr>>,
scope: Scope,
) -> anyhow::Result<Self> {
let eth_handle: EthernetHandle = channel::start_capture(&intf)?;
let identity = SourceIdentity::resolve(&intf, &ip_set)?;
let target_count = ip_set.len() as usize;
let deadline = AdaptiveDeadline::new(DEADLINE_CONFIG, target_count);
Ok(Self {
ctx,
ip_set,
identity,
eth_handle,
deadline,
protocols: vec![Box::new(ArpProtocol), Box::new(Icmpv6Protocol)],
pending_probes: PendingProbes::with_capacity(target_count),
dns_tx,
mac_to_ip: HashMap::new(),
scope,
responded: HashSet::new(),
})
}
fn process_eth_packet(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
let eth_frame: EthernetPacket = ethernet::get_packet_from_u8(bytes)?;
let source_mac = eth_frame.get_source();
if source_mac == self.identity.mac {
return Err(LocalScannerError::SelfSourcedPacket.into());
}
let source_addr: IpAddr = protocol::get_ip_addr_from_eth(ð_frame)?;
let out_of_range = match self.scope {
Scope::Targeted => !self.ip_set.contains(&source_addr),
Scope::Sweep => source_addr.is_ipv4() && !self.ip_set.contains(&source_addr),
};
if out_of_range {
return Err(LocalScannerError::AddressOutOfRange(source_addr).into());
}
if let ProtocolMatch::Handled { rtt } = self.interpret_response(ð_frame, source_addr) {
if self.ip_set.contains(&source_addr) {
self.responded.insert(source_addr);
}
self.record_response(source_mac, source_addr, rtt);
}
Ok(())
}
fn all_targets_responded(&self) -> bool {
self.responded.len() as u128 >= self.ip_set.len()
}
fn interpret_response(&mut self, frame: &EthernetPacket, source: IpAddr) -> ProtocolMatch {
for protocol in &self.protocols {
match protocol.interpret(frame, source, &mut self.pending_probes) {
Ok(ProtocolMatch::Handled { rtt }) => return ProtocolMatch::Handled { rtt },
Ok(ProtocolMatch::Unhandled) => continue,
Err(e) => {
error!(verbosity = 1, "Failed to interpret discovery response: {e}");
return ProtocolMatch::Unhandled;
}
}
}
ProtocolMatch::Unhandled
}
fn record_response(&mut self, source_mac: MacAddr, source_addr: IpAddr, rtt: Option<Duration>) {
let primary_ip = *self.mac_to_ip.entry(source_mac).or_insert(source_addr);
let mut is_new_ip = false;
let is_new_host = self.ctx.write_host(primary_ip, |host| {
if host.mac().is_none() {
host.set_mac(source_mac.into_core());
}
let mut changed = rtt.is_some();
if let Some(rtt) = rtt {
host.add_rtt(rtt);
}
is_new_ip = host.add_ip(source_addr);
changed |= is_new_ip;
if source_addr.is_ipv4() && host.primary_ip().is_ipv6() {
host.set_primary_ip(source_addr);
changed = true;
}
changed
});
if is_new_host {
self.deadline.mark_activity();
}
if let Some(rtt) = rtt {
info!(
incoming,
verbosity = 2,
"{source_addr} responded in {}ms",
rtt.as_millis()
);
self.deadline.record_rtt(rtt);
}
if (is_new_host || is_new_ip)
&& let Some(tx) = &self.dns_tx
{
let _ = tx.send(source_addr);
}
}
fn should_stop(&self) -> bool {
self.ctx.handle.should_stop() || self.deadline.has_expired()
}
}