use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use pnet_base::MacAddr;
use pnet_packet::Packet;
use pnet_packet::arp::{ArpOperations, ArpPacket};
use pnet_packet::ethernet::{EtherTypes, EthernetPacket};
use crate::protocols::arp;
use crate::transport::capture::{self, FrameSink};
use crate::transport::frame;
use crate::transport::neighbor::{LinkRoute, NeighborResolver};
use crate::transport::probe::{Emission, IpProtocols, ProbeSender, SendError};
const ARP_TIMEOUT: Duration = Duration::from_millis(500);
const CHANNEL_READ_TIMEOUT: Duration = Duration::from_millis(50);
struct InterfaceChannel {
channel: capture::FrameChannel,
}
pub struct EthernetSender {
resolver: Mutex<NeighborResolver>,
channels: Mutex<HashMap<String, InterfaceChannel>>,
protocols: IpProtocols,
}
impl EthernetSender {
pub fn from_system(protocols: IpProtocols) -> Option<Self> {
let resolver = NeighborResolver::from_system();
if !resolver.has_ethernet() {
return None;
}
Some(Self {
resolver: Mutex::new(resolver),
channels: Mutex::new(HashMap::new()),
protocols,
})
}
fn next_hop_mac(&self, route: &LinkRoute) -> Result<MacAddr, SendError> {
if let Some(mac) = route.next_hop_mac {
return Ok(mac);
}
let target_v4 = match route.next_hop {
IpAddr::V4(v4) => v4,
IpAddr::V6(_) => {
return Err(SendError::Unsupported(
"on-link IPv6 next-hop resolution (NDP) is not yet implemented",
));
}
};
let src_v4 = match route.src_ip {
IpAddr::V4(v4) => v4,
IpAddr::V6(_) => {
return Err(SendError::Unsupported(
"an IPv4 target cannot be reached from an IPv6 source",
));
}
};
let mac = self.arp_resolve(&route.interface, route.src_mac, src_v4, target_v4)?;
self.resolver
.lock()
.map_err(|_| poisoned("route resolver"))?
.remember(&route.interface, route.next_hop, mac);
Ok(mac)
}
fn arp_resolve(
&self,
interface: &str,
src_mac: MacAddr,
src_ip: Ipv4Addr,
target: Ipv4Addr,
) -> Result<MacAddr, SendError> {
let mut channels = self
.channels
.lock()
.map_err(|_| poisoned("datalink channel"))?;
let channel = self.channel_for(&mut channels, interface)?;
let request = arp::build_request(src_mac, src_ip, target);
channel
.channel
.send_frame(&request)
.map_err(|reason| SendError::Refused(format!("sending an ARP request: {reason}")))?;
let deadline = Instant::now() + ARP_TIMEOUT;
while Instant::now() < deadline {
let Some(frame) = channel.channel.next_frame() else {
continue; };
if let Some(mac) = parse_arp_reply(frame, target) {
return Ok(mac);
}
}
Err(SendError::Unroutable(format!(
"no ARP reply for {target} on {interface} within {ARP_TIMEOUT:?}"
)))
}
fn channel_for<'a>(
&self,
channels: &'a mut HashMap<String, InterfaceChannel>,
interface: &str,
) -> Result<&'a mut InterfaceChannel, SendError> {
if !channels.contains_key(interface) {
let channel = capture::FrameChannel::open(interface, "arp", CHANNEL_READ_TIMEOUT)
.map_err(|error| {
SendError::Refused(format!("no datalink channel on {interface}: {error}"))
})?;
channels.insert(interface.to_string(), InterfaceChannel { channel });
}
Ok(channels.get_mut(interface).unwrap())
}
}
impl ProbeSender for EthernetSender {
fn send(
&self,
segment: &[u8],
src: IpAddr,
dst: IpAddr,
_zone: Option<u32>,
emission: Emission,
) -> Result<(), SendError> {
(|| -> Result<(), SendError> {
let route = self
.resolver
.lock()
.map_err(|_| poisoned("route resolver"))?
.resolve(dst)
.ok_or_else(|| SendError::Unroutable(format!("no Ethernet route to {dst}")))?;
let dst_mac = self.next_hop_mac(&route)?;
let src_mac = spoofed_source_mac(route.src_mac, emission.source_mac);
let protocol = self.protocols.for_destination(dst);
let spec = frame::FrameSpec {
src_mac,
dst_mac,
src,
dst,
protocol,
hop_limit: emission.hop_limit,
};
let frames = match emission.fragment {
Some(mtu) => frame::build_fragmented_ethernet_frames(&spec, segment, mtu),
None => frame::build_ethernet_frame(&spec, segment).map(|frame| vec![frame]),
}
.map_err(|error| {
SendError::Refused(format!("the frame could not be built: {error}"))
})?;
let mut channels = self
.channels
.lock()
.map_err(|_| poisoned("datalink channel"))?;
let channel = self.channel_for(&mut channels, &route.interface)?;
for frame in &frames {
channel.channel.send_frame(frame).map_err(|reason| {
SendError::Refused(format!("the frame could not be sent: {reason}"))
})?;
}
Ok(())
})()
}
}
fn poisoned(what: &str) -> SendError {
SendError::Refused(format!(
"the {what} lock was poisoned by another thread's panic"
))
}
fn spoofed_source_mac(interface: MacAddr, spoofed: Option<crate::model::mac::MacAddr>) -> MacAddr {
match spoofed {
Some(mac) => {
let octets: [u8; 6] = mac.into();
MacAddr::new(
octets[0], octets[1], octets[2], octets[3], octets[4], octets[5],
)
}
None => interface,
}
}
fn parse_arp_reply(frame: &[u8], target: Ipv4Addr) -> Option<MacAddr> {
let eth = EthernetPacket::new(frame)?;
if eth.get_ethertype() != EtherTypes::Arp {
return None;
}
let arp = ArpPacket::new(eth.payload())?;
if arp.get_operation() == ArpOperations::Reply && arp.get_sender_proto_addr() == target {
Some(arp.get_sender_hw_addr())
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use pnet_packet::arp::{ArpHardwareTypes, ArpOperations, MutableArpPacket};
use pnet_packet::ethernet::MutableEthernetPacket;
fn arp_reply(sender_ip: Ipv4Addr, sender_mac: MacAddr) -> Vec<u8> {
let mut buf = vec![0u8; 42];
{
let mut eth = MutableEthernetPacket::new(&mut buf[..14]).unwrap();
eth.set_ethertype(EtherTypes::Arp);
eth.set_source(sender_mac);
eth.set_destination(MacAddr::broadcast());
}
{
let mut a = MutableArpPacket::new(&mut buf[14..]).unwrap();
a.set_hardware_type(ArpHardwareTypes::Ethernet);
a.set_protocol_type(EtherTypes::Ipv4);
a.set_hw_addr_len(6);
a.set_proto_addr_len(4);
a.set_operation(ArpOperations::Reply);
a.set_sender_hw_addr(sender_mac);
a.set_sender_proto_addr(sender_ip);
a.set_target_proto_addr(Ipv4Addr::new(192, 0, 2, 50));
}
buf
}
#[test]
fn parses_matching_arp_reply() {
let ip = Ipv4Addr::new(192, 0, 2, 200);
let mac = MacAddr::new(0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01);
assert_eq!(parse_arp_reply(&arp_reply(ip, mac), ip), Some(mac));
}
#[test]
fn a_spoofed_source_mac_replaces_the_interface_and_converts_faithfully() {
let interface = MacAddr::new(0x00, 0x11, 0x22, 0x33, 0x44, 0x55);
assert_eq!(spoofed_source_mac(interface, None), interface);
let spoofed = crate::model::mac::MacAddr::new(0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01);
assert_eq!(
spoofed_source_mac(interface, Some(spoofed)),
MacAddr::new(0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01)
);
}
#[test]
fn ignores_arp_reply_from_other_ip() {
let mac = MacAddr::new(0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01);
let reply = arp_reply(Ipv4Addr::new(192, 0, 2, 201), mac);
assert_eq!(parse_arp_reply(&reply, Ipv4Addr::new(192, 0, 2, 200)), None);
}
#[test]
fn ignores_non_arp_frame() {
let mut buf = vec![0u8; 42];
let mut eth = MutableEthernetPacket::new(&mut buf).unwrap();
eth.set_ethertype(EtherTypes::Ipv4);
assert_eq!(parse_arp_reply(&buf, Ipv4Addr::new(192, 0, 2, 200)), None);
}
}