use std::collections::HashSet;
use std::net::IpAddr;
use crate::model::host::{Host, NetworkRole};
use crate::model::ip::scoped::Zone;
use crate::scanner::session::ScanContext;
#[derive(Debug, Clone)]
struct Interface {
index: u32,
addresses: Vec<IpAddr>,
gateways: Vec<IpAddr>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Located {
ip: IpAddr,
zone: Option<u32>,
}
impl Located {
fn new(ip: IpAddr, interface: u32) -> Self {
let zone = needs_zone(ip).then_some(interface);
Self { ip, zone }
}
fn matches(&self, ip: IpAddr, zone: Option<u32>) -> bool {
self.ip == ip && (self.zone.is_none() || self.zone == zone)
}
}
fn needs_zone(ip: IpAddr) -> bool {
match ip {
IpAddr::V6(v6) => v6.is_unicast_link_local(),
IpAddr::V4(_) => false,
}
}
pub(super) struct Vantage {
own: Vec<Located>,
gateways: Vec<Located>,
}
impl Vantage {
pub(super) fn from_system() -> Self {
Self::from_interfaces(netdev::get_interfaces().into_iter().map(|iface| {
let mut addresses: Vec<IpAddr> = iface
.ipv4
.iter()
.map(|net| IpAddr::V4(net.addr()))
.collect();
addresses.extend(iface.ipv6.iter().map(|net| IpAddr::V6(net.addr())));
let gateways = iface.gateway.map_or_else(Vec::new, |gw| {
let mut ips: Vec<IpAddr> = gw.ipv4.into_iter().map(IpAddr::V4).collect();
ips.extend(gw.ipv6.into_iter().map(IpAddr::V6));
ips
});
Interface {
index: iface.index,
addresses,
gateways,
}
}))
}
fn from_interfaces(interfaces: impl IntoIterator<Item = Interface>) -> Self {
let mut own = Vec::new();
let mut gateways = Vec::new();
for iface in interfaces {
own.extend(
iface
.addresses
.into_iter()
.map(|ip| Located::new(ip, iface.index)),
);
gateways.extend(
iface
.gateways
.into_iter()
.map(|ip| Located::new(ip, iface.index)),
);
}
Self { own, gateways }
}
fn is_empty(&self) -> bool {
self.own.is_empty() && self.gateways.is_empty()
}
fn attribute(&self, host: &mut Host) -> bool {
let zone = host.zone().and_then(Zone::index);
let mut recorded = false;
for ip in host.ips().iter().copied().collect::<Vec<_>>() {
if self.own.iter().any(|own| own.matches(ip, zone)) {
recorded |= host.add_network_role(NetworkRole::Origin);
}
if self.gateways.iter().any(|gw| gw.matches(ip, zone)) {
recorded |= host.add_network_role(NetworkRole::Router);
}
}
recorded
}
}
pub(super) fn attribute(ctx: &ScanContext) {
let vantage = Vantage::from_system();
let forwarders = forwarders(ctx);
if vantage.is_empty() && forwarders.is_empty() {
return;
}
for ip in ctx.host_addresses() {
ctx.write_host(ip, |host| {
let mut recorded = vantage.attribute(host);
if host.ips().iter().any(|ip| forwarders.contains(ip)) {
recorded |= host.add_network_role(NetworkRole::Router);
}
recorded
});
}
}
fn forwarders(ctx: &ScanContext) -> HashSet<IpAddr> {
let mut forwarders = HashSet::new();
for address in ctx.host_addresses() {
ctx.read_host(&address, |host| {
for hop in host.path().hops() {
if let Some(hop) = hop.address().filter(|hop| !host.ips().contains(hop)) {
forwarders.insert(hop);
}
}
});
}
forwarders
}
#[cfg(test)]
mod tests {
use super::*;
const LAN: u32 = 3;
const OTHER_LINK: u32 = 7;
fn ip(text: &str) -> IpAddr {
text.parse().expect("a literal address")
}
fn lan() -> Interface {
Interface {
index: LAN,
addresses: vec![ip("192.168.1.50"), ip("fe80::50")],
gateways: vec![ip("192.168.1.1"), ip("fe80::1")],
}
}
fn host_at(address: &str) -> Host {
Host::new(ip(address))
}
#[test]
fn this_machine_and_its_gateway_are_named_from_the_routing_table() {
let vantage = Vantage::from_interfaces([lan()]);
let mut ourselves = host_at("192.168.1.50");
assert!(vantage.attribute(&mut ourselves));
assert!(ourselves.network_roles().contains(&NetworkRole::Origin));
assert!(!ourselves.network_roles().contains(&NetworkRole::Router));
let mut gateway = host_at("192.168.1.1");
assert!(vantage.attribute(&mut gateway));
assert!(gateway.network_roles().contains(&NetworkRole::Router));
let mut neighbour = host_at("192.168.1.20");
assert!(!vantage.attribute(&mut neighbour));
assert!(neighbour.network_roles().is_empty());
}
#[test]
fn a_gateway_is_recognised_by_any_of_the_addresses_it_answers_at() {
let vantage = Vantage::from_interfaces([lan()]);
let mut dual_stack = host_at("2001:db8::1");
dual_stack.add_ip(ip("192.168.1.1"));
assert!(vantage.attribute(&mut dual_stack));
assert!(dual_stack.network_roles().contains(&NetworkRole::Router));
}
#[test]
fn a_link_local_gateway_is_only_the_router_of_the_link_it_was_read_on() {
let vantage = Vantage::from_interfaces([lan()]);
let mut here = host_at("fe80::1");
here.set_zone(Zone::new(LAN, "en0"));
assert!(vantage.attribute(&mut here));
assert!(here.network_roles().contains(&NetworkRole::Router));
let mut elsewhere = host_at("fe80::1");
elsewhere.set_zone(Zone::new(OTHER_LINK, "en1"));
assert!(!vantage.attribute(&mut elsewhere));
assert!(elsewhere.network_roles().is_empty());
let mut unscoped = host_at("fe80::1");
assert!(!vantage.attribute(&mut unscoped));
assert!(unscoped.network_roles().is_empty());
}
#[test]
fn a_scan_run_from_the_router_reports_the_address_as_both() {
let vantage = Vantage::from_interfaces([Interface {
index: LAN,
addresses: vec![ip("192.168.1.1")],
gateways: vec![ip("192.168.1.1")],
}]);
let mut host = host_at("192.168.1.1");
assert!(vantage.attribute(&mut host));
assert!(host.network_roles().contains(&NetworkRole::Origin));
assert!(host.network_roles().contains(&NetworkRole::Router));
}
#[tokio::test]
async fn a_hop_in_somebody_elses_path_is_a_router_and_a_trace_target_is_not() {
use crate::model::host::Hop;
use crate::scanner::session::ScanSession;
let router = ip("198.51.100.1");
let target = ip("192.0.2.10");
let (session, ctx) = ScanSession::new();
ctx.write_host(target, |host| {
host.record_hop(Hop::answered(1, router, None));
host.record_hop(Hop::answered(2, target, None));
true
});
ctx.write_host(router, |_| true);
attribute(&ctx);
let hosts = session.hosts();
assert!(
hosts
.get(&router)
.expect("the router was scanned")
.network_roles()
.contains(&NetworkRole::Router),
"a probe aimed past it expired there, which is forwarding"
);
assert!(
!hosts
.get(&target)
.expect("the target was scanned")
.network_roles()
.contains(&NetworkRole::Router),
"the end of a path is where the packet was going, not a hop through"
);
}
}