Files
harpia/crates/harpia-core/src/scan/ports.rs
T
Lucas RayanandClaude Sonnet 5 5ed6cb2c95
Release / Build image (amd64) (push) Successful in 10m49s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 20m40s
CI / Format and clippy (push) Successful in 5m43s
CI / Tests (Linux) (push) Successful in 16m5s
CI / Dependency audit (push) Successful in 11s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Successful in 7m34s
Release / Publish tags (push) Successful in 15s
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped
refactor!: rename project from Xexéu to Harpia
Renames the whole project, after the harpy eagle: crates
(xexeu-core/xexeu-cli -> harpia-core/harpia-cli), binary (xexeu ->
harpia), admin token env var (XEXEU_ADMIN_TOKEN -> HARPIA_ADMIN_TOKEN),
compose env vars (XEXEU_* -> HARPIA_*), container image
(ciberfauna/xexeu -> ciberfauna/harpia) and the Gitea repository
(ciberfauna/xexeu -> ciberfauna/harpia). Logo updated to the new brand
artwork. All docs (EN/PT-BR), CI workflows, scripts, GUI strings and
the openspec change history updated to match.

BREAKING CHANGE: binary, crate, env var and image names all changed;
existing .env files, scripts and deployments referencing the old
xexeu/XEXEU names must be updated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8cd6jzwpJM9cS1oGjy
2026-11-03 13:43:21 -03:00

384 lines
13 KiB
Rust

//! TCP port scanning engine in degraded `nativo-sem-raw` mode (TCP connect).
//!
//! # Determinism Guarantee
//!
//! Given the same target environment and network conditions, scans produce
//! identical results with deterministic ordering:
//! - Results for a host are always sorted by port number ascending.
//! - Multi-host results are always sorted by IP address ascending.
//!
//! **Important:** Timeouts and network concurrency limits are the only sources of
//! potential variation across executions (e.g. dropped packets on congested links
//! causing a port to be classified as `Filtered` instead of `Closed`). To avoid
//! the intermittent instability common in Nmap, timeouts should be tuned with
//! appropriate margin for network latency.
//!
//! // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::sync::Semaphore;
/// State of a probed TCP port.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum PortState {
/// Port is open and accepted a TCP connection (SYN-ACK received).
Open,
/// Port is closed and explicitly rejected the connection (RST received / connection refused).
Closed,
/// Port is filtered or unresponsive (timeout, packet dropped, or ICMP unreachable).
Filtered,
}
/// Target port specification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PortTarget {
/// Explicit list of port numbers.
List(Vec<u16>),
/// Inclusive range of ports (e.g. 1-1024 or 1-65535).
Range(u16, u16),
/// Top 1000 commonly used TCP ports.
Top1000,
}
impl PortTarget {
/// Parses a port specification string such as:
/// - `"top-1000"` or `"top1000"`
/// - `"1-1024"`, `"1-65535"`
/// - `"80,443,8080"`
pub fn parse(spec: &str) -> Result<Self, String> {
let trimmed = spec.trim();
if trimmed.eq_ignore_ascii_case("top-1000") || trimmed.eq_ignore_ascii_case("top1000") {
return Ok(PortTarget::Top1000);
}
if !trimmed.contains(',') {
if let Some((start_s, end_s)) = trimmed.split_once('-') {
let start: u16 = start_s
.trim()
.parse()
.map_err(|e| format!("invalid range start in '{trimmed}': {e}"))?;
let end: u16 = end_s
.trim()
.parse()
.map_err(|e| format!("invalid range end in '{trimmed}': {e}"))?;
if start == 0 || start > end {
return Err(format!(
"invalid port range '{trimmed}': start must be >= 1 and <= end"
));
}
return Ok(PortTarget::Range(start, end));
}
}
let mut ports = Vec::new();
for part in trimmed.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
if let Some((s, e)) = part.split_once('-') {
let start: u16 = s
.trim()
.parse()
.map_err(|err| format!("invalid port range start '{s}': {err}"))?;
let end: u16 = e
.trim()
.parse()
.map_err(|err| format!("invalid port range end '{e}': {err}"))?;
if start == 0 || start > end {
return Err(format!("invalid port range '{s}-{e}'"));
}
for p in start..=end {
ports.push(p);
}
} else {
let p: u16 = part
.parse()
.map_err(|err| format!("invalid port number '{part}': {err}"))?;
if p == 0 {
return Err("port number 0 is reserved and invalid".into());
}
ports.push(p);
}
}
if ports.is_empty() {
return Err("no valid ports specified".into());
}
ports.sort_unstable();
ports.dedup();
Ok(PortTarget::List(ports))
}
/// Resolves the specification into a deduplicated, sorted list of port numbers.
pub fn to_ports(&self) -> Vec<u16> {
match self {
PortTarget::List(ports) => {
let mut p = ports.clone();
p.sort_unstable();
p.dedup();
p
}
PortTarget::Range(start, end) => (*start..=*end).collect(),
PortTarget::Top1000 => TOP_1000_PORTS.to_vec(),
}
}
}
/// Result of probing a single port on a host.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct PortScanResult {
pub port: u16,
pub state: PortState,
}
/// Result of scanning all specified ports on a host.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct HostPortScanResult {
pub ip: IpAddr,
pub ports: Vec<PortScanResult>,
}
/// Configuration options for port scanning.
#[derive(Debug, Clone)]
pub struct PortScanConfig {
/// Connection timeout per port probe.
pub timeout: Duration,
/// Maximum number of concurrent in-flight connections.
pub max_concurrency: usize,
}
impl Default for PortScanConfig {
fn default() -> Self {
Self {
timeout: Duration::from_millis(1500),
max_concurrency: 64,
}
}
}
/// Probes a single TCP port using TCP connect (`nativo-sem-raw`).
///
/// // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3
pub async fn scan_port_tcp_connect(ip: IpAddr, port: u16, timeout_duration: Duration) -> PortState {
let addr = SocketAddr::new(ip, port);
match tokio::time::timeout(timeout_duration, TcpStream::connect(addr)).await {
Ok(Ok(stream)) => {
drop(stream);
PortState::Open
}
Ok(Err(err)) => match err.kind() {
std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::ConnectionReset => {
PortState::Closed
}
std::io::ErrorKind::TimedOut => PortState::Filtered,
_ => PortState::Filtered,
},
Err(_elapsed) => PortState::Filtered,
}
}
/// Scans a slice of ports on a target IP address using TCP connect mode.
///
/// Results are always returned in deterministic ascending order of port numbers.
pub async fn scan_tcp_connect(
target: IpAddr,
ports: &[u16],
config: &PortScanConfig,
) -> Vec<PortScanResult> {
if ports.is_empty() {
return Vec::new();
}
let mut unique_ports = ports.to_vec();
unique_ports.sort_unstable();
unique_ports.dedup();
let semaphore = Arc::new(Semaphore::new(config.max_concurrency.max(1)));
let mut handles = Vec::with_capacity(unique_ports.len());
for port in unique_ports {
let sem = Arc::clone(&semaphore);
let timeout = config.timeout;
handles.push(tokio::spawn(async move {
let _permit = sem.acquire().await.ok();
let state = scan_port_tcp_connect(target, port, timeout).await;
PortScanResult { port, state }
}));
}
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 port ascending
results.sort_by_key(|r| r.port);
results
}
/// Scans multiple hosts across the specified port list.
///
/// Results are returned in deterministic order: sorted by IP address ascending,
/// with each host's ports sorted by port number ascending.
pub async fn scan_hosts_tcp_connect(
hosts: &[IpAddr],
ports: &[u16],
config: &PortScanConfig,
) -> Vec<HostPortScanResult> {
if hosts.is_empty() {
return Vec::new();
}
let mut sorted_hosts = hosts.to_vec();
sorted_hosts.sort_unstable();
sorted_hosts.dedup();
let mut results = Vec::with_capacity(sorted_hosts.len());
for ip in sorted_hosts {
let port_results = scan_tcp_connect(ip, ports, config).await;
results.push(HostPortScanResult {
ip,
ports: port_results,
});
}
results
}
/// Static preset of 1000 commonly audited TCP ports (sorted ascending).
///
/// Contains well-known ports (1..=950) plus standard application service ports
/// (e.g. 1433, 1521, 3306, 3389, 5432, 6379, 8080, 8443, 27017).
pub static TOP_1000_PORTS: [u16; 1000] = {
// Generate 1..=950 and 50 well-known high service ports
let high: [u16; 50] = [
1080, 1194, 1433, 1434, 1521, 1723, 1883, 2049, 2082, 2083, 2086, 2087, 2181, 2222, 2375,
2376, 3000, 3128, 3306, 3389, 4369, 5000, 5432, 5672, 5900, 5901, 5984, 5985, 5986, 6379,
6667, 7000, 7001, 8000, 8008, 8080, 8081, 8443, 8500, 8888, 9000, 9042, 9090, 9092, 9200,
9300, 9418, 9999, 11211, 27017,
];
let mut arr = [0u16; 1000];
let mut i = 0;
while i < 950 {
arr[i] = (i + 1) as u16;
i += 1;
}
let mut j = 0;
while j < 50 {
arr[950 + j] = high[j];
j += 1;
}
arr
};
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
use tokio::net::TcpListener;
#[test]
fn test_top_1000_ports_length_and_ordering() {
assert_eq!(TOP_1000_PORTS.len(), 1000);
assert_eq!(TOP_1000_PORTS[0], 1);
assert_eq!(TOP_1000_PORTS[949], 950);
assert_eq!(TOP_1000_PORTS[999], 27017);
// Ensure strictly sorted
for window in TOP_1000_PORTS.windows(2) {
assert!(window[0] < window[1]);
}
}
#[test]
fn test_port_target_parsing() {
let t1 = PortTarget::parse("top-1000").expect("valid");
assert_eq!(t1, PortTarget::Top1000);
assert_eq!(t1.to_ports().len(), 1000);
let t2 = PortTarget::parse("1-100").expect("valid");
assert_eq!(t2, PortTarget::Range(1, 100));
assert_eq!(t2.to_ports().len(), 100);
let t3 = PortTarget::parse("80, 443, 8080, 80").expect("valid");
assert_eq!(t3.to_ports(), vec![80, 443, 8080]);
let t4 = PortTarget::parse("22, 100-103").expect("valid");
assert_eq!(t4.to_ports(), vec![22, 100, 101, 102, 103]);
assert!(PortTarget::parse("0").is_err());
assert!(PortTarget::parse("500-100").is_err());
assert!(PortTarget::parse("abc").is_err());
}
#[tokio::test]
async fn test_ports_tcp_connect_open_and_closed() {
// Bind an ephemeral listener to simulate an open port
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind ephemeral listener");
let open_port = listener.local_addr().unwrap().port();
// Spawn a background task to accept connections so the port remains Open
let server_handle = tokio::spawn(async move {
if let Ok((stream, _)) = listener.accept().await {
drop(stream);
}
});
// Find an unused/closed port on 127.0.0.1
let dummy = TcpListener::bind("127.0.0.1:0").await.unwrap();
let closed_port = dummy.local_addr().unwrap().port();
drop(dummy); // dropping immediately closes the port
let config = PortScanConfig {
timeout: Duration::from_millis(1000),
max_concurrency: 4,
};
let target = IpAddr::V4(Ipv4Addr::LOCALHOST);
// Pass out of order to verify sorting
let scan_results = scan_tcp_connect(target, &[closed_port, open_port], &config).await;
assert_eq!(scan_results.len(), 2);
// Verify deterministic sorting by port ascending
assert!(scan_results[0].port < scan_results[1].port);
let open_res = scan_results.iter().find(|r| r.port == open_port).unwrap();
let closed_res = scan_results.iter().find(|r| r.port == closed_port).unwrap();
assert_eq!(open_res.state, PortState::Open);
assert_eq!(closed_res.state, PortState::Closed);
server_handle.abort();
}
#[tokio::test]
async fn test_scan_hosts_tcp_connect_deterministic_order() {
let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2));
let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
let config = PortScanConfig {
timeout: Duration::from_millis(50),
max_concurrency: 2,
};
// Pass IPs out of order: [127.0.0.2, 127.0.0.1]
let results = scan_hosts_tcp_connect(&[ip1, ip2], &[80, 443], &config).await;
assert_eq!(results.len(), 2);
assert_eq!(results[0].ip, ip2);
assert_eq!(results[1].ip, ip1);
assert_eq!(results[0].ports[0].port, 80);
assert_eq!(results[0].ports[1].port, 443);
}
}