Files
harpia/crates/xexeu-core/src/scan/discovery.rs
T

214 lines
7.3 KiB
Rust

//! Host discovery engine in degraded `nativo-sem-raw` mode (TCP connect probes).
//!
//! # Determinism Guarantee
//!
//! Host discovery output is strictly deterministic given identical network conditions:
//! - Results are always returned sorted by IP address ascending.
//! - A host is classified as [`HostState::Alive`] as soon as any probed port responds
//! (either connection established or active connection refusal / TCP RST).
//! - A host is classified as [`HostState::Unresponsive`] only if all probed ports
//! time out or yield network unreachability errors.
//!
//! **Important:** Timeouts and concurrency limits are the only sources of potential
//! variation across executions (e.g. temporary packet drops on congested paths
//! causing timeouts before RST/SYN-ACK is received). Appropriate timeout margins
//! prevent Nmap-like discovery flapping.
//!
//! // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3
use super::ports::{scan_port_tcp_connect, PortState};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Semaphore;
/// State of a discovered host.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum HostState {
/// Host responded on at least one probed port (SYN-ACK or RST).
Alive,
/// Host did not respond on any probed port within the timeout window.
Unresponsive,
}
/// Result of probing a single host for presence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct HostDiscoveryResult {
/// Target IP address.
pub ip: IpAddr,
/// Whether the host is confirmed alive or unresponsive.
pub state: HostState,
/// The first port that confirmed the host is alive (if any).
pub responded_port: Option<u16>,
}
/// Default ports probed for TCP connect host discovery when ICMP/ARP is unavailable.
pub const DEFAULT_DISCOVERY_PORTS: &[u16] = &[80, 443, 22, 445, 3389];
/// Configuration options for host discovery.
#[derive(Debug, Clone)]
pub struct DiscoveryConfig {
/// Ports probed to verify whether a host is active.
pub ports: Vec<u16>,
/// Connection timeout per port probe.
pub timeout: Duration,
/// Maximum number of hosts evaluated concurrently (`hosts_simultaneos`).
pub max_concurrency: usize,
}
impl Default for DiscoveryConfig {
fn default() -> Self {
Self {
ports: DEFAULT_DISCOVERY_PORTS.to_vec(),
timeout: Duration::from_millis(500),
max_concurrency: 64,
}
}
}
/// Checks whether a single IP address is alive by probing candidate TCP ports.
///
/// In `nativo-sem-raw` mode without `NET_RAW`, we cannot send ICMP echo or ARP requests.
/// Instead, we probe common ports via TCP connect. An `Open` or `Closed` (RST) response
/// indicates that the host's network stack is actively processing packets.
///
/// // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3
pub async fn probe_host_tcp(ip: IpAddr, config: &DiscoveryConfig) -> HostDiscoveryResult {
for &port in &config.ports {
let state = scan_port_tcp_connect(ip, port, config.timeout).await;
match state {
PortState::Open | PortState::Closed => {
return HostDiscoveryResult {
ip,
state: HostState::Alive,
responded_port: Some(port),
};
}
PortState::Filtered => continue,
}
}
HostDiscoveryResult {
ip,
state: HostState::Unresponsive,
responded_port: None,
}
}
/// Discovers active hosts across a slice of IP addresses.
///
/// Execution is parallelized up to `config.max_concurrency` (`hosts_simultaneos`).
/// Results are always returned in deterministic ascending order of IP addresses.
pub async fn discover_hosts_tcp(
hosts: &[IpAddr],
config: &DiscoveryConfig,
) -> Vec<HostDiscoveryResult> {
if hosts.is_empty() {
return Vec::new();
}
let mut unique_hosts = hosts.to_vec();
unique_hosts.sort_unstable();
unique_hosts.dedup();
let semaphore = Arc::new(Semaphore::new(config.max_concurrency.max(1)));
let mut handles = Vec::with_capacity(unique_hosts.len());
for ip in unique_hosts {
let sem = Arc::clone(&semaphore);
let cfg = config.clone();
handles.push(tokio::spawn(async move {
let _permit = sem.acquire().await.ok();
probe_host_tcp(ip, &cfg).await
}));
}
let mut results = Vec::with_capacity(handles.len());
for handle in handles {
if let Ok(res) = handle.await {
results.push(res);
}
}
// Deterministic ordering: always sort by IP ascending
results.sort_by_key(|r| r.ip);
results
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
use tokio::net::TcpListener;
#[tokio::test]
async fn test_discover_host_alive_on_open_port() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let _server = tokio::spawn(async move {
let _ = listener.accept().await;
});
let config = DiscoveryConfig {
ports: vec![port],
timeout: Duration::from_millis(500),
max_concurrency: 2,
};
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
let result = probe_host_tcp(ip, &config).await;
assert_eq!(result.state, HostState::Alive);
assert_eq!(result.responded_port, Some(port));
}
#[tokio::test]
async fn test_discover_host_alive_on_closed_rst_port() {
// Ephemeral port bound and immediately dropped -> closed port on localhost (RST)
let dummy = TcpListener::bind("127.0.0.1:0").await.unwrap();
let closed_port = dummy.local_addr().unwrap().port();
drop(dummy);
let config = DiscoveryConfig {
ports: vec![closed_port],
timeout: Duration::from_millis(500),
max_concurrency: 2,
};
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
let result = probe_host_tcp(ip, &config).await;
// Receiving RST confirms the host network stack is active
assert_eq!(result.state, HostState::Alive);
assert_eq!(result.responded_port, Some(closed_port));
}
#[tokio::test]
async fn test_discover_hosts_unresponsive_and_deterministic_order() {
// 192.0.2.1 and 192.0.2.2 are reserved documentation IPs (TEST-NET-1)
// With a tiny timeout, they should time out and count as Unresponsive.
let ip_a = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2));
let ip_b = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
let config = DiscoveryConfig {
ports: vec![80],
timeout: Duration::from_millis(50),
max_concurrency: 2,
};
// Pass out of order
let results = discover_hosts_tcp(&[ip_a, ip_b], &config).await;
assert_eq!(results.len(), 2);
// Verify deterministic sorting: ip_b (192.0.2.1) < ip_a (192.0.2.2)
assert_eq!(results[0].ip, ip_b);
assert_eq!(results[1].ip, ip_a);
assert_eq!(results[0].state, HostState::Unresponsive);
assert_eq!(results[1].state, HostState::Unresponsive);
assert_eq!(results[0].responded_port, None);
}
}