diff --git a/build/nmap_payloads.rs b/build/nmap_payloads.rs index 6d0352b2..56866f9d 100644 --- a/build/nmap_payloads.rs +++ b/build/nmap_payloads.rs @@ -1,10 +1,19 @@ use std::{collections::BTreeMap, fmt::Write}; +/// A probe sent to a port: the index of its shared payload bytes, and its name. +#[derive(PartialEq)] +struct PortProbe { + payload: usize, + name: String, +} + pub fn generate(entries: Vec) -> String { // Resolve overlaps and share payloads at build time. Even a one-port scan // can then borrow static probes without building a 33,000-entry heap map. let mut payloads = Vec::new(); - let mut ports: BTreeMap> = BTreeMap::new(); + // Bytes are shared across ports, but names are chosen per port: probes + // with identical bytes can be configured for different ports. + let mut ports: BTreeMap> = BTreeMap::new(); for entry in entries { let index = match payloads .iter() @@ -17,24 +26,27 @@ pub fn generate(entries: Vec) -> String { } }; for port in entry.ports { - let variants = ports.entry(port).or_default(); - if !variants.contains(&index) { - variants.push(index); + let probes = ports.entry(port).or_default(); + if !probes.iter().any(|probe| probe.payload == index) { + probes.push(PortProbe { + payload: index, + name: entry.name.clone(), + }); } } } - // Merge only adjacent ports with identical variant lists. Overlapping input + // Merge only adjacent ports with identical probe lists. Overlapping input // ranges must retain their combined probes rather than shadowing each other. - let mut ranges: Vec<(u16, u16, Vec)> = Vec::new(); - for (port, variants) in ports { + let mut ranges: Vec<(u16, u16, Vec)> = Vec::new(); + for (port, probes) in ports { if let Some((_, end, previous)) = ranges.last_mut() { - if end.checked_add(1) == Some(port) && *previous == variants { + if end.checked_add(1) == Some(port) && *previous == probes { *end = port; continue; } } - ranges.push((port, port, variants)); + ranges.push((port, port, probes)); } let mut code = String::new(); @@ -42,15 +54,31 @@ pub fn generate(entries: Vec) -> String { writeln!(code, "static PAYLOAD_{index}: &[u8] = &{payload:?};").unwrap(); } code.push_str("pub fn payloads_for(port: u16) -> &'static [&'static [u8]] {\nmatch port {\n"); - for (start, end, variants) in ranges { - let variants = variants + for (start, end, probes) in &ranges { + let payloads = probes + .iter() + .map(|probe| format!("PAYLOAD_{}", probe.payload)) + .collect::>() + .join(", "); + writeln!( + code, + "{start}..={end} => {{ static PROBES: &[&[u8]] = &[{payloads}]; PROBES }}," + ) + .unwrap(); + } + code.push_str("_ => &[],\n}\n}\n"); + + // Index-aligned with `payloads_for`. + code.push_str("pub fn probe_names_for(port: u16) -> &'static [&'static str] {\nmatch port {\n"); + for (start, end, probes) in &ranges { + let names = probes .iter() - .map(|index| format!("PAYLOAD_{index}")) + .map(|probe| format!("{:?}", probe.name)) .collect::>() .join(", "); writeln!( code, - "{start}..={end} => {{ static PROBES: &[&[u8]] = &[{variants}]; PROBES }}," + "{start}..={end} => {{ static NAMES: &[&str] = &[{names}]; NAMES }}," ) .unwrap(); } @@ -60,6 +88,7 @@ pub fn generate(entries: Vec) -> String { #[derive(Debug, PartialEq, Eq)] pub struct Entry { + pub name: String, pub ports: Vec, pub payload: Vec, } @@ -89,7 +118,7 @@ pub fn parse_service_probes(input: &str) -> Result, String> { if protocol != "UDP" { return Err(error("expected TCP or UDP probe")); } - let (_, quoted) = rest + let (name, quoted) = rest .trim_start() .split_once(char::is_whitespace) .ok_or_else(|| error("expected probe name and q-delimited payload"))?; @@ -112,6 +141,7 @@ pub fn parse_service_probes(input: &str) -> Result, String> { .any(|flag| flag.starts_with("no-payload")) { current = Some(Entry { + name: name.to_owned(), ports: Vec::new(), payload, }); diff --git a/docs/udp-payloads.md b/docs/udp-payloads.md index 7273b391..fcde8088 100644 --- a/docs/udp-payloads.md +++ b/docs/udp-payloads.md @@ -35,11 +35,20 @@ only destination that loses a specific probe and now receives an empty datagram, as it does with this Nmap pin. No local exception is retained. SQL Browser's `no-payload` exclusion is also preserved. +## Probe names + +With `--udp --greppable --probe-names`, each open port is followed by the name +of the Nmap probe whose reply opened it, for example +`192.0.2.1 -> [53:DNSStatusRequest,161:SNMPv1public,40000]`. A port that only +answered the empty datagram has no name. Byte-identical probes sharing a port +keep the first probe's name. Without the flag the output is unchanged. + ## Packet budget For a target port, an attempt sends each distinct variant once, or one empty -UDP datagram when no variant exists. There is one timeout per attempt, and the -socket stays alive across retries. Successful replies or explicit rejection +UDP datagram when no variant exists. Each variant goes out from its own source +port, so a reply identifies the probe that drew it. There is one timeout per +attempt, and the sockets stay alive across retries. Successful replies or explicit rejection can end the scan early. For ports **1–65535**, per target IP: diff --git a/src/input.rs b/src/input.rs index e7d94880..3f8a8c15 100644 --- a/src/input.rs +++ b/src/input.rs @@ -230,6 +230,12 @@ pub struct Opts { #[arg(long)] pub closed: bool, + /// In greppable output, append the name of the Nmap probe that drew each + /// UDP reply, as in 53:DNSStatusRequest. Ports that only answered the + /// empty datagram are listed without a name. + #[arg(long)] + pub probe_names: bool, + /// Milliseconds to wait after scanning a port (on every address) before /// scanning the next one, for slow, low-noise scans. 0 disables the delay. #[arg(long, default_value = "0", value_name = "MS")] @@ -323,8 +329,20 @@ impl Opts { } merge_required!( - addresses, greppable, accessible, batch_size, timeout, tries, scan_order, scripts, - command, udp, no_banner, closed, interval + addresses, + greppable, + accessible, + batch_size, + timeout, + tries, + scan_order, + scripts, + command, + udp, + no_banner, + closed, + probe_names, + interval ); } @@ -372,6 +390,7 @@ impl Default for Opts { exclude_addresses: None, udp: false, closed: false, + probe_names: false, interval: 0, cli_args: HashSet::new(), } @@ -402,6 +421,7 @@ pub struct Config { udp: Option, no_banner: Option, closed: Option, + probe_names: Option, interval: Option, } @@ -421,6 +441,7 @@ impl Config { /// exclude_ports = [8080, 9090, 80] /// udp = false /// closed = false + /// probe_names = false /// interval = 0 /// pub fn read(custom_config_path: Option) -> Self { @@ -521,6 +542,7 @@ mod tests { udp: Some(false), no_banner: None, closed: Some(false), + probe_names: Some(false), interval: None, } } diff --git a/src/main.rs b/src/main.rs index d0c8add8..62cc4180 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,7 +12,7 @@ use rustscan::{detail, funny_opening, output, warning}; use colorful::{Color, Colorful}; use std::collections::HashMap; -use std::net::IpAddr; +use std::net::{IpAddr, SocketAddr}; use std::string::ToString; use std::time::Duration; @@ -119,10 +119,16 @@ fn main() { let mut ports_per_ip: HashMap> = HashMap::new(); let mut closed_ports_per_ip: HashMap> = HashMap::new(); + let mut probe_names: HashMap = HashMap::new(); for status in scan_result { let (map, socket) = match status { - PortStatus::Open(socket) => (&mut ports_per_ip, socket), + PortStatus::Open(socket, probe) => { + if let Some(probe) = probe { + probe_names.insert(socket, probe); + } + (&mut ports_per_ip, socket) + } PortStatus::Closed(socket) => (&mut closed_ports_per_ip, socket), }; map.entry(socket.ip()).or_default().push(socket.port()); @@ -154,6 +160,18 @@ fn main() { // if option scripts is none, no script will be spawned if opts.greppable || opts.scripts == ScriptsRequired::None { + let ports_str = if opts.probe_names { + ports + .iter() + .map(|&port| match probe_names.get(&SocketAddr::new(*ip, port)) { + Some(probe) => format!("{port}:{probe}"), + None => port.to_string(), + }) + .collect::>() + .join(",") + } else { + ports_str + }; println_safe(format_args!("{ip} -> [{ports_str}]")); continue; } diff --git a/src/scanner/mod.rs b/src/scanner/mod.rs index 09e9f1e2..4a57b067 100644 --- a/src/scanner/mod.rs +++ b/src/scanner/mod.rs @@ -1,5 +1,5 @@ //! Core functionality for actual scanning behaviour. -use crate::generated::payloads_for; +use crate::generated::{payloads_for, probe_names_for}; use crate::port_strategy::PortStrategy; use crate::tui::println_safe; use log::debug; @@ -94,8 +94,10 @@ pub struct Scanner { /// The outcome for a single socket, as returned by [`Scanner::run_with_status`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PortStatus { - /// The TCP connection succeeded, or the UDP target answered. - Open(SocketAddr), + /// The TCP connection succeeded, or the UDP target answered. For UDP, + /// also the name of the Nmap probe that drew the reply; `None` for TCP + /// and for ports that only got the generic empty datagram. + Open(SocketAddr, Option<&'static str>), /// The target actively refused the TCP connection (for example with a /// RST). Only reported when [`Scanner::with_closed_ports`] is enabled. Closed(SocketAddr), @@ -171,7 +173,7 @@ impl Scanner { .await .into_iter() .filter_map(|status| match status { - PortStatus::Open(socket) => Some(socket), + PortStatus::Open(socket, _) => Some(socket), PortStatus::Closed(_) => None, }) .collect() @@ -226,7 +228,8 @@ impl Scanner { } /// Scans every socket yielded by `sockets`, keeping at most `batch_size` - /// connection attempts in flight. + /// descriptors in flight. A UDP target holds one per probe variant; a + /// target that needs more than the whole batch runs on its own. /// /// Starts sockets and handles finished ones in rounds of at most /// [`WORK_PER_TURN`] of either, and lets the runtime poll for I/O and fire @@ -243,14 +246,20 @@ impl Scanner { errors: &mut ScanErrors, ) { let mut ftrs = FuturesUnordered::new(); + let mut descriptors = 0; + let mut next = sockets.next(); loop { let mut work = 0; while work < WORK_PER_TURN { let mut started = false; - if ftrs.len() < self.batch_size { - if let Some(socket) = sockets.next() { - ftrs.push(self.scan_socket(socket)); + if let Some(socket) = next { + let needed = self.descriptors_for(socket); + if ftrs.is_empty() || descriptors + needed <= self.batch_size { + let scan = self.scan_socket(socket); + ftrs.push(async move { (needed, scan.await) }); + descriptors += needed; + next = sockets.next(); started = true; work += 1; } @@ -258,7 +267,8 @@ impl Scanner { // Poll once without waiting; this starts the new socket. match poll_fn(|cx| Poll::Ready(ftrs.poll_next_unpin(cx))).await { - Poll::Ready(Some(result)) => { + Poll::Ready(Some((released, result))) => { + descriptors -= released; self.record(result, found_sockets, errors); work += 1; } @@ -276,13 +286,24 @@ impl Scanner { // The batch is full (or complete) and every socket in it is // waiting on the network. match ftrs.next().await { - Some(result) => self.record(result, found_sockets, errors), + Some((released, result)) => { + descriptors -= released; + self.record(result, found_sockets, errors); + } None => return, } } } } + fn descriptors_for(&self, socket: SocketAddr) -> usize { + if self.udp { + payloads_for(socket.port()).len().max(1) + } else { + 1 + } + } + /// Records the outcome of one socket. fn record( &self, @@ -313,7 +334,11 @@ impl Scanner { async fn scan_socket(&self, socket: SocketAddr) -> io::Result { if self.udp { return self - .scan_udp_socket(socket, payloads_for(socket.port())) + .scan_udp_socket( + socket, + payloads_for(socket.port()), + probe_names_for(socket.port()), + ) .await; } @@ -328,7 +353,7 @@ impl Scanner { self.fmt_ports(socket); debug!("Return Ok after {nr_try} tries"); - return Ok(PortStatus::Open(socket)); + return Ok(PortStatus::Open(socket, None)); } Err(e) => { // A refused connection is a definitive answer, so there is @@ -353,14 +378,18 @@ impl Scanner { unreachable!(); } - /// Sends every probe variant for the port back-to-back, then waits for a - /// reply, with one timeout per attempt covering both. The socket is kept - /// across attempts, so a late reply to an earlier attempt still counts. - /// An explicit rejection ends the scan without waiting or retrying. + /// Sends every probe variant for the port from its own socket, then waits + /// for a reply on any of them, with one timeout per attempt covering both. + /// A source port per variant tells which probe drew the reply. The sockets + /// are kept across attempts, so a late reply to an earlier attempt still + /// counts. An explicit rejection ends the scan without waiting or retrying. + /// + /// `names` is index-aligned with `payloads`, or empty when unknown. async fn scan_udp_socket( &self, socket: SocketAddr, payloads: &[&[u8]], + names: &[&'static str], ) -> io::Result { const EMPTY_PROBE: &[&[u8]] = &[b""]; let payloads = if payloads.is_empty() { @@ -369,12 +398,19 @@ impl Scanner { payloads }; - let udp_socket = Self::udp_bind(socket).inspect_err(|e| { - debug!("Error binding UDP socket: {e:?}"); - })?; - udp_socket.connect(socket)?; + let udp_sockets = payloads + .iter() + .map(|_| { + let udp_socket = Self::udp_bind(socket)?; + udp_socket.connect(socket)?; + Ok(udp_socket) + }) + .collect::>>() + .inspect_err(|e| { + assert!(!is_descriptor_exhaustion(e), "Too many open files. Please reduce batch size. The default is 5000. Try -b 2500."); + debug!("Error binding UDP socket: {e:?}"); + })?; let mut buf = [0u8; 1024]; - let mut refusals = UdpSendRefusals::new(payloads.len() > 1); let first_deadline = Instant::now() + self.timeout; // Send the probes and try the first receive straight away, as @@ -383,34 +419,43 @@ impl Scanner { // through the event loop, while the probes can almost always be sent // immediately and, on the local host, the answer (often an ICMP "port // unreachable", seen as a refused connection) is usually already - // there when the sends return. The socket is only registered with + // there when the sends return. The sockets are only registered with // Tokio when we really have to wait. - let unsent = send_probes(|probe| udp_socket.send(probe), payloads, &mut refusals)?; - refusals.finish()?; - if unsent.is_empty() { + let mut unsent = Vec::new(); + for (index, (udp_socket, probe)) in udp_sockets.iter().zip(payloads).enumerate() { + match udp_socket.send(probe) { + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::WouldBlock => unsent.push(index), + Err(e) => return Err(e), + } + } + for (index, udp_socket) in udp_sockets.iter().enumerate() { match udp_socket.recv(&mut buf) { - Ok(size) => return Ok(self.udp_open(socket, size)), + Ok(size) => return Ok(self.udp_open(socket, size, names.get(index).copied())), Err(e) if e.kind() == io::ErrorKind::WouldBlock => {} Err(e) => return Err(e), } } - let udp_socket = UdpSocket::from_std(udp_socket)?; + let udp_sockets = udp_sockets + .into_iter() + .map(UdpSocket::from_std) + .collect::>>()?; for attempt in 0..self.tries.get() { let (probes, deadline) = if attempt == 0 { (unsent, first_deadline) } else { - (payloads, Instant::now() + self.timeout) + ((0..payloads.len()).collect(), Instant::now() + self.timeout) }; - let exchange = udp_exchange(&udp_socket, probes, &mut refusals, &mut buf); - let result = timeout_at(deadline, exchange).await; - // A timeout while sending must not retry a known rejection. - refusals.finish()?; - match result { - Ok(Ok(size)) => return Ok(self.udp_open(socket, size)), + let exchange = udp_exchange(&udp_sockets, payloads, &probes); + match timeout_at(deadline, exchange).await { + Ok(Ok((index, size))) => { + return Ok(self.udp_open(socket, size, names.get(index).copied())) + } Ok(Err(e)) if e.kind() != io::ErrorKind::TimedOut => return Err(e), _ => {} } + unsent = Vec::new(); } Err(io::Error::other(format!( @@ -418,10 +463,10 @@ impl Scanner { ))) } - fn udp_open(&self, socket: SocketAddr, size: usize) -> PortStatus { - debug!("Received {size} bytes"); + fn udp_open(&self, socket: SocketAddr, size: usize, probe: Option<&'static str>) -> PortStatus { + debug!("Received {size} bytes in reply to {probe:?}"); self.fmt_ports(socket); - PortStatus::Open(socket) + PortStatus::Open(socket, probe) } /// Performs the connection to the socket with timeout @@ -480,84 +525,44 @@ impl Scanner { } } -/// Sends `probes` back-to-back until they are all sent or the socket would -/// block, and returns the probes left unsent. -/// -/// A connected UDP socket can surface an earlier probe's ICMP rejection on a -/// later send, before that payload leaves the socket. Such a send is retried a -/// bounded number of times, so a peer that keeps rejecting cannot stall it. -fn send_probes<'a>( - mut send: impl FnMut(&[u8]) -> io::Result, - probes: &'a [&'a [u8]], - refusals: &mut UdpSendRefusals, -) -> io::Result<&'a [&'a [u8]]> { - let mut unsent = probes; - while let Some((probe, rest)) = unsent.split_first() { - for _ in 0..=probes.len() { - match send(probe) { +/// Sends the probes at the `unsent` indices, each on its own connected socket, +/// then waits for the first reply on any socket, or for the error a peer +/// answers with. Returns the index of the answering socket and the reply size. +async fn udp_exchange( + sockets: &[UdpSocket], + payloads: &[&[u8]], + unsent: &[usize], +) -> io::Result<(usize, usize)> { + for &index in unsent { + loop { + sockets[index].writable().await?; + match sockets[index].try_send(payloads[index]) { Ok(_) => break, - Err(e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(unsent), - Err(e) => refusals.record(e)?, + Err(e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e), } } - unsent = rest; } - Ok(unsent) -} -/// Sends `probes` on a connected UDP socket, then waits for a reply or the -/// error the peer answers with. -async fn udp_exchange( - socket: &UdpSocket, - probes: &[&[u8]], - refusals: &mut UdpSendRefusals, - buf: &mut [u8], -) -> io::Result { - let mut unsent = probes; - while !unsent.is_empty() { - socket.writable().await?; - unsent = send_probes(|probe| socket.try_send(probe), unsent, refusals)?; - } - refusals.finish()?; - recv_or_error(socket, buf).await -} - -/// Remembers an ICMP rejection surfaced by a send while the rest of a -/// multi-probe burst goes out, so the scan can stop on it afterwards. -/// Single-probe scans and local or resource errors fail straight away. -struct UdpSendRefusals { - multiple: bool, - last: Option, -} - -impl UdpSendRefusals { - fn new(multiple: bool) -> Self { - Self { - multiple, - last: None, - } - } - - fn record(&mut self, error: io::Error) -> io::Result<()> { - if self.multiple && Self::is_refusal(&error) { - self.last = Some(error); - Ok(()) - } else { - Err(error) - } - } - - fn finish(&mut self) -> io::Result<()> { - self.last.take().map_or(Ok(()), Err) - } - - fn is_refusal(error: &io::Error) -> bool { - // Winsock reports an ICMP port-unreachable as ConnectionReset. - matches!( - error.kind(), - io::ErrorKind::ConnectionRefused | io::ErrorKind::ConnectionReset - ) - } + // Most ports have a single probe; skip the set of futures for them. + if let [socket] = sockets { + let mut buf = [0u8; 1024]; + return recv_or_error(socket, &mut buf).await.map(|size| (0, size)); + } + let mut replies: FuturesUnordered<_> = sockets + .iter() + .enumerate() + .map(|(index, socket)| async move { + let mut buf = [0u8; 1024]; + recv_or_error(socket, &mut buf) + .await + .map(|size| (index, size)) + }) + .collect(); + replies + .next() + .await + .expect("a UDP scan always has at least one probe") } /// Shuts down both halves of a connected stream before it is closed, as the @@ -750,32 +755,15 @@ mod tests { } #[test] - fn send_refusals_are_kept_only_for_multi_probe_bursts() { - for kind in [ - io::ErrorKind::ConnectionRefused, - io::ErrorKind::ConnectionReset, - ] { - let mut multiple = UdpSendRefusals::new(true); - assert!(multiple.record(kind.into()).is_ok()); - assert_eq!(multiple.finish().unwrap_err().kind(), kind); - assert!(multiple.finish().is_ok()); - - let mut single = UdpSendRefusals::new(false); - assert_eq!(single.record(kind.into()).unwrap_err().kind(), kind); - } - } - - #[test] - fn local_send_errors_fail_a_burst_straight_away() { - for kind in [ - io::ErrorKind::PermissionDenied, - io::ErrorKind::OutOfMemory, - io::ErrorKind::AddrNotAvailable, - ] { - let mut multiple = UdpSendRefusals::new(true); - assert_eq!(multiple.record(kind.into()).unwrap_err().kind(), kind); - assert!(multiple.finish().is_ok()); - } + fn udp_targets_count_one_descriptor_per_probe_variant() { + let tcp = test_scanner(); + let mut udp = test_scanner(); + udp.udp = true; + let target = |port| SocketAddr::from(([127, 0, 0, 1], port)); + + assert_eq!(tcp.descriptors_for(target(161)), 1); + assert_eq!(udp.descriptors_for(target(161)), payloads_for(161).len()); + assert_eq!(udp.descriptors_for(target(1)), 1, "the empty datagram"); } #[test] diff --git a/src/scanner/udp_socket_tests.rs b/src/scanner/udp_socket_tests.rs index ee51b8d4..7955f2e6 100644 --- a/src/scanner/udp_socket_tests.rs +++ b/src/scanner/udp_socket_tests.rs @@ -35,7 +35,7 @@ async fn scan( target: SocketAddr, payloads: &[&'static [u8]], ) -> io::Result { - scanner.scan_udp_socket(target, payloads).await + scanner.scan_udp_socket(target, payloads, &[]).await } async fn receive(server: &UdpSocket) -> (Vec, SocketAddr) { @@ -49,27 +49,36 @@ async fn receive(server: &UdpSocket) -> (Vec, SocketAddr) { #[test] #[ignore = "opens sockets; run by the UDP regression workflow"] -fn a_reply_to_any_variant_marks_the_port_open() { +fn a_reply_names_the_variant_that_drew_it() { block_on(async { for address in ["127.0.0.1:0", "[::1]:0"] { for answered in 0..4 { let server = UdpSocket::bind(address).await.unwrap(); let target = server.local_addr().unwrap(); let payloads: &[&[u8]] = &[b"first", b"second", b"third", b"fourth"]; + let names = &["First", "Second", "Third", "Fourth"]; let responder = spawn(async move { let mut peers = Vec::new(); - for (index, expected) in payloads.iter().enumerate() { + for _ in payloads { let (payload, peer) = receive(&server).await; - assert_eq!(payload, *expected); + let index = payloads.iter().position(|p| *p == payload).unwrap(); peers.push(peer); if index == answered { server.send_to(&[], peer).await.unwrap(); } } - assert!(peers.iter().all(|peer| *peer == peers[0])); + peers.sort(); + peers.dedup(); + assert_eq!(peers.len(), payloads.len(), "one source port per variant"); }); - let status = scan(&udp_scanner(Duration::from_secs(2), 2), target, payloads).await; - assert!(matches!(status, Ok(PortStatus::Open(_))), "{:?}", status); + let status = udp_scanner(Duration::from_secs(2), 2) + .scan_udp_socket(target, payloads, names) + .await; + assert!( + matches!(status, Ok(PortStatus::Open(_, Some(name))) if name == names[answered]), + "{:?}", + status + ); responder.await.unwrap(); } } @@ -95,7 +104,11 @@ fn the_last_variant_gets_the_whole_response_window() { }); let payloads: &[&[u8]] = &[b"first", b"second", b"third", b"fourth"]; let status = scan(&udp_scanner(Duration::from_secs(2), 1), target, payloads).await; - assert!(matches!(status, Ok(PortStatus::Open(_))), "{:?}", status); + assert!( + matches!(status, Ok(PortStatus::Open(_, None))), + "{:?}", + status + ); responder.await.unwrap(); }); } @@ -116,7 +129,11 @@ fn a_late_reply_to_the_first_attempt_still_counts() { server.send_to(b"late", first).await.unwrap(); }); let status = scan(&udp_scanner(Duration::from_secs(1), 2), target, &[b"probe"]).await; - assert!(matches!(status, Ok(PortStatus::Open(_))), "{:?}", status); + assert!( + matches!(status, Ok(PortStatus::Open(_, None))), + "{:?}", + status + ); responder.await.unwrap(); }); } @@ -153,9 +170,12 @@ fn silent_ports_send_each_variant_once_per_attempt() { } } assert_eq!(packets.len(), payloads.len() * 2); - for (index, (payload, peer)) in packets.iter().enumerate() { - assert_eq!(payload, payloads[index % payloads.len()]); - assert_eq!(*peer, packets[0].1); + let (first, retry) = packets.split_at(payloads.len()); + for (index, ((payload, peer), (retried, retry_peer))) in first.iter().zip(retry).enumerate() + { + assert_eq!(payload, payloads[index]); + assert_eq!(retried, payloads[index]); + assert_eq!(peer, retry_peer, "retries must keep the source port"); } }); } @@ -173,7 +193,11 @@ fn ports_without_a_payload_get_one_empty_datagram() { server.send_to(b"response", peer).await.unwrap(); }); let status = scan(&udp_scanner(Duration::from_secs(2), 1), target, payloads).await; - assert!(matches!(status, Ok(PortStatus::Open(_))), "{:?}", status); + assert!( + matches!(status, Ok(PortStatus::Open(_, None))), + "{:?}", + status + ); responder.await.unwrap(); } }); diff --git a/tests/udp_payload_lookup.rs b/tests/udp_payload_lookup.rs index be600200..60fd048f 100644 --- a/tests/udp_payload_lookup.rs +++ b/tests/udp_payload_lookup.rs @@ -1,4 +1,4 @@ -use rustscan::generated::payloads_for; +use rustscan::generated::{payloads_for, probe_names_for}; #[test] fn udp_payload_lookup_contains_common_udp_ports() { @@ -73,3 +73,39 @@ fn ports_without_a_payload_return_no_probes() { assert!(payloads_for(0).is_empty()); assert!(payloads_for(1).is_empty()); } + +#[test] +fn every_probe_variant_has_a_name() { + for port in 0..=u16::MAX { + assert_eq!( + probe_names_for(port).len(), + payloads_for(port).len(), + "port {}", + port + ); + } +} + +#[test] +fn probe_names_follow_the_nmap_database() { + assert_eq!(probe_names_for(161), ["SNMPv1public", "SNMPv3GetRequest"]); + assert!(probe_names_for(1).is_empty()); +} + +#[test] +fn probes_sharing_bytes_keep_the_name_configured_for_the_port() { + // GPRS_GTPv2prime sends the same bytes but is configured for 3386 only. + for port in [2123, 2152] { + assert!( + probe_names_for(port).contains(&"GPRS_GTPv2"), + "port {}", + port + ); + assert!( + !probe_names_for(port).contains(&"GPRS_GTPv2prime"), + "port {}", + port + ); + } + assert!(probe_names_for(3386).contains(&"GPRS_GTPv2prime")); +} diff --git a/tests/udp_payloads.rs b/tests/udp_payloads.rs index 7700748a..08893434 100644 --- a/tests/udp_payloads.rs +++ b/tests/udp_payloads.rs @@ -32,6 +32,7 @@ ports 0,53", assert_eq!(entries[0].payload, b"a#b|\0\n\r\t\\"); assert_eq!(entries[1].ports, [0, 53]); assert_eq!(entries[1].payload, b"final"); + assert_eq!([&entries[0].name, &entries[1].name], ["First", "Last"]); } #[test]