Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 44 additions & 14 deletions build/nmap_payloads.rs
Original file line number Diff line number Diff line change
@@ -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<Entry>) -> 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<u16, Vec<usize>> = 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<u16, Vec<PortProbe>> = BTreeMap::new();
for entry in entries {
let index = match payloads
.iter()
Expand All @@ -17,40 +26,59 @@ pub fn generate(entries: Vec<Entry>) -> 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<usize>)> = Vec::new();
for (port, variants) in ports {
let mut ranges: Vec<(u16, u16, Vec<PortProbe>)> = 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();
for (index, payload) in payloads.iter().enumerate() {
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::<Vec<_>>()
.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::<Vec<_>>()
.join(", ");
writeln!(
code,
"{start}..={end} => {{ static PROBES: &[&[u8]] = &[{variants}]; PROBES }},"
"{start}..={end} => {{ static NAMES: &[&str] = &[{names}]; NAMES }},"
)
.unwrap();
}
Expand All @@ -60,6 +88,7 @@ pub fn generate(entries: Vec<Entry>) -> String {

#[derive(Debug, PartialEq, Eq)]
pub struct Entry {
pub name: String,
pub ports: Vec<u16>,
pub payload: Vec<u8>,
}
Expand Down Expand Up @@ -89,7 +118,7 @@ pub fn parse_service_probes(input: &str) -> Result<Vec<Entry>, 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"))?;
Expand All @@ -112,6 +141,7 @@ pub fn parse_service_probes(input: &str) -> Result<Vec<Entry>, String> {
.any(|flag| flag.starts_with("no-payload"))
{
current = Some(Entry {
name: name.to_owned(),
ports: Vec::new(),
payload,
});
Expand Down
13 changes: 11 additions & 2 deletions docs/udp-payloads.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
26 changes: 24 additions & 2 deletions src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -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
);
}

Expand Down Expand Up @@ -372,6 +390,7 @@ impl Default for Opts {
exclude_addresses: None,
udp: false,
closed: false,
probe_names: false,
interval: 0,
cli_args: HashSet::new(),
}
Expand Down Expand Up @@ -402,6 +421,7 @@ pub struct Config {
udp: Option<bool>,
no_banner: Option<bool>,
closed: Option<bool>,
probe_names: Option<bool>,
interval: Option<u64>,
}

Expand All @@ -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<PathBuf>) -> Self {
Expand Down Expand Up @@ -521,6 +542,7 @@ mod tests {
udp: Some(false),
no_banner: None,
closed: Some(false),
probe_names: Some(false),
interval: None,
}
}
Expand Down
22 changes: 20 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -119,10 +119,16 @@ fn main() {

let mut ports_per_ip: HashMap<IpAddr, Vec<u16>> = HashMap::new();
let mut closed_ports_per_ip: HashMap<IpAddr, Vec<u16>> = HashMap::new();
let mut probe_names: HashMap<SocketAddr, &str> = 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());
Expand Down Expand Up @@ -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::<Vec<_>>()
.join(",")
} else {
ports_str
};
println_safe(format_args!("{ip} -> [{ports_str}]"));
continue;
}
Expand Down
Loading