use std::fmt::{self, Write as _};
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::export::schema::{ENGINE_NAME, protocol_name, reference_text, severity_name};
use crate::export::{ExportError, ExportOptions, Exporter};
use crate::model::finding::Finding;
use crate::model::host::{Host, HostStatus, IpProtocolState};
use crate::model::port::{Port, PortState, Protocol};
use crate::model::technique::TcpScanTechnique;
use crate::report::{ScanPhase, ScanReport};
use crate::system::privilege::Privilege;
const XML_OUTPUT_VERSION: &str = "1.05";
#[must_use]
#[derive(Debug, Clone, Default)]
pub struct NmapXmlExporter {
options: ExportOptions,
}
impl NmapXmlExporter {
pub fn new(options: ExportOptions) -> Self {
Self { options }
}
pub fn options(&self) -> &ExportOptions {
&self.options
}
}
impl Exporter for NmapXmlExporter {
fn export(&self, report: &ScanReport, out: &mut dyn Write) -> Result<(), ExportError> {
let started = epoch_seconds(report.started_at());
let elapsed = report.elapsed().as_secs_f64();
writeln!(out, r#"<?xml version="1.0" encoding="UTF-8"?>"#)?;
write_exclusion_note(out, report)?;
writeln!(
out,
concat!(
r#"<nmaprun scanner="zond" args="" start="{}" startstr="{}" "#,
r#"version="{}" xmloutputversion="{}">"#
),
started,
Attr(&time_string(report.started_at())),
Attr(crate::report::ENGINE_VERSION),
XML_OUTPUT_VERSION,
)?;
for phase in report.phases() {
write_scan_info(out, phase)?;
}
writeln!(out, r#"<verbose level="0"/>"#)?;
writeln!(out, r#"<debugging level="0"/>"#)?;
for host in report.hosts() {
write_host(out, host, &self.options)?;
}
let summary = report.summary();
let finished = SystemTime::now();
writeln!(out, "<runstats>")?;
writeln!(
out,
r#"<finished time="{}" timestr="{}" elapsed="{:.2}" summary="{}" exit="{}"/>"#,
epoch_seconds(finished),
Attr(&time_string(finished)),
elapsed,
Attr(&format!(
"{ENGINE_NAME} done; {} IP addresses ({} hosts up) scanned in {elapsed:.2} seconds",
summary.hosts_total, summary.hosts_alive
)),
if report.is_partial() {
"error"
} else {
"success"
},
)?;
writeln!(
out,
r#"<hosts up="{}" down="{}" total="{}"/>"#,
summary.hosts_alive,
summary.hosts_total.saturating_sub(summary.hosts_alive),
summary.hosts_total,
)?;
writeln!(out, "</runstats>")?;
writeln!(out, "</nmaprun>")?;
Ok(())
}
}
fn write_exclusion_note(out: &mut dyn Write, report: &ScanReport) -> Result<(), ExportError> {
let mut excluded: Vec<String> = Vec::new();
for phase in report.phases() {
for range in phase.targets().excluded() {
let text = format!("{}-{}", range.start_addr(), range.end_addr());
if !excluded.contains(&text) {
excluded.push(text);
}
}
}
if excluded.is_empty() {
return Ok(());
}
writeln!(
out,
"<!-- zond: excluded by policy, not scanned: {} -->",
excluded.join(", ")
)?;
Ok(())
}
fn write_scan_info(out: &mut dyn Write, phase: &ScanPhase) -> Result<(), ExportError> {
let Some(ports) = phase.targets().ports().ports() else {
return Ok(());
};
for protocol in Protocol::ALL {
let ranges = ports.ranges(protocol);
if ranges.is_empty() {
continue;
}
let services = ranges
.iter()
.map(|range| {
if range.start() == range.end() {
range.start().to_string()
} else {
format!("{}-{}", range.start(), range.end())
}
})
.collect::<Vec<_>>()
.join(",");
writeln!(
out,
r#"<scaninfo type="{}" protocol="{}" numservices="{}" services="{}"/>"#,
scan_type(phase, protocol),
protocol_name(protocol),
ports.len_on(protocol),
Attr(&services),
)?;
}
Ok(())
}
fn scan_type(phase: &ScanPhase, protocol: Protocol) -> &'static str {
match protocol {
Protocol::Udp => return "udp",
Protocol::Sctp => return "sctpinit",
Protocol::Tcp => {}
}
if phase.privilege() == Some(Privilege::Connect) {
return "connect";
}
match phase.settings().tcp_technique {
TcpScanTechnique::Syn => "syn",
TcpScanTechnique::Fin => "fin",
TcpScanTechnique::Null => "null",
TcpScanTechnique::Xmas => "xmas",
TcpScanTechnique::Maimon => "maimon",
TcpScanTechnique::Ack => "ack",
TcpScanTechnique::Window => "window",
}
}
fn write_host(
out: &mut dyn Write,
host: &Host,
options: &ExportOptions,
) -> Result<(), ExportError> {
let redaction = options.redaction;
writeln!(
out,
r#"<host starttime="{}" endtime="{}">"#,
epoch_seconds(host.first_seen()),
epoch_seconds(host.last_seen()),
)?;
writeln!(
out,
r#"<status state="{}" reason="{}" reason_ttl="{}"/>"#,
host_state(host.status()),
Attr(status_reason(host.status())),
0,
)?;
let primary = host.primary_ip();
let addresses = std::iter::once(&primary).chain(host.ips().iter().filter(|ip| **ip != primary));
for ip in addresses {
writeln!(
out,
r#"<address addr="{}" addrtype="{}"/>"#,
Attr(&ip.to_string()),
if ip.is_ipv4() { "ipv4" } else { "ipv6" },
)?;
}
if let Some(mac) = host.mac() {
match host.vendor() {
Some(vendor) => writeln!(
out,
r#"<address addr="{}" addrtype="mac" vendor="{}"/>"#,
Attr(&redaction.mac(&mac)),
Attr(vendor),
)?,
None => writeln!(
out,
r#"<address addr="{}" addrtype="mac"/>"#,
Attr(&redaction.mac(&mac)),
)?,
}
}
if let Some(hostname) = host.hostname() {
writeln!(out, "<hostnames>")?;
writeln!(
out,
r#"<hostname name="{}" type="PTR"/>"#,
Attr(&redaction.hostname(hostname)),
)?;
writeln!(out, "</hostnames>")?;
}
write_ip_protocols(out, host)?;
let mut probed = host
.ports()
.filter(|port| port_state(port.state()).is_some());
if let Some(first) = probed.next() {
writeln!(out, "<ports>")?;
write_port(out, first)?;
for port in probed {
write_port(out, port)?;
}
writeln!(out, "</ports>")?;
}
if let Some(os) = host.os() {
writeln!(out, "<os>")?;
writeln!(
out,
r#"<osmatch name="{}" accuracy="{}" line="0"/>"#,
Attr(os.name()),
os.accuracy(),
)?;
writeln!(out, "</os>")?;
}
if let Some(distance) = host.path().length() {
writeln!(out, r#"<distance value="{distance}"/>"#)?;
}
if host.findings().next().is_some() {
writeln!(out, "<hostscript>")?;
write_finding_scripts(out, host.findings())?;
writeln!(out, "</hostscript>")?;
}
write_trace(out, host)?;
if let Some(rtt) = host.median_rtt() {
writeln!(
out,
r#"<times srtt="{}" rttvar="0" to="{}"/>"#,
rtt.as_micros(),
rtt.as_micros(),
)?;
}
writeln!(out, "</host>")?;
Ok(())
}
fn write_trace(out: &mut dyn Write, host: &Host) -> Result<(), ExportError> {
let hops = host.path().hops();
if hops.is_empty() {
return Ok(());
}
writeln!(out, "<trace>")?;
for hop in hops {
write!(out, r#"<hop ttl="{}""#, hop.distance())?;
if let Some(address) = hop.address() {
write!(out, r#" ipaddr="{}""#, Attr(&address.to_string()))?;
}
if let Some(rtt) = hop.rtt() {
write!(out, r#" rtt="{:.2}""#, rtt.as_secs_f64() * 1000.0)?;
}
writeln!(out, "/>")?;
}
writeln!(out, "</trace>")?;
Ok(())
}
fn finding_output(finding: &Finding) -> String {
let mut parts = vec![format!(
"[{}] {}",
severity_name(finding.severity()),
finding.title()
)];
let references: Vec<String> = finding.references().map(reference_text).collect();
if !references.is_empty() {
parts.push(references.join(", "));
}
if !finding.excerpt().is_empty() {
parts.push(finding.excerpt().as_str().to_owned());
}
if let Some(remediation) = finding.remediation() {
parts.push(format!("fix: {remediation}"));
}
parts.join(" | ")
}
fn write_finding_scripts<'a>(
out: &mut dyn Write,
findings: impl Iterator<Item = &'a Finding>,
) -> Result<(), ExportError> {
for finding in findings {
writeln!(
out,
r#"<script id="{}" output="{}"/>"#,
Attr(finding.detection().id()),
Attr(&finding_output(finding)),
)?;
}
Ok(())
}
fn write_ip_protocols(out: &mut dyn Write, host: &Host) -> Result<(), ExportError> {
let mut asked = host
.ip_protocols()
.iter()
.filter(|(_, state)| state.is_established());
let Some(first) = asked.next() else {
return Ok(());
};
writeln!(out, "<ports>")?;
for (number, state) in std::iter::once(first).chain(asked) {
writeln!(out, r#"<port protocol="ip" portid="{number}">"#)?;
writeln!(
out,
r#"<state state="{}" reason="{}" reason_ttl="0"/>"#,
ip_protocol_state(*state),
Attr(ip_protocol_reason(*state)),
)?;
if let Some(name) = crate::model::host::ip_protocol_name(*number) {
writeln!(
out,
r#"<service name="{}" method="table" conf="3"/>"#,
Attr(name),
)?;
}
writeln!(out, "</port>")?;
}
writeln!(out, "</ports>")?;
Ok(())
}
fn ip_protocol_state(state: IpProtocolState) -> &'static str {
match state {
IpProtocolState::Open => "open",
IpProtocolState::Closed => "closed",
IpProtocolState::Filtered => "filtered",
IpProtocolState::OpenFiltered => "open|filtered",
IpProtocolState::Unasked => "open|filtered",
}
}
fn ip_protocol_reason(state: IpProtocolState) -> &'static str {
match state {
IpProtocolState::Closed => "proto-unreach",
IpProtocolState::Filtered => "admin-prohibited",
IpProtocolState::Open => "response",
IpProtocolState::OpenFiltered | IpProtocolState::Unasked => "no-response",
}
}
fn write_port(out: &mut dyn Write, port: &Port) -> Result<(), ExportError> {
let (Some(state), Some(reason)) = (port_state(port.state()), port_reason(port.state())) else {
return Ok(());
};
writeln!(
out,
r#"<port protocol="{}" portid="{}">"#,
transport(port.protocol()),
port.number(),
)?;
writeln!(
out,
r#"<state state="{}" reason="{}" reason_ttl="0"/>"#,
state,
Attr(reason),
)?;
if let Some(service) = port.service() {
write!(out, r#"<service name="{}""#, Attr(service.name()))?;
if let Some(product) = service.product() {
write!(out, r#" product="{}""#, Attr(product))?;
}
if let Some(version) = service.version() {
write!(out, r#" version="{}""#, Attr(version))?;
}
if let Some(extrainfo) = service.extrainfo() {
write!(out, r#" extrainfo="{}""#, Attr(extrainfo))?;
}
writeln!(
out,
r#" method="{}" conf="{}"/>"#,
if service.is_inferred() {
"table"
} else {
"probed"
},
nmap_confidence(service.confidence()),
)?;
}
write_finding_scripts(out, port.findings())?;
writeln!(out, "</port>")?;
Ok(())
}
fn port_state(state: PortState) -> Option<&'static str> {
Some(match state {
PortState::Open => "open",
PortState::Closed => "closed",
PortState::Filtered => "filtered",
PortState::Unfiltered => "unfiltered",
PortState::OpenFiltered => "open|filtered",
PortState::ClosedFiltered => "closed|filtered",
PortState::Unasked => return None,
})
}
fn port_reason(state: PortState) -> Option<&'static str> {
Some(match state {
PortState::Open => "syn-ack",
PortState::Closed => "reset",
PortState::Filtered
| PortState::Unfiltered
| PortState::OpenFiltered
| PortState::ClosedFiltered => "no-response",
PortState::Unasked => return None,
})
}
fn host_state(status: HostStatus) -> &'static str {
match status {
HostStatus::Up | HostStatus::Filtered => "up",
HostStatus::Down => "down",
HostStatus::Unknown => "unknown",
}
}
fn status_reason(status: HostStatus) -> &'static str {
match status {
HostStatus::Up => "echo-reply",
HostStatus::Filtered => "probes-filtered",
HostStatus::Down => "no-response",
HostStatus::Unknown => "unknown-response",
}
}
fn transport(protocol: Protocol) -> &'static str {
match protocol {
Protocol::Tcp => "tcp",
Protocol::Udp => "udp",
Protocol::Sctp => "sctp",
}
}
fn nmap_confidence(confidence: u8) -> u8 {
if confidence == 0 {
return TABLE_CONFIDENCE;
}
(u16::from(confidence).saturating_mul(10) / 100).clamp(1, 10) as u8
}
const TABLE_CONFIDENCE: u8 = 3;
fn epoch_seconds(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH)
.map(|since| since.as_secs())
.unwrap_or(0)
}
fn time_string(time: SystemTime) -> String {
crate::format::time::rfc3339(time)
}
struct Attr<'a>(&'a str);
impl fmt::Display for Attr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for character in self.0.chars() {
match character {
'&' => f.write_str("&")?,
'<' => f.write_str("<")?,
'>' => f.write_str(">")?,
'"' => f.write_str(""")?,
'\'' => f.write_str("'")?,
character if is_forbidden(character) => {}
character => f.write_char(character)?,
}
}
Ok(())
}
}
fn is_forbidden(character: char) -> bool {
let code = u32::from(character);
let control = matches!(code, 0x00..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F);
let noncharacter = matches!(code, 0xFFFE | 0xFFFF);
let bidirectional = matches!(code, 0x202A..=0x202E | 0x2066..=0x2069 | 0x200E | 0x200F);
control || noncharacter || bidirectional
}
#[cfg(test)]
mod tests {
use super::*;
use crate::export::fixture;
fn render() -> String {
let mut out = Vec::new();
NmapXmlExporter::new(ExportOptions::new())
.export(&fixture::report(), &mut out)
.expect("the fixture exports");
String::from_utf8(out).expect("the document is UTF-8")
}
fn export(hosts: &[Host]) -> String {
let report = ScanReport::recorded("zond", Vec::new(), hosts.to_vec());
let mut out = Vec::new();
NmapXmlExporter::new(ExportOptions::new())
.export(&report, &mut out)
.expect("the report exports");
String::from_utf8(out).expect("the document is UTF-8")
}
#[test]
fn the_document_is_in_nmaps_shape() {
let document = render();
assert!(document.starts_with(r#"<?xml version="1.0" encoding="UTF-8"?>"#));
assert!(document.contains(r#"<nmaprun scanner="zond""#));
assert!(document.contains(&format!(r#"xmloutputversion="{XML_OUTPUT_VERSION}""#)));
assert!(document.contains("<host "));
assert!(document.contains("<ports>"));
assert!(document.contains("<runstats>"));
assert!(document.trim_end().ends_with("</nmaprun>"));
}
#[test]
fn the_document_never_claims_to_be_nmap() {
let document = render();
assert!(
document.contains(r#"scanner="zond""#),
"the document must say who wrote it"
);
assert!(
!document.contains(r#"scanner="nmap""#),
"the document must never claim to be nmap's output"
);
}
#[test]
fn every_port_state_a_probe_reaches_maps_to_a_state_nmap_defines() {
const NMAP_STATES: [&str; 6] = [
"open",
"closed",
"filtered",
"unfiltered",
"open|filtered",
"closed|filtered",
];
for state in PortState::ALL {
let Some(name) = port_state(state) else {
assert_eq!(
state,
PortState::Unasked,
"{state:?} has no name in nmap's vocabulary and is not the \
one state that has none"
);
continue;
};
assert!(
NMAP_STATES.contains(&name),
"{state:?} maps to '{name}', which nmap does not define"
);
}
}
#[test]
fn a_protocol_verdict_is_written_as_nmap_writes_one_and_reads_back_as_one() {
use crate::import::report::ReportReader;
use crate::import::report::nmap::NmapXmlReportReader;
use crate::model::host::IpProtocolState;
use std::net::{IpAddr, Ipv4Addr};
let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 11)));
host.set_status(HostStatus::Up);
host.record_ip_protocol(47, IpProtocolState::Open);
host.record_ip_protocol(89, IpProtocolState::Closed);
host.record_ip_protocol(103, IpProtocolState::Unasked);
let document = export(&[host]);
assert!(
document.contains(r#"<port protocol="ip" portid="47">"#),
"{document}"
);
assert!(document.contains(r#"<service name="gre""#), "{document}");
assert!(
!document.contains(r#"portid="103""#),
"a protocol nobody reached was written down anyway"
);
let restored = NmapXmlReportReader::default()
.read(&mut std::io::Cursor::new(document.into_bytes()))
.expect("this crate's own document reads back");
let restored = restored.hosts().next().expect("the host survived");
assert_eq!(
restored.ip_protocols().get(&47),
Some(&IpProtocolState::Open)
);
assert_eq!(
restored.ip_protocols().get(&89),
Some(&IpProtocolState::Closed)
);
assert_eq!(
restored.port_count(),
0,
"a protocol came back as a port, which is the one reading that must not happen"
);
}
#[test]
fn a_port_nobody_asked_about_is_left_out_of_the_document() {
use std::net::{IpAddr, Ipv4Addr};
let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 9)));
host.set_status(HostStatus::Up);
host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
host.add_port(Port::new(23, Protocol::Tcp, PortState::Unasked));
let document = export(&[host]);
assert!(
document.contains(r#"portid="22""#),
"the probed port is missing"
);
assert!(
!document.contains(r#"portid="23""#),
"a port nobody asked about was written down anyway"
);
}
#[test]
fn a_host_with_nothing_probed_writes_no_ports_element() {
use std::net::{IpAddr, Ipv4Addr};
let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 10)));
host.set_status(HostStatus::Up);
host.add_port(Port::new(80, Protocol::Tcp, PortState::Unasked));
assert!(!export(&[host]).contains("<ports>"));
}
#[cfg(feature = "import-nmap")]
#[test]
fn a_multi_homed_host_keeps_the_address_it_is_keyed_by() {
use crate::import::report::ReportReader;
use crate::import::report::nmap::NmapXmlReportReader;
use std::net::{IpAddr, Ipv4Addr};
let keyed = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 10));
let lower = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 4));
let mut host = Host::new(keyed);
host.add_ip(lower);
assert_eq!(
host.primary_ip(),
keyed,
"two addresses of one family rank alike, so the first seen leads"
);
let report = ScanReport::recorded("zond", Vec::new(), [host]);
let mut document = Vec::new();
NmapXmlExporter::new(ExportOptions::new())
.export(&report, &mut document)
.expect("the report exports");
let restored = NmapXmlReportReader::default()
.read(&mut std::io::Cursor::new(document))
.expect("this crate's own document reads back");
let host = restored.hosts().next().expect("the host survived");
assert_eq!(
host.primary_ip(),
keyed,
"the round trip re-keyed the host onto its other address"
);
assert!(host.ips().contains(&lower), "and kept the other one");
}
#[test]
fn a_filtered_host_is_exported_as_up_because_that_is_what_it_is() {
assert_eq!(host_state(HostStatus::Filtered), "up");
assert_eq!(host_state(HostStatus::Up), "up");
assert_eq!(host_state(HostStatus::Down), "down");
assert_eq!(host_state(HostStatus::Unknown), "unknown");
}
#[test]
fn the_five_meaningful_characters_are_escaped() {
let escaped = Attr(r#"<a href="x">&'</a>"#).to_string();
assert_eq!(escaped, "<a href="x">&'</a>");
}
#[test]
fn characters_xml_cannot_carry_are_dropped_rather_than_referenced() {
let banner = "OpenSSH\u{0}\u{1}\u{1f} 9.6\u{202e}drowssap";
let escaped = Attr(banner).to_string();
assert_eq!(escaped, "OpenSSH 9.6drowssap");
assert!(!escaped.contains('&'), "no reference was invented for them");
assert_eq!(Attr("a\tb\nc\rd").to_string(), "a\tb\nc\rd");
}
#[test]
fn required_attributes_the_dtd_demands_are_present() {
let document = render();
for required in [
r#"<nmaprun scanner="#,
r#" version="#,
r#" xmloutputversion="#,
r#"<status state="#,
r#" reason="#,
r#"<address addr="#,
r#" addrtype="#,
r#"<port protocol="#,
r#" portid="#,
r#"<hosts up="#,
] {
assert!(
document.contains(required),
"the document is missing {required:?}, which the DTD requires"
);
}
if document.contains("<osmatch ") {
assert!(document.contains(r#" line="0"/>"#));
}
}
#[test]
fn a_report_with_no_ports_still_produces_a_whole_document() {
let document = render();
assert!(
document.contains(r#"<host starttime="#),
"the fixture's portless host is missing"
);
assert!(document.contains("</nmaprun>"));
let portless = document
.split("<host ")
.skip(1)
.find(|section| !section.contains("<ports>"))
.expect("the fixture has a host with no ports");
assert!(portless.contains("<status state="));
}
#[test]
fn redaction_applies_to_this_format_like_any_other() {
let mut out = Vec::new();
NmapXmlExporter::new(
ExportOptions::new().with_redaction(crate::export::Redaction::Standard),
)
.export(&fixture::report(), &mut out)
.expect("exports");
let document = String::from_utf8(out).expect("UTF-8");
assert!(
document.contains(r#"addrtype="mac""#),
"the fixture has a hardware address to mask"
);
assert!(
!document.contains("2c:cf:67:00:00:01"),
"an unmasked hardware address survived redaction"
);
assert!(
document.contains("2c:cf:67:XX:XX:XX"),
"the vendor half has to survive, which is the point of the policy"
);
}
#[test]
fn service_confidence_lands_on_nmaps_scale() {
assert_eq!(nmap_confidence(100), 10);
assert_eq!(nmap_confidence(85), 8);
assert_eq!(nmap_confidence(50), 5);
assert_eq!(nmap_confidence(255), 10, "and stops at 10");
assert_eq!(
nmap_confidence(0),
TABLE_CONFIDENCE,
"a port-number lookup is what nmap spells 3, not the weakest identification"
);
}
#[test]
fn a_port_number_label_is_written_as_the_lookup_it_is() {
use crate::model::port::{Port, PortState, Protocol, Service};
let mut out = Vec::new();
write_port(
&mut out,
&Port::new(80, Protocol::Tcp, PortState::Closed).with_service(Service::new("http", 0)),
)
.expect("writing to a vector");
let inferred = String::from_utf8(out).expect("UTF-8");
assert!(inferred.contains(r#"method="table""#), "{inferred}");
let mut out = Vec::new();
write_port(
&mut out,
&Port::new(80, Protocol::Tcp, PortState::Open).with_service(Service::new("http", 100)),
)
.expect("writing to a vector");
let probed = String::from_utf8(out).expect("UTF-8");
assert!(probed.contains(r#"method="probed""#), "{probed}");
}
#[test]
fn no_field_of_a_hostile_report_reaches_the_document_unescaped() {
let mut out = Vec::new();
NmapXmlExporter::new(ExportOptions::new())
.export(&fixture::hostile(), &mut out)
.expect("the document renders");
let document = String::from_utf8(out).expect("utf-8");
assert!(
document.contains("<script>"),
"the payload should be present, escaped - otherwise this proves \
nothing about a document that simply dropped it"
);
assert!(
!document.contains("<script>"),
"a scanned host's banner opened an element in the report"
);
assert!(
!document.contains(fixture::HOSTILE),
"the payload survived intact somewhere in the document"
);
}
}