use std::net::IpAddr;
use anyhow::Context;
use pnet::datalink;
use pnet::packet::Packet;
use crate::core::config::SendMode;
use crate::network::capture::{self, CaptureGuard, CaptureStream};
use crate::network::ethernet::EthernetSender;
use crate::network::transport::{self, TransportSenderHandle, TransportType};
#[derive(Debug, Clone, Copy)]
pub enum ProbeKind {
TcpSyn,
UdpResolve,
UdpProbe,
}
impl ProbeKind {
fn transport_type(self) -> TransportType {
match self {
ProbeKind::TcpSyn => TransportType::TcpLayer4,
ProbeKind::UdpResolve | ProbeKind::UdpProbe => TransportType::UdpLayer4,
}
}
fn filter(self) -> &'static str {
match self {
ProbeKind::TcpSyn => "tcp and (tcp[tcpflags] & (tcp-syn|tcp-rst)) != 0",
ProbeKind::UdpResolve => "udp and (src port 53 or src port 5353)",
ProbeKind::UdpProbe => "icmp or icmp6 or udp",
}
}
}
pub trait ProbeSender: Send + Sync {
fn send(&self, segment: &[u8], src: IpAddr, dst: IpAddr) -> anyhow::Result<()>;
}
struct RawSegment<'a>(&'a [u8]);
impl Packet for RawSegment<'_> {
fn packet(&self) -> &[u8] {
self.0
}
fn payload(&self) -> &[u8] {
&[]
}
}
pub struct RawIpSender {
handle: TransportSenderHandle,
}
impl RawIpSender {
fn open(kind: ProbeKind) -> anyhow::Result<Self> {
Ok(Self {
handle: transport::open_sender(kind.transport_type())?,
})
}
}
impl ProbeSender for RawIpSender {
fn send(&self, segment: &[u8], _src: IpAddr, dst: IpAddr) -> anyhow::Result<()> {
self.handle.send_to(RawSegment(segment), dst).map(|_| ())
}
}
struct NoopSender;
impl ProbeSender for NoopSender {
fn send(&self, _segment: &[u8], _src: IpAddr, _dst: IpAddr) -> anyhow::Result<()> {
anyhow::bail!("this transport is receive-only and cannot send")
}
}
pub struct ProbeTransport {
pub tx: Box<dyn ProbeSender>,
pub rx: CaptureStream,
_capture: CaptureGuard,
}
impl ProbeTransport {
pub fn open(kind: ProbeKind) -> anyhow::Result<Self> {
Self::open_with(kind, SendMode::Auto)
}
pub fn open_with(kind: ProbeKind, mode: SendMode) -> anyhow::Result<Self> {
match mode {
SendMode::Ethernet => Self::open_ethernet(kind),
SendMode::RawSocket => Self::open_on(kind, &capturable_interfaces()),
SendMode::Auto => {
#[cfg(windows)]
{
Self::open_ethernet(kind)
}
#[cfg(not(windows))]
{
Self::open_on(kind, &capturable_interfaces())
}
}
}
}
pub fn open_on(kind: ProbeKind, interfaces: &[String]) -> anyhow::Result<Self> {
let (rx, capture) = capture::start(interfaces, kind.filter())?;
let tx: Box<dyn ProbeSender> = Box::new(RawIpSender::open(kind)?);
Ok(Self {
tx,
rx,
_capture: capture,
})
}
pub fn open_ethernet(kind: ProbeKind) -> anyhow::Result<Self> {
let sender = EthernetSender::from_system()
.context("no Ethernet-capable interface for Layer-2 send")?;
let (rx, capture) = capture::start(&capturable_interfaces(), kind.filter())?;
Ok(Self {
tx: Box::new(sender),
rx,
_capture: capture,
})
}
pub fn open_receiver(kind: ProbeKind) -> anyhow::Result<Self> {
let (rx, capture) = capture::start(&capturable_interfaces(), kind.filter())?;
Ok(Self {
tx: Box::new(NoopSender),
rx,
_capture: capture,
})
}
#[cfg(test)]
pub fn from_parts(tx: Box<dyn ProbeSender>, rx: CaptureStream, capture: CaptureGuard) -> Self {
Self {
tx,
rx,
_capture: capture,
}
}
}
fn capturable_interfaces() -> Vec<String> {
datalink::interfaces()
.into_iter()
.filter(|iface| iface.is_up())
.map(|iface| iface.name)
.collect()
}
#[cfg(test)]
pub type SentProbe = (Vec<u8>, IpAddr, IpAddr);
#[cfg(test)]
#[derive(Clone, Default)]
pub struct MockSender {
pub sent: std::sync::Arc<std::sync::Mutex<Vec<SentProbe>>>,
}
#[cfg(test)]
impl ProbeSender for MockSender {
fn send(&self, segment: &[u8], src: IpAddr, dst: IpAddr) -> anyhow::Result<()> {
self.sent.lock().unwrap().push((segment.to_vec(), src, dst));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn transport_forwards_sends_and_delivers_replies() {
use crate::network::capture::CaptureGuard;
use std::net::Ipv4Addr;
let mock = MockSender::default();
let recorded = mock.sent.clone();
let (reply_tx, reply_rx) = tokio::sync::mpsc::unbounded_channel();
let mut transport =
ProbeTransport::from_parts(Box::new(mock), reply_rx, CaptureGuard::noop());
let src = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2));
let dst = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
transport.tx.send(&[0xAA, 0xBB], src, dst).unwrap();
let sent = recorded.lock().unwrap().clone();
assert_eq!(sent, vec![(vec![0xAA, 0xBB], src, dst)]);
reply_tx.send((vec![1, 2, 3], dst)).unwrap();
assert_eq!(transport.rx.recv().await, Some((vec![1, 2, 3], dst)));
}
}