use quick_xml::events::{BytesStart, Event};
use quick_xml::Reader;
use serde_json::{Map, Value};
pub fn parse_nmap_xml(input: &str) -> Result<Value, String> {
let mut reader = Reader::from_str(input);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut doc = Map::new();
let mut hosts: Vec<Value> = Vec::new();
let mut host: Option<HostAcc> = None;
let mut port: Option<PortAcc> = None;
let mut osmatch: Option<OsMatchAcc> = None;
let mut osclass: Option<Map<String, Value>> = None;
let mut runstats = Map::new();
let mut text: Option<String> = None;
loop {
match reader.read_event_into(&mut buf) {
Err(e) => return Err(format!("nmap XML parse error: {e}")),
Ok(Event::Eof) => break,
Ok(Event::Start(e)) => {
let name = e.name().as_ref().to_vec();
match name.as_slice() {
b"nmaprun" => {
attrs_into(&e, &mut doc)?;
}
b"host" => host = Some(HostAcc::default()),
b"port" => port = Some(PortAcc::from_attrs(&e)?),
b"service" => {
if let Some(p) = port.as_mut() {
p.service_attrs = Some(ServiceAcc::from_attrs(&e)?);
}
}
b"osmatch" => osmatch = Some(OsMatchAcc::from_attrs(&e)?),
b"osclass" => osclass = Some(attrs_map(&e)?),
b"script" => {
if let Some(p) = port.as_mut() {
let attrs = owned_attrs(&e)?;
p.scripts.push(parse_script(&mut reader, &mut buf, attrs)?);
}
}
_ => {}
}
}
Ok(Event::Empty(e)) => {
let name = e.name().as_ref().to_vec();
let m = attrs_map(&e)?;
match name.as_slice() {
b"status" => {
if let Some(h) = host.as_mut() {
h.status = Some(m);
}
}
b"address" => {
if let Some(h) = host.as_mut() {
h.addresses.push(m);
}
}
b"hostname" => {
if let Some(h) = host.as_mut() {
h.hostnames.push(m);
}
}
b"state" => {
if let Some(p) = port.as_mut() {
p.state = Some(m);
}
}
b"uptime" => {
if let Some(h) = host.as_mut() {
h.uptime = Some(m);
}
}
b"hop" => {
if let Some(h) = host.as_mut() {
h.traceroute.push(m);
}
}
b"extraports" => {
if let Some(h) = host.as_mut() {
h.extraports = Some(m);
}
}
b"service" => {
if let Some(p) = port.as_mut() {
p.service_attrs = Some(ServiceAcc::from_attrs(&e)?);
}
}
b"finished" => {
runstats.insert("finished".to_string(), Value::Object(m));
}
b"hosts" => {
runstats.insert("hosts".to_string(), Value::Object(m));
}
b"script" => {
if let Some(p) = port.as_mut() {
p.scripts.push(Value::Object(m));
}
}
_ => {}
}
}
Ok(Event::Text(t)) => {
text = Some(t.xml_content().map_err(|e| e.to_string())?.into_owned());
}
Ok(Event::End(e)) => {
let name = e.name().as_ref().to_vec();
match name.as_slice() {
b"host" => {
if let Some(h) = host.take() {
hosts.push(h.finish());
}
}
b"port" => {
if let Some(p) = port.take() {
if let Some(h) = host.as_mut() {
h.ports.push(p.finish());
}
}
}
b"osmatch" => {
if let Some(o) = osmatch.take() {
if let Some(h) = host.as_mut() {
h.os_matches.push(o.finish());
}
}
}
b"osclass" => {
if let Some(cls) = osclass.take() {
if let Some(o) = osmatch.as_mut() {
o.classes.push(Value::Object(cls));
}
}
}
b"cpe" => {
let t = text.take().unwrap_or_default();
if let Some(p) = port.as_mut() {
if let Some(s) = p.service_attrs.as_mut() {
s.cpes.push(t.clone());
}
}
if let Some(o) = osclass.as_mut() {
o.entry("cpe").or_insert_with(|| Value::Array(Vec::new()));
if let Some(Value::Array(arr)) = o.get_mut("cpe") {
arr.push(Value::String(t));
}
}
}
_ => {}
}
}
Ok(_) => {}
}
}
doc.insert("hosts".to_string(), Value::Array(hosts));
if !runstats.is_empty() {
doc.insert("runstats".to_string(), Value::Object(runstats));
}
Ok(Value::Object(doc))
}
fn parse_script(
reader: &mut Reader<&[u8]>,
buf: &mut Vec<u8>,
attrs: Vec<(Vec<u8>, String)>,
) -> Result<Value, String> {
let mut map = Map::new();
let mut id = None;
let mut output = None;
for (key, val) in attrs {
match key.as_slice() {
b"id" => id = Some(val),
b"output" => output = Some(val),
_ => {}
}
}
if let Some(id) = id {
map.insert("id".to_string(), Value::String(id));
}
if let Some(output) = output {
map.insert("output".to_string(), Value::String(output));
}
let bucket = parse_script_children(reader, buf)?;
let data = bucket.finish();
if !data.is_null() {
map.insert("data".to_string(), data);
}
Ok(Value::Object(map))
}
fn parse_script_children(
reader: &mut Reader<&[u8]>,
buf: &mut Vec<u8>,
) -> Result<ScriptBucket, String> {
let mut bucket = ScriptBucket::default();
loop {
match reader.read_event_into(buf) {
Ok(Event::Start(e)) => {
let name = e.name().as_ref().to_vec();
let key = key_attr(&e)?;
match name.as_slice() {
b"elem" => {
let value = read_text_until(reader, buf, b"elem")?;
bucket.insert(key, Value::String(value));
}
b"table" => {
let child = parse_script_children(reader, buf)?;
bucket.insert(key, child.finish());
}
_ => {
skip_until(reader, buf, &name)?;
}
}
}
Ok(Event::Empty(e)) => {
let name = e.name().as_ref().to_vec();
if name.as_slice() == b"elem" {
let key = key_attr(&e)?;
bucket.insert(key, Value::String(String::new()));
}
}
Ok(Event::End(e)) => {
let name = e.name().as_ref().to_vec();
if name.as_slice() == b"table" || name.as_slice() == b"script" {
break;
}
}
Ok(Event::Eof) => break,
Ok(_) => {}
Err(e) => return Err(format!("nmap XML parse error: {e}")),
}
}
Ok(bucket)
}
#[derive(Default)]
struct ScriptBucket {
map: Map<String, Value>,
list: Vec<Value>,
}
impl ScriptBucket {
fn insert(&mut self, key: Option<String>, value: Value) {
match key {
Some(k) => {
self.map.insert(k, value);
}
None => self.list.push(value),
}
}
fn finish(self) -> Value {
match (self.map.is_empty(), self.list.is_empty()) {
(true, true) => Value::Null,
(false, true) => Value::Object(self.map),
(true, false) => Value::Array(self.list),
(false, false) => {
let mut m = self.map;
m.insert("_list".to_string(), Value::Array(self.list));
Value::Object(m)
}
}
}
}
fn read_text_until(
reader: &mut Reader<&[u8]>,
buf: &mut Vec<u8>,
name: &[u8],
) -> Result<String, String> {
let mut out = String::new();
loop {
match reader.read_event_into(buf) {
Ok(Event::Text(t)) => {
out.push_str(&t.xml_content().map_err(|e| e.to_string())?);
}
Ok(Event::CData(t)) => {
out.push_str(&t.xml_content().map_err(|e| e.to_string())?);
}
Ok(Event::End(e)) if e.name().as_ref() == name => break,
Ok(Event::Eof) => break,
Ok(_) => {}
Err(e) => return Err(format!("nmap XML parse error: {e}")),
}
}
Ok(out)
}
fn skip_until(reader: &mut Reader<&[u8]>, buf: &mut Vec<u8>, name: &[u8]) -> Result<(), String> {
loop {
match reader.read_event_into(buf) {
Ok(Event::End(e)) if e.name().as_ref() == name => return Ok(()),
Ok(Event::Eof) => return Ok(()),
Ok(_) => {}
Err(e) => return Err(format!("nmap XML parse error: {e}")),
}
}
}
fn key_attr(e: &BytesStart<'_>) -> Result<Option<String>, String> {
for attr in e.attributes() {
let attr = attr.map_err(|err| format!("bad attribute: {err}"))?;
if attr.key.as_ref() == b"key" {
return Ok(Some(
attr.unescape_value()
.map_err(|err| err.to_string())?
.into_owned(),
));
}
}
Ok(None)
}
fn owned_attrs(e: &BytesStart<'_>) -> Result<Vec<(Vec<u8>, String)>, String> {
let mut out = Vec::new();
for attr in e.attributes() {
let attr = attr.map_err(|err| format!("bad attribute: {err}"))?;
let key = attr.key.as_ref().to_vec();
let val = attr.unescape_value().map_err(|err| err.to_string())?;
out.push((key, val.into_owned()));
}
Ok(out)
}
fn attrs_map(e: &BytesStart<'_>) -> Result<Map<String, Value>, String> {
let mut m = Map::new();
attrs_into(e, &mut m)?;
Ok(m)
}
fn attrs_into(e: &BytesStart<'_>, m: &mut Map<String, Value>) -> Result<(), String> {
for attr in e.attributes() {
let attr = attr.map_err(|err| format!("bad attribute: {err}"))?;
let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
let val = attr.unescape_value().map_err(|err| err.to_string())?;
m.insert(key, Value::String(val.into_owned()));
}
Ok(())
}
#[derive(Default)]
struct HostAcc {
status: Option<Map<String, Value>>,
addresses: Vec<Map<String, Value>>,
hostnames: Vec<Map<String, Value>>,
ports: Vec<Value>,
os_matches: Vec<Value>,
uptime: Option<Map<String, Value>>,
traceroute: Vec<Map<String, Value>>,
extraports: Option<Map<String, Value>>,
}
impl HostAcc {
fn finish(self) -> Value {
let mut m = Map::new();
if let Some(s) = self.status {
m.insert("status".to_string(), Value::Object(s));
}
if !self.addresses.is_empty() {
m.insert(
"addresses".to_string(),
Value::Array(self.addresses.into_iter().map(Value::Object).collect()),
);
}
if !self.hostnames.is_empty() {
m.insert(
"hostnames".to_string(),
Value::Array(self.hostnames.into_iter().map(Value::Object).collect()),
);
}
if !self.ports.is_empty() {
m.insert("ports".to_string(), Value::Array(self.ports));
}
if !self.os_matches.is_empty() {
m.insert("os_matches".to_string(), Value::Array(self.os_matches));
}
if let Some(u) = self.uptime {
m.insert("uptime".to_string(), Value::Object(u));
}
if !self.traceroute.is_empty() {
m.insert(
"traceroute".to_string(),
Value::Array(self.traceroute.into_iter().map(Value::Object).collect()),
);
}
if let Some(e) = self.extraports {
m.insert("extraports".to_string(), Value::Object(e));
}
Value::Object(m)
}
}
struct PortAcc {
protocol: Option<String>,
portid: Option<String>,
state: Option<Map<String, Value>>,
service_attrs: Option<ServiceAcc>,
scripts: Vec<Value>,
}
impl PortAcc {
fn from_attrs(e: &BytesStart<'_>) -> Result<Self, String> {
let m = attrs_map(e)?;
Ok(Self {
protocol: m
.get("protocol")
.and_then(|v| v.as_str())
.map(str::to_string),
portid: m.get("portid").and_then(|v| v.as_str()).map(str::to_string),
state: None,
service_attrs: None,
scripts: Vec::new(),
})
}
fn finish(mut self) -> Value {
let mut m = Map::new();
if let Some(p) = self.protocol {
m.insert("protocol".to_string(), Value::String(p));
}
if let Some(pid) = self.portid {
m.insert("portid".to_string(), Value::String(pid));
}
if let Some(s) = self.state {
m.insert("state".to_string(), Value::Object(s));
}
if let Some(s) = self.service_attrs.take() {
m.insert("service".to_string(), s.finish());
}
if !self.scripts.is_empty() {
m.insert("scripts".to_string(), Value::Array(self.scripts));
}
Value::Object(m)
}
}
struct ServiceAcc {
attrs: Map<String, Value>,
cpes: Vec<String>,
}
impl ServiceAcc {
fn from_attrs(e: &BytesStart<'_>) -> Result<Self, String> {
Ok(Self {
attrs: attrs_map(e)?,
cpes: Vec::new(),
})
}
fn finish(mut self) -> Value {
if !self.cpes.is_empty() {
self.attrs.insert(
"cpe".to_string(),
Value::Array(self.cpes.into_iter().map(Value::String).collect()),
);
}
Value::Object(self.attrs)
}
}
struct OsMatchAcc {
name: Option<String>,
accuracy: Option<String>,
classes: Vec<Value>,
}
impl OsMatchAcc {
fn from_attrs(e: &BytesStart<'_>) -> Result<Self, String> {
let m = attrs_map(e)?;
Ok(Self {
name: m.get("name").and_then(|v| v.as_str()).map(str::to_string),
accuracy: m
.get("accuracy")
.and_then(|v| v.as_str())
.map(str::to_string),
classes: Vec::new(),
})
}
fn finish(self) -> Value {
let mut m = Map::new();
if let Some(n) = self.name {
m.insert("name".to_string(), Value::String(n));
}
if let Some(a) = self.accuracy {
m.insert("accuracy".to_string(), Value::String(a));
}
if !self.classes.is_empty() {
m.insert("classes".to_string(), Value::Array(self.classes));
}
Value::Object(m)
}
}
#[cfg(test)]
mod tests {
use super::*;
const PORT_SCAN_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.95 scan initiated Sat Aug 8 21:20:04 2026 as: nmap -sT -p 22 -oX - 127.0.0.1 -->
<nmaprun scanner="nmap" args="nmap -sT -p 22 -oX - 127.0.0.1" start="1786216804" startstr="Sat Aug 8 21:20:04 2026" version="7.95" xmloutputversion="1.05">
<scaninfo type="connect" protocol="tcp" numservices="1" services="22"/>
<verbose level="0"/>
<debugging level="0"/>
<hosthint><status state="up" reason="unknown-response" reason_ttl="0"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<hostnames>
</hostnames>
</hosthint>
<host starttime="1786216804" endtime="1786216804"><status state="up" reason="conn-refused" reason_ttl="0"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<hostnames>
<hostname name="localhost" type="PTR"/>
</hostnames>
<ports><port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
</ports>
<times srtt="40" rttvar="2128" to="100000"/>
</host>
<runstats><finished time="1786216804" timestr="Sat Aug 8 21:20:04 2026" summary="Nmap done at Sat Aug 8 21:20:04 2026; 1 IP address (1 host up) scanned in 0.01 seconds" elapsed="0.01" exit="success"/><hosts up="1" down="0" total="1"/>
</runstats>
</nmaprun>"#;
#[test]
fn parses_host_and_port_scan() {
let v = parse_nmap_xml(PORT_SCAN_XML).expect("parses");
assert_eq!(v["version"], "7.95");
assert_eq!(v["scanner"], "nmap");
let hosts = v["hosts"].as_array().expect("hosts array");
assert_eq!(hosts.len(), 1);
let h = &hosts[0];
assert_eq!(h["status"]["state"], "up");
assert_eq!(h["addresses"][0]["addr"], "127.0.0.1");
assert_eq!(h["hostnames"][0]["name"], "localhost");
let port = &h["ports"][0];
assert_eq!(port["protocol"], "tcp");
assert_eq!(port["portid"], "22");
assert_eq!(port["state"]["state"], "open");
assert_eq!(port["service"]["name"], "ssh");
assert_eq!(port["service"]["method"], "table");
let rs = &v["runstats"];
assert_eq!(rs["hosts"]["up"], "1");
assert_eq!(rs["hosts"]["total"], "1");
assert_eq!(rs["finished"]["exit"], "success");
}
const NO_HOST_UP_XML: &str = r#"<nmaprun scanner="nmap" args="nmap -sn -oX - 10.0.0.99" start="1" version="7.95" xmloutputversion="1.05">
<scaninfo type="syn" protocol="tcp" numservices="0" services=""/>
<verbose level="0"/>
<debugging level="0"/>
<hosthint><status state="up" reason="unknown-response" reason_ttl="0"/>
<address addr="10.0.0.99" addrtype="ipv4"/>
<hostnames>
</hostnames>
</hosthint>
<runstats><finished time="1" timestr="" summary="Nmap done at ...; 1 IP address (0 hosts up) scanned in 0.01 seconds" elapsed="0.01" exit="success"/><hosts up="0" down="1" total="1"/>
</runstats>
</nmaprun>"#;
#[test]
fn parses_zero_hosts_up() {
let v = parse_nmap_xml(NO_HOST_UP_XML).expect("parses");
assert_eq!(v["hosts"].as_array().unwrap().len(), 0);
assert_eq!(v["runstats"]["hosts"]["up"], "0");
assert_eq!(v["runstats"]["hosts"]["down"], "1");
}
const SCRIPT_SCAN_XML: &str = r#"<nmaprun scanner="nmap" args="nmap -sT --script ssh-hostkey -p 22 -oX - 127.0.0.1" start="1" version="7.95" xmloutputversion="1.05">
<host><status state="up" reason="conn-refused"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="22"><state state="open" reason="syn-ack"/>
<service name="ssh" product="OpenSSH" version="9.2p1" method="probed" conf="10"><cpe>cpe:/a:openbsd:openssh:9.2p1</cpe></service>
<script id="ssh-hostkey" output="
 ssh-ed25519 SHA256:AAAA
 ssh-rsa SHA256:BBBB">
<table key="algorithm">
<elem key="type">ssh-ed25519</elem>
<elem key="bits">256</elem>
</table>
<table key="fingerprints">
<elem>SHA256:AAAA</elem>
<elem>SHA256:BBBB</elem>
</table>
</script>
<script id="ssh2-enum-algos"/>
</port>
</ports>
</host>
</nmaprun>"#;
#[test]
fn parses_service_version_cpe_and_script_structured_output() {
let v = parse_nmap_xml(SCRIPT_SCAN_XML).expect("parses");
let port = &v["hosts"][0]["ports"][0];
let svc = &port["service"];
assert_eq!(svc["name"], "ssh");
assert_eq!(svc["product"], "OpenSSH");
assert_eq!(svc["version"], "9.2p1");
assert_eq!(svc["method"], "probed");
assert_eq!(svc["cpe"][0], "cpe:/a:openbsd:openssh:9.2p1");
let scripts = port["scripts"].as_array().expect("scripts");
assert_eq!(scripts.len(), 2);
let hostkey = &scripts[0];
assert_eq!(hostkey["id"], "ssh-hostkey");
assert!(hostkey["output"].as_str().unwrap().contains("SHA256:AAAA"));
assert_eq!(hostkey["data"]["algorithm"]["type"], "ssh-ed25519");
assert_eq!(hostkey["data"]["algorithm"]["bits"], "256");
assert_eq!(hostkey["data"]["fingerprints"][0], "SHA256:AAAA");
assert_eq!(hostkey["data"]["fingerprints"][1], "SHA256:BBBB");
let empty = &scripts[1];
assert_eq!(empty["id"], "ssh2-enum-algos");
assert!(empty.get("data").is_none());
}
const OS_SCAN_XML: &str = r#"<nmaprun scanner="nmap" args="nmap -O -oX - 192.168.1.1" start="1" version="7.95" xmloutputversion="1.05">
<host><status state="up" reason="arp-response"/>
<address addr="192.168.1.1" addrtype="ipv4"/>
<address addr="AA:BB:CC:DD:EE:FF" addrtype="mac" vendor="Router Co"/>
<os>
<osmatch name="Linux 2.6.32 - 3.2" accuracy="100" line="123">
<osclass type="general purpose" vendor="Linux" osfamily="Linux" osgen="2.6.X" accuracy="100"><cpe>cpe:/o:linux:linux_kernel:2.6</cpe></osclass>
</osmatch>
</os>
<uptime seconds="12345" lastboot="Sat Aug 1 12:00:00 2026"/>
<traceroute>
<hop ttl="1" ipaddr="192.168.1.254" rtt="0.50"/>
<hop ttl="2" ipaddr="10.0.0.1" rtt="1.20"/>
</traceroute>
</host>
</nmaprun>"#;
#[test]
fn parses_os_detection_uptime_and_traceroute() {
let v = parse_nmap_xml(OS_SCAN_XML).expect("parses");
let h = &v["hosts"][0];
let m = &h["os_matches"][0];
assert_eq!(m["name"], "Linux 2.6.32 - 3.2");
assert_eq!(m["accuracy"], "100");
let cls = &m["classes"][0];
assert_eq!(cls["vendor"], "Linux");
assert_eq!(cls["osfamily"], "Linux");
assert_eq!(cls["osgen"], "2.6.X");
assert_eq!(cls["type"], "general purpose");
assert_eq!(cls["cpe"][0], "cpe:/o:linux:linux_kernel:2.6");
assert_eq!(h["uptime"]["seconds"], "12345");
assert_eq!(h["traceroute"][0]["ttl"], "1");
assert_eq!(h["traceroute"][1]["ipaddr"], "10.0.0.1");
}
#[test]
fn rejects_malformed_xml() {
let err = parse_nmap_xml("<nmaprun><host></nmaprun>").expect_err("bad xml");
assert!(err.contains("parse error") || err.contains("unexpected"));
}
#[test]
fn handles_entities_in_attributes_and_text() {
let xml = r#"<nmaprun scanner="nmap" args="a & b" version="7.95" xmloutputversion="1.05">
<host><status state="up" reason="conn-refused"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="80"><state state="open" reason="syn-ack"/>
<script id="http-title" output="
Title: A & B"></script>
</port>
</ports>
</host>
</nmaprun>"#;
let v = parse_nmap_xml(xml).expect("parses");
assert_eq!(v["args"], "a & b");
let script = &v["hosts"][0]["ports"][0]["scripts"][0];
assert!(script["output"].as_str().unwrap().contains("A & B"));
}
}