use std::net::IpAddr;
use tokio::net::TcpStream;
use crate::model::ip::scoped::ScopedIp;
use crate::warn;
use tokio::time::timeout;
use crate::config::ServiceDetection;
use crate::fingerprint::os;
use crate::model::port::{Port, PortState, Protocol};
use crate::scanner::pacing::limits::{CONNECT_CONCURRENCY, CONNECT_PROBE_TIMEOUT};
use crate::scanner::pool::ProbePool;
use crate::scanner::session::{ScanContext, ScannerKind};
pub async fn detect(ctx: &ScanContext, detection: ServiceDetection) {
if !detection.connects() {
return;
}
let targets = fingerprintable_ports(ctx);
if targets.is_empty() {
return;
}
let mut pool = ProbePool::new(
CONNECT_CONCURRENCY,
ctx.clone(),
ScannerKind::Connect,
|fingerprinted, _audit| {
if let Some((ip, port, about_the_host)) = fingerprinted {
write_back(ctx, ip, port, about_the_host);
}
},
);
for (target, port, protocol) in targets {
if ctx.handle.should_stop() {
break;
}
pool.admit(fingerprint_one(target, port, protocol, detection))
.await;
}
pool.drain().await;
}
fn fingerprintable_ports(ctx: &ScanContext) -> Vec<(ScopedIp, u16, Protocol)> {
let mut targets = Vec::new();
for host in ctx.store.iter() {
let address = host.value().scoped_ip();
for port in host.value().ports() {
if port.state() == PortState::Open
&& crate::fingerprint::reads_replies(port.number(), port.protocol())
{
targets.push((address.clone(), port.number(), port.protocol()));
}
}
}
targets
}
async fn fingerprint_one(
target: ScopedIp,
port_number: u16,
protocol: Protocol,
detection: ServiceDetection,
) -> Option<(IpAddr, Port, Vec<os::OsEvidence>)> {
let Some(addr) = target.to_socket_addr(port_number) else {
warn!(
verbosity = 1,
"cannot fingerprint {target}:{port_number}: no interface recorded for a link-local address"
);
return None;
};
let ip = target.addr();
let port = crate::fingerprint::baseline_port(port_number, protocol, PortState::Open);
let (port, about_the_host) = match protocol {
Protocol::Tcp => {
let stream = timeout(CONNECT_PROBE_TIMEOUT, TcpStream::connect(addr))
.await
.ok()?
.ok()?;
crate::fingerprint::fingerprint_tcp_detailed(stream, port, detection).await
}
Protocol::Udp => crate::fingerprint::fingerprint_udp_detailed(addr, port).await?,
};
Some((ip, port, about_the_host))
}
fn write_back(ctx: &ScanContext, ip: IpAddr, port: Port, about_the_host: Vec<os::OsEvidence>) {
ctx.update_host(ip, |host| {
host.add_port(port);
if about_the_host.is_empty() {
return;
}
os::identify(host, about_the_host);
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::host::Host;
use crate::scanner::session::ScanSession;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
#[tokio::test]
async fn detect_fingerprints_an_open_tcp_port_end_to_end() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
if let Ok((mut sock, _)) = listener.accept().await {
let _ = sock.write_all(b"SSH-2.0-OpenSSH_9.6p1 Debian-3\r\n").await;
}
});
let (session, ctx) = ScanSession::new();
let ip = addr.ip();
let mut host = Host::new(ip);
host.add_port(Port::new(addr.port(), Protocol::Tcp, PortState::Open));
session.hosts().insert(ip, host);
detect(&ctx, ServiceDetection::default()).await;
let host = session.hosts().get(&ip).unwrap();
let port = host
.ports()
.find(|p| p.number() == addr.port())
.expect("port present");
let service = port.service().expect("service identified");
assert_eq!(service.name(), "ssh");
assert_eq!(service.product(), Some("OpenSSH"));
assert_eq!(service.version(), Some("9.6p1"));
}
#[tokio::test]
async fn detection_turned_off_connects_to_nothing() {
let (session, ctx) = ScanSession::new();
let unreachable: IpAddr = "192.0.2.1".parse().expect("a documentation address");
ctx.update_host(unreachable, |host| {
host.add_port(Port::new(80, Protocol::Tcp, PortState::Open));
});
let started = std::time::Instant::now();
detect(&ctx, ServiceDetection::Off).await;
assert!(
started.elapsed() < CONNECT_PROBE_TIMEOUT,
"a level that connects to nothing cannot have waited on a connection"
);
drop(session);
}
#[tokio::test]
async fn detect_is_a_no_op_with_no_open_ports() {
let (session, ctx) = ScanSession::new();
let ip: IpAddr = "127.0.0.1".parse().unwrap();
let mut host = Host::new(ip);
host.add_port(Port::new(9, Protocol::Tcp, PortState::Closed));
session.hosts().insert(ip, host);
detect(&ctx, ServiceDetection::default()).await;
let host = session.hosts().get(&ip).unwrap();
let port = host.ports().find(|p| p.number() == 9).unwrap();
assert!(port.service().is_none());
}
}