use async_trait::async_trait;
use tokio::sync::mpsc;
use crate::core::models::port::Protocol;
use crate::core::models::target::Target;
use crate::core::session::{ScanContext, ScannerKind};
use crate::scanner::PortScanner;
use crate::warn;
pub struct CompositePortScanner {
scanners: Vec<Box<dyn PortScanner>>,
}
impl CompositePortScanner {
pub fn new(scanners: Vec<Box<dyn PortScanner>>) -> Self {
Self { scanners }
}
}
#[async_trait]
impl PortScanner for CompositePortScanner {
fn kind(&self) -> ScannerKind {
ScannerKind::Composite
}
fn supported_protocols(&self) -> Vec<Protocol> {
let mut protocols = Vec::new();
for scanner in &self.scanners {
for proto in scanner.supported_protocols() {
if !protocols.contains(&proto) {
protocols.push(proto);
}
}
}
protocols
}
async fn scan(&mut self, mut targets: mpsc::Receiver<Target>) -> anyhow::Result<()> {
struct Route {
supported_protocols: Vec<Protocol>,
tx: mpsc::Sender<Target>,
}
let mut routes = Vec::new();
let mut handles = Vec::new();
for mut scanner in self.scanners.drain(..) {
let (tx, rx) = mpsc::channel(1024);
let supported_protocols = scanner.supported_protocols();
let kind = scanner.kind();
let handle = tokio::spawn(async move {
let res = scanner.scan(rx).await;
(scanner, res)
});
handles.push((kind, handle));
routes.push(Route {
supported_protocols,
tx,
});
}
let mut unroutable = 0usize;
let mut undeliverable = 0usize;
while let Some(target) = targets.recv().await {
match routes
.iter()
.find(|route| route.supported_protocols.contains(&target.protocol))
{
Some(route) => {
if route.tx.send(target).await.is_err() {
undeliverable += 1;
}
}
None => unroutable += 1,
}
}
if unroutable > 0 {
warn!("{unroutable} targets had no scanner for their protocol and went unprobed");
}
if undeliverable > 0 {
warn!("{undeliverable} targets arrived after their scanner had already finished");
}
drop(routes);
let mut failure: Option<anyhow::Error> = None;
for (kind, handle) in handles {
match handle.await {
Ok((scanner, res)) => {
self.scanners.push(scanner);
if let Err(e) = res {
failure.get_or_insert(e);
}
}
Err(e) => {
failure
.get_or_insert_with(|| anyhow::anyhow!("{kind:?} scanner panicked: {e}"));
}
}
}
match failure {
Some(e) => Err(e),
None => Ok(()),
}
}
async fn detect_services(&mut self, ctx: &ScanContext) {
for scanner in &mut self.scanners {
scanner.detect_services(ctx).await;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::{Arc, Mutex};
enum Behaviour {
Collect,
Fail(&'static str),
Panic,
}
struct MockPortScanner {
supported: Vec<Protocol>,
received: Arc<Mutex<Vec<Target>>>,
behaviour: Behaviour,
}
impl MockPortScanner {
fn new(supported: Vec<Protocol>) -> (Self, Arc<Mutex<Vec<Target>>>) {
Self::with_behaviour(supported, Behaviour::Collect)
}
fn with_behaviour(
supported: Vec<Protocol>,
behaviour: Behaviour,
) -> (Self, Arc<Mutex<Vec<Target>>>) {
let received = Arc::new(Mutex::new(Vec::new()));
(
Self {
supported,
received: received.clone(),
behaviour,
},
received,
)
}
}
#[async_trait]
impl PortScanner for MockPortScanner {
fn kind(&self) -> ScannerKind {
ScannerKind::Composite
}
fn supported_protocols(&self) -> Vec<Protocol> {
self.supported.clone()
}
async fn scan(&mut self, mut targets: mpsc::Receiver<Target>) -> anyhow::Result<()> {
match self.behaviour {
Behaviour::Fail(reason) => return Err(anyhow::anyhow!(reason)),
Behaviour::Panic => panic!("scanner bug"),
Behaviour::Collect => {}
}
while let Some(t) = targets.recv().await {
self.received.lock().unwrap().push(t);
}
Ok(())
}
}
fn target(protocol: Protocol, port: u16) -> Target {
Target {
ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
port,
protocol,
}
}
async fn run(scanners: Vec<Box<dyn PortScanner>>, targets: Vec<Target>) -> anyhow::Result<()> {
let mut composite = CompositePortScanner::new(scanners);
let (tx, rx) = mpsc::channel(16);
for t in targets {
tx.send(t).await.unwrap();
}
drop(tx);
composite.scan(rx).await
}
#[tokio::test]
async fn composite_routes_by_protocol() {
let (tcp_scanner, tcp_rx) = MockPortScanner::new(vec![Protocol::Tcp]);
let (udp_scanner, udp_rx) = MockPortScanner::new(vec![Protocol::Udp]);
let mut composite =
CompositePortScanner::new(vec![Box::new(tcp_scanner), Box::new(udp_scanner)]);
let (tx, rx) = mpsc::channel(10);
let target_tcp = Target {
ip: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
port: 80,
protocol: Protocol::Tcp,
};
let target_udp = Target {
ip: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
port: 53,
protocol: Protocol::Udp,
};
tx.send(target_tcp).await.unwrap();
tx.send(target_udp).await.unwrap();
drop(tx);
composite.scan(rx).await.unwrap();
let tcp_received = tcp_rx.lock().unwrap();
assert_eq!(tcp_received.len(), 1);
assert_eq!(tcp_received[0].protocol, Protocol::Tcp);
let udp_received = udp_rx.lock().unwrap();
assert_eq!(udp_received.len(), 1);
assert_eq!(udp_received[0].protocol, Protocol::Udp);
}
#[tokio::test]
async fn a_failing_scanner_is_reported_without_losing_the_others() {
let (failing, _) =
MockPortScanner::with_behaviour(vec![Protocol::Tcp], Behaviour::Fail("transport died"));
let (working, udp_rx) = MockPortScanner::new(vec![Protocol::Udp]);
let mut composite = CompositePortScanner::new(vec![Box::new(failing), Box::new(working)]);
let (tx, rx) = mpsc::channel(16);
tx.send(target(Protocol::Udp, 53)).await.unwrap();
drop(tx);
let err = composite.scan(rx).await.expect_err("the failure surfaces");
assert!(err.to_string().contains("transport died"));
assert_eq!(udp_rx.lock().unwrap().len(), 1, "sibling still ran");
assert_eq!(composite.scanners.len(), 2, "both scanners restored");
}
#[tokio::test]
async fn a_panicking_scanner_surfaces_as_a_failure() {
let (panicking, _) = MockPortScanner::with_behaviour(vec![Protocol::Tcp], Behaviour::Panic);
let (working, udp_rx) = MockPortScanner::new(vec![Protocol::Udp]);
let err = run(
vec![Box::new(panicking), Box::new(working)],
vec![target(Protocol::Udp, 53)],
)
.await
.expect_err("a panic is a failure");
assert!(err.to_string().contains("panicked"), "got: {err}");
assert_eq!(udp_rx.lock().unwrap().len(), 1, "sibling still ran");
}
#[tokio::test]
async fn targets_with_no_route_do_not_stop_the_run() {
let (tcp_scanner, tcp_rx) = MockPortScanner::new(vec![Protocol::Tcp]);
run(
vec![Box::new(tcp_scanner)],
vec![
target(Protocol::Tcp, 80),
target(Protocol::Udp, 53),
target(Protocol::Sctp, 9),
],
)
.await
.expect("unroutable targets are not a failure");
let received = tcp_rx.lock().unwrap();
assert_eq!(received.len(), 1);
assert_eq!(received[0].protocol, Protocol::Tcp);
}
}