use std::io::BufRead;
use crate::import::xml::{Element, Event, Parser};
use crate::import::{ImportError, ImportLimits, ImportOrigin, Importer, TargetSink};
use crate::model::port::Protocol;
const FORMAT: &str = "nmap XML";
const KEPT: &[&[u8]] = &[b"addr", b"addrtype", b"protocol", b"portid"];
#[derive(Debug, Clone, Copy, Default)]
pub struct NmapXmlImporter {
limits: ImportLimits,
}
impl NmapXmlImporter {
pub fn new(limits: ImportLimits) -> Self {
Self { limits }
}
}
impl Importer for NmapXmlImporter {
fn import(
&self,
input: &mut dyn BufRead,
sink: &mut dyn TargetSink,
) -> Result<(), ImportError> {
crate::import::skip_bom(input)?;
let mut parser = Parser::new(input, self.limits.max_line_bytes, FORMAT, KEPT);
let mut host: Option<Accumulator> = None;
let mut saw_root = false;
let mut token = String::new();
loop {
match parser.next_event()? {
Event::Eof => break,
Event::Start { self_closing } => {
match parser.element.name.as_slice() {
b"nmaprun" => saw_root = true,
b"host" => host = Some(Accumulator::default()),
b"address" => {
if let Some(accumulator) = host.as_mut() {
accumulator.address(&parser.element)?;
}
}
b"port" => {
if let Some(accumulator) = host.as_mut() {
accumulator.port(&parser.element, &parser)?;
}
}
_ => {}
}
if self_closing && parser.element.name == b"host" {
emit(host.take(), sink, &mut token, parser.origin())?;
}
}
Event::End => {
if parser.element.name == b"host" {
emit(host.take(), sink, &mut token, parser.origin())?;
}
}
}
}
if !saw_root {
return Err(ImportError::Malformed {
format: FORMAT,
origin: ImportOrigin::unknown(),
message: "no <nmaprun> element: this is not an nmap document".to_string(),
});
}
Ok(())
}
}
#[derive(Debug, Default)]
struct Accumulator {
addresses: Vec<String>,
ports: Vec<(u16, Protocol)>,
}
impl Accumulator {
fn address(&mut self, element: &Element) -> Result<(), ImportError> {
let kind = element.value(b"addrtype").unwrap_or("");
if kind != "ipv4" && kind != "ipv6" {
return Ok(());
}
if let Some(address) = element.value(b"addr")
&& !address.is_empty()
{
self.addresses.push(address.to_string());
}
Ok(())
}
fn port(&mut self, element: &Element, parser: &Parser<'_>) -> Result<(), ImportError> {
let Some(number) = element.value(b"portid") else {
return Ok(());
};
let number: u16 = number
.parse()
.map_err(|_| parser.malformed(format!("'{number}' is not a port number")))?;
let name = element.value(b"protocol").unwrap_or("tcp");
if name == "ip" {
return Ok(());
}
let Some(protocol) = crate::record::wire::protocol(name) else {
return Err(parser.malformed(format!(
"port {number} names transport '{name}', which this build cannot probe"
)));
};
self.ports.push((number, protocol));
Ok(())
}
}
const MAX_HOST_EXPANSION: usize = 1 << 20;
fn emit(
host: Option<Accumulator>,
sink: &mut dyn TargetSink,
token: &mut String,
origin: ImportOrigin,
) -> Result<(), ImportError> {
let Some(host) = host else {
return Ok(());
};
let expansion = host.addresses.len().saturating_mul(host.ports.len());
if expansion > MAX_HOST_EXPANSION {
return Err(ImportError::Malformed {
format: FORMAT,
origin,
message: format!(
"one host expands to {expansion} address/port pairs, past the {MAX_HOST_EXPANSION} \
this reader accepts: {} addresses times {} ports",
host.addresses.len(),
host.ports.len()
),
});
}
let mut ports = String::new();
for (number, protocol) in &host.ports {
if !ports.is_empty() {
ports.push(',');
}
ports.push_str(protocol.spec_prefix());
ports.push_str(&number.to_string());
}
for address in &host.addresses {
crate::import::expression(token, address, &ports);
sink.accept(token, origin)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::import::{ImportFormat, ImportOptions, Imported};
use crate::model::port::PortSet;
use std::io::Cursor;
const REAL_PREAMBLE: &str = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
"<!DOCTYPE nmaprun>\n",
"<?xml-stylesheet href=\"file:///usr/share/nmap/nmap.xsl\" type=\"text/xsl\"?>\n",
"<!-- Nmap 7.99 scan initiated Tue Aug 11 19:09:27 2026 as: nmap -oX out.xml -->\n",
);
fn options() -> ImportOptions<'static> {
ImportOptions::new(PortSet::try_from("80").unwrap())
}
fn read(input: &str) -> Result<Imported, ImportError> {
ImportFormat::NmapXml.read(&mut Cursor::new(input), &options())
}
#[test]
fn a_real_nmap_document_reads_as_its_hosts_and_ports() {
let document = format!(
"{REAL_PREAMBLE}{}",
concat!(
r#"<nmaprun scanner="nmap" args="nmap -oX out.xml 198.51.100.0/24" start="1786468167" version="7.99" xmloutputversion="1.05">"#,
"\n<scaninfo type=\"syn\" protocol=\"tcp\" numservices=\"1000\" services=\"1,3-4,6-7,9,13,17,19-26\"/>\n",
"<verbose level=\"0\"/>\n<debugging level=\"0\"/>\n",
"<host starttime=\"1\" endtime=\"2\">\n",
"<status state=\"up\" reason=\"echo-reply\" reason_ttl=\"64\"/>\n",
"<address addr=\"198.51.100.1\" addrtype=\"ipv4\"/>\n",
"<address addr=\"aa:bb:cc:dd:ee:ff\" addrtype=\"mac\" vendor=\"Arris\"/>\n",
"<hostnames>\n<hostname name=\"router.lan\" type=\"PTR\"/>\n</hostnames>\n",
"<ports>\n",
"<extraports state=\"closed\" count=\"998\"><extrareasons reason=\"resets\" count=\"998\"/></extraports>\n",
"<port protocol=\"tcp\" portid=\"22\"><state state=\"open\" reason=\"syn-ack\" reason_ttl=\"64\"/><service name=\"ssh\" product=\"OpenSSH\" method=\"probed\" conf=\"10\"/></port>\n",
"<port protocol=\"udp\" portid=\"53\"><state state=\"open\" reason=\"udp-response\"/></port>\n",
"</ports>\n<times srtt=\"39\" rttvar=\"5000\" to=\"100000\"/>\n</host>\n",
"<host><status state=\"up\" reason=\"conn-refused\"/><address addr=\"2001:db8::1\" addrtype=\"ipv6\"/></host>\n",
"<runstats><finished time=\"3\" elapsed=\"0.01\" exit=\"success\"/><hosts up=\"2\" down=\"0\" total=\"2\"/></runstats>\n",
"</nmaprun>\n",
)
);
let imported = read(&document).expect("a real nmap document reads");
assert_eq!(imported.addresses, 2, "one IPv4 host and one IPv6 host");
assert!(
imported
.map
.units
.iter()
.any(|unit| unit.ports().has_tcp(22) && unit.ports().has_udp(53)),
"the ports nmap found have to come back on the host it found them on"
);
assert!(
imported
.map
.units
.iter()
.any(|unit| unit.ports().has_tcp(80)),
"the host with no ports takes the caller's defaults"
);
}
#[test]
fn the_preamble_nmap_actually_writes_is_accepted() {
let document = format!(
"{REAL_PREAMBLE}<nmaprun><host><address addr=\"198.51.100.1\" addrtype=\"ipv4\"/></host></nmaprun>"
);
assert_eq!(read(&document).expect("accepted").addresses, 1);
}
#[test]
fn an_entity_declaration_is_refused_outright() {
let document = concat!(
r#"<?xml version="1.0"?>"#,
"\n<!DOCTYPE nmaprun [\n",
" <!ENTITY lol \"lol\">\n",
" <!ENTITY lol2 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n",
" <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">\n",
"]>\n",
r#"<nmaprun><host><address addr="&lol3;" addrtype="ipv4"/></host></nmaprun>"#,
);
let error = read(document).expect_err("an internal subset is refused");
let message = error.to_string();
assert!(
message.contains("internal subset"),
"the refusal has to say what it refused: {message}"
);
}
#[test]
fn an_external_entity_is_refused_at_the_doctype() {
for document in [
concat!(
r#"<!DOCTYPE nmaprun [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>"#,
r#"<nmaprun><host><address addr="&xxe;" addrtype="ipv4"/></host></nmaprun>"#,
),
concat!(
r#"<!DOCTYPE nmaprun SYSTEM "http://example.invalid/evil.dtd">"#,
r#"<nmaprun><host><address addr="198.51.100.1" addrtype="ipv4"/></host></nmaprun>"#,
),
concat!(
r#"<!DOCTYPE nmaprun PUBLIC "-//x//y" "http://example.invalid/evil.dtd">"#,
r#"<nmaprun><host><address addr="198.51.100.1" addrtype="ipv4"/></host></nmaprun>"#,
),
] {
let error = read(document).expect_err("refused");
assert!(matches!(error, ImportError::Malformed { .. }), "{error:?}");
}
}
#[test]
fn an_undeclared_entity_reference_is_refused_naming_it() {
let document =
r#"<nmaprun><host><address addr="&secret;" addrtype="ipv4"/></host></nmaprun>"#;
let message = read(document).expect_err("refused").to_string();
assert!(message.contains("secret"), "{message}");
}
#[test]
fn the_predefined_and_numeric_references_resolve() {
let document =
r#"<nmaprun><host><address addr="a&bA" addrtype="ipv4"/></host></nmaprun>"#;
let message = read(document)
.expect_err("'a&bA' is not an address")
.to_string();
assert!(
message.contains("a&bA"),
"the entity was not resolved: {message}"
);
}
#[test]
fn a_document_that_is_not_nmaps_is_refused() {
let message = read("<rss><channel><item/></channel></rss>")
.expect_err("not an nmap document")
.to_string();
assert!(message.contains("nmaprun"), "{message}");
}
#[test]
fn nesting_past_the_limit_is_refused() {
let deep = format!(
"<nmaprun>{}{}</nmaprun>",
"<a>".repeat(crate::import::xml::MAX_DEPTH + 8),
"</a>".repeat(crate::import::xml::MAX_DEPTH + 8)
);
let error = read(&deep).expect_err("refused");
assert!(error.to_string().contains("nested"), "{error}");
}
#[test]
fn an_element_past_the_byte_limit_is_refused() {
let options = options().with_limits(ImportLimits {
max_line_bytes: 256,
..ImportLimits::default()
});
let runaway = format!("<nmaprun><host attr=\"{}\"/></nmaprun>", "x".repeat(4096));
assert!(matches!(
ImportFormat::NmapXml.read(&mut Cursor::new(runaway), &options),
Err(ImportError::LineTooLong { .. })
));
}
#[test]
fn a_host_whose_addresses_times_its_ports_runs_away_is_refused() {
const SIDE: usize = 1025;
let addresses: String = (0..SIDE)
.map(|n| {
format!(
"<address addr=\"10.0.{}.{}\" addrtype=\"ipv4\"/>",
n / 256,
n % 256
)
})
.collect();
let ports: String = (1..=SIDE)
.map(|port| format!("<port protocol=\"tcp\" portid=\"{port}\"/>"))
.collect();
let document = format!("<nmaprun><host>{addresses}<ports>{ports}</ports></host></nmaprun>");
let error = read(&document).expect_err("a host past the expansion ceiling reads");
assert!(
error.to_string().contains("pairs"),
"the refusal should name what ran away, said: {error}"
);
}
#[test]
fn a_multi_homed_host_with_a_long_port_list_still_reads() {
let addresses = concat!(
"<address addr=\"198.51.100.1\" addrtype=\"ipv4\"/>",
"<address addr=\"198.51.100.2\" addrtype=\"ipv4\"/>",
"<address addr=\"2001:db8::1\" addrtype=\"ipv6\"/>",
);
let ports: String = (1..=4096)
.map(|port| format!("<port protocol=\"tcp\" portid=\"{port}\"/>"))
.collect();
let document = format!("<nmaprun><host>{addresses}<ports>{ports}</ports></host></nmaprun>");
assert_eq!(
read(&document).expect("reads").addresses,
3,
"three addresses, four thousand ports, well inside the ceiling"
);
}
#[test]
fn a_long_attribute_this_parser_ignores_is_not_a_problem() {
let services: String = (1..2000).map(|port| format!("{port},")).collect();
let document = format!(
"<nmaprun><scaninfo services=\"{services}\"/>\
<host><address addr=\"198.51.100.1\" addrtype=\"ipv4\"/></host></nmaprun>"
);
assert_eq!(read(&document).expect("reads").addresses, 1);
}
#[test]
fn an_unknown_transport_is_refused() {
let document = concat!(
r#"<nmaprun><host><address addr="198.51.100.1" addrtype="ipv4"/>"#,
r#"<ports><port protocol="dccp" portid="9"><state state="open"/></port></ports>"#,
r#"</host></nmaprun>"#,
);
let message = read(document).expect_err("refused").to_string();
assert!(message.contains("dccp"), "{message}");
}
#[test]
fn an_empty_document_is_refused_and_a_hostless_one_is_not() {
assert!(read("").is_err(), "nothing is not an nmap document");
let imported = read("<nmaprun><runstats/></nmaprun>").expect("a scan that found nothing");
assert_eq!(imported.tokens, 0);
assert!(imported.map.is_empty());
}
#[test]
#[ignore = "needs a real nmap file named by ZOND_NMAP_XML"]
fn a_file_nmap_itself_wrote() {
let path =
std::env::var("ZOND_NMAP_XML").expect("set ZOND_NMAP_XML to a file nmap produced");
let document = std::fs::read_to_string(&path).expect("the file is readable");
let imported = ImportFormat::NmapXml
.read(&mut Cursor::new(document), &options())
.expect("a file nmap wrote has to read");
println!(
"{path}: {} addresses, {} refused",
imported.addresses,
imported.refusals.len()
);
for unit in &imported.map.units {
let ports: Vec<String> = unit
.ports()
.iter()
.map(|(number, protocol)| format!("{number}/{protocol:?}"))
.collect();
println!(" {} addresses on {}", unit.ips().len(), ports.join(", "));
}
assert!(
imported.addresses > 0,
"a real scan's output produced no targets at all"
);
}
#[cfg(feature = "export-nmap")]
#[test]
fn a_document_this_engine_wrote_reads_back_as_its_own_targets() {
use crate::export::{ExportOptions, Exporter, NmapXmlExporter};
use std::collections::BTreeSet;
let report = crate::export::fixture::report();
let mut expected: BTreeSet<(String, u16)> = BTreeSet::new();
for host in report.hosts() {
for ip in host.ips() {
if host.port_count() == 0 {
expected.insert((ip.to_string(), 80));
continue;
}
for port in host.ports() {
expected.insert((ip.to_string(), port.number()));
}
}
}
let mut document = Vec::new();
NmapXmlExporter::new(ExportOptions::new())
.export(&report, &mut document)
.expect("the fixture exports");
let imported = ImportFormat::NmapXml
.read(&mut Cursor::new(document), &options())
.expect("this engine reads back what it wrote");
let mut found: BTreeSet<(String, u16)> = BTreeSet::new();
for target in imported.map.iter() {
found.insert((target.ip.to_string(), target.port));
}
assert_eq!(
found, expected,
"the hosts and ports the scan found are not the ones that came back"
);
assert!(
!expected.is_empty(),
"a fixture with no ports proves nothing"
);
}
}