use super::dispatcher::Dispatcher;
use super::pool::ProbePool;
use super::{NetworkExplorer, PortScanner, tuning};
use crate::core::models::host::Host;
use crate::core::models::ip::set::IpSet;
use crate::core::models::port::{Port, PortSet, PortState, Protocol};
use crate::core::models::target::{Target, TargetMap, TargetSet};
use crate::core::session::{ScanContext, ScannerKind};
use async_trait::async_trait;
use dashmap::DashSet;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::time::timeout;
const DISCOVERY_PORTS: &[u16] = &[22, 80, 443, 445, 3389];
pub struct ConnectScanner {
ips: IpSet,
ctx: ScanContext,
}
impl ConnectScanner {
pub fn new(ips: IpSet, ctx: ScanContext) -> Self {
Self { ips, ctx }
}
}
#[async_trait]
impl NetworkExplorer for ConnectScanner {
async fn discover_hosts(self: Box<Self>) -> anyhow::Result<()> {
discover(self.ips, self.ctx).await
}
}
type ProbedPort = Option<(IpAddr, Port)>;
pub struct ConnectPortScanner {
ctx: ScanContext,
concurrency: usize,
}
impl ConnectPortScanner {
pub fn new(ctx: ScanContext, concurrency: usize) -> Self {
Self { ctx, concurrency }
}
}
#[async_trait]
impl PortScanner for ConnectPortScanner {
fn kind(&self) -> ScannerKind {
ScannerKind::Connect
}
fn supported_protocols(&self) -> Vec<Protocol> {
vec![Protocol::Tcp]
}
async fn scan(&mut self, rx: mpsc::Receiver<Target>) -> anyhow::Result<()> {
scan(rx, self.concurrency, self.ctx.clone()).await
}
}
pub struct ConnectUdpPortScanner {
ctx: ScanContext,
concurrency: usize,
}
impl ConnectUdpPortScanner {
pub fn new(ctx: ScanContext, concurrency: usize) -> Self {
Self { ctx, concurrency }
}
}
#[async_trait]
impl PortScanner for ConnectUdpPortScanner {
fn kind(&self) -> ScannerKind {
ScannerKind::Connect }
fn supported_protocols(&self) -> Vec<Protocol> {
vec![Protocol::Udp]
}
async fn scan(&mut self, mut rx: mpsc::Receiver<Target>) -> anyhow::Result<()> {
let mut pool = ProbePool::new(self.concurrency, |probed| absorb_probe(&self.ctx, probed));
while let Some(target) = rx.recv().await {
if self.ctx.handle.should_stop() {
break;
}
pool.admit(udp_port_prober(target)).await;
}
pool.drain().await;
Ok(())
}
}
pub async fn scan(
mut rx: mpsc::Receiver<Target>,
concurrency_limit: usize,
ctx: ScanContext,
) -> anyhow::Result<()> {
let mut pool = ProbePool::new(concurrency_limit, |probed| absorb_probe(&ctx, probed));
while let Some(target) = rx.recv().await {
if ctx.handle.should_stop() {
break;
}
pool.admit(port_prober(target)).await;
}
pool.drain().await;
Ok(())
}
fn absorb_probe(ctx: &ScanContext, probed: ProbedPort) {
if let Some((ip, port)) = probed {
ctx.update_host(ip, |host| host.add_port(port));
}
}
async fn port_prober(target: Target) -> ProbedPort {
if target.protocol == Protocol::Udp {
return None;
}
let socket_addr = SocketAddr::new(target.ip, target.port);
match timeout(
tuning::CONNECT_PROBE_TIMEOUT,
TcpStream::connect(socket_addr),
)
.await
{
Ok(Ok(stream)) => {
let port =
crate::fingerprinting::baseline_port(target.port, Protocol::Tcp, PortState::Open);
let port = crate::fingerprinting::fingerprint_tcp(stream, port).await;
Some((target.ip, port))
}
Ok(Err(e)) => {
use std::io::ErrorKind;
match e.kind() {
ErrorKind::ConnectionRefused => None,
_ => Some((
target.ip,
crate::fingerprinting::baseline_port(
target.port,
Protocol::Tcp,
PortState::Filtered,
),
)),
}
}
Err(_) => Some((
target.ip,
crate::fingerprinting::baseline_port(target.port, Protocol::Tcp, PortState::Filtered),
)),
}
}
async fn udp_port_prober(target: Target) -> ProbedPort {
if target.protocol != Protocol::Udp {
return None;
}
let socket_addr = SocketAddr::new(target.ip, target.port);
let socket = match tokio::net::UdpSocket::bind("0.0.0.0:0").await {
Ok(s) => s,
Err(_) => return None,
};
if socket.connect(socket_addr).await.is_err() {
return None;
}
if socket.send(b"").await.is_err() {
return None; }
let mut buf = [0u8; 1024];
match timeout(tuning::CONNECT_PROBE_TIMEOUT, socket.recv(&mut buf)).await {
Ok(Ok(_)) => {
Some((
target.ip,
crate::fingerprinting::baseline_port(target.port, Protocol::Udp, PortState::Open),
))
}
Ok(Err(e)) => {
use std::io::ErrorKind;
if e.kind() == ErrorKind::ConnectionRefused {
Some((
target.ip,
crate::fingerprinting::baseline_port(
target.port,
Protocol::Udp,
PortState::Closed,
),
))
} else {
Some((
target.ip,
crate::fingerprinting::baseline_port(
target.port,
Protocol::Udp,
PortState::OpenFiltered,
),
))
}
}
Err(_) => {
Some((
target.ip,
crate::fingerprinting::baseline_port(
target.port,
Protocol::Udp,
PortState::OpenFiltered,
),
))
}
}
}
pub async fn discover(ips: IpSet, ctx: ScanContext) -> anyhow::Result<()> {
let mut target_map = TargetMap::new();
let port_set = PortSet::try_from(
DISCOVERY_PORTS
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(",")
.as_str(),
)?;
target_map.add_unit(TargetSet::new(ips, port_set));
let dispatcher = Dispatcher::new(target_map).with_batch_size(1024);
let mut rx = dispatcher.run_shuffled(&ctx.handle);
let found_hosts = Arc::new(DashSet::new());
let mut pool = ProbePool::new(tuning::DISCOVERY_CONCURRENCY, |probed| {
absorb_host(&ctx, probed)
});
while let Some(target) = rx.recv().await {
if ctx.handle.should_stop() {
break;
}
let found = Arc::clone(&found_hosts);
pool.admit(prober(target, found)).await;
}
pool.drain().await;
Ok(())
}
type ProbedHost = Option<Host>;
fn absorb_host(ctx: &ScanContext, probed: ProbedHost) {
if let Some(host) = probed {
let ip = host.primary_ip();
ctx.update_host(ip, |existing| existing.merge(host));
}
}
async fn prober(target: Target, found_set: Arc<DashSet<IpAddr>>) -> ProbedHost {
if found_set.contains(&target.ip) {
return None;
}
let socket_addr: SocketAddr = SocketAddr::new(target.ip, target.port);
let start: Instant = Instant::now();
let alive = match timeout(
tuning::CONNECT_PROBE_TIMEOUT,
TcpStream::connect(socket_addr),
)
.await
{
Ok(Ok(_)) => true,
Ok(Err(e)) => {
use std::io::ErrorKind;
matches!(
e.kind(),
ErrorKind::ConnectionRefused
| ErrorKind::ConnectionReset
| ErrorKind::ConnectionAborted
)
}
Err(_elapsed) => false,
};
if alive && found_set.insert(target.ip) {
Some(Host::new(target.ip).with_rtt(start.elapsed()))
} else {
None
}
}