eggsec-nse 0.3.0

Standalone Lua-based Nmap Scripting Engine runtime
Documentation
//! NSE output formatting module
//!
//! Provides various output format handlers compatible with nmap conventions.

use serde::{Deserialize, Serialize};
use std::fmt::Write as FmtWrite;

/// `writeln!` for infallible `String` buffers.
///
/// `fmt::Write for String` fails only on allocator OOM, so the result is
/// debug-asserted rather than panicked on (`.unwrap()`) or silently
/// discarded (`let _ =`).
macro_rules! writeln_checked {
    ($dst:expr) => {{
        let result: std::fmt::Result = writeln!($dst);
        debug_assert!(
            result.is_ok(),
            "writing to a String buffer is infallible"
        );
    }};
    ($dst:expr, $($arg:tt)*) => {{
        let result: std::fmt::Result = writeln!($dst, $($arg)*);
        debug_assert!(
            result.is_ok(),
            "writing to a String buffer is infallible"
        );
    }};
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseOutput {
    pub target: String,
    pub scripts: String,
    pub output: String,
    pub ports: Option<String>,
    pub timing: u8,
    pub debug: u8,
}

#[derive(Debug, Clone)]
pub enum OutputFormat {
    Stdout,
    Xml(String),
    Grepable(String),
    Normal(String),
    All,
}

/// Generate XML output in nmap format
pub fn generate_xml(results: &[NseOutput]) -> String {
    let mut xml = String::new();

    writeln_checked!(xml, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    writeln_checked!(
        xml,
        "<nmaprun scanner=\"eggsec\" args=\"eggsec nse\" start=\"{}\" version=\"1.0\">",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    );

    writeln_checked!(xml, "  <verbose level=\"0\"/>");
    writeln_checked!(xml, "  <debugging level=\"0\"/>");

    for result in results {
        writeln_checked!(
            xml,
            "  <host starttime=\"{}\" endtime=\"{}\">",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
                + 1
        );

        writeln_checked!(xml, "    <status state=\"up\" reason=\"echo-reply\"/>");
        writeln_checked!(
            xml,
            "    <address addr=\"{}\" addrtype=\"ipv4\"/>",
            escape_xml(&result.target)
        );

        writeln_checked!(xml, "    <hostnames>");
        writeln_checked!(
            xml,
            "      <hostname name=\"{}\" type=\"user\"/>",
            escape_xml(&result.target)
        );
        writeln_checked!(xml, "    </hostnames>");

        writeln_checked!(xml, "    <ports>");
        let port_line = result.ports.as_deref().unwrap_or("80/tcp   open  http");
        let port_id = port_line.split('/').next().unwrap_or("80");
        writeln_checked!(xml, "      <port protocol=\"tcp\" portid=\"{}\">", port_id);
        writeln_checked!(xml, "        <state state=\"open\" reason=\"syn-ack\"/>");
        writeln_checked!(
            xml,
            "        <service name=\"http\" method=\"probed\" conf=\"10\"/>"
        );
        writeln_checked!(
            xml,
            "        <script id=\"{}\" output=\"{}\">",
            escape_xml(&result.scripts),
            escape_xml(&result.output)
        );
        writeln_checked!(xml, "        </script>");
        writeln_checked!(xml, "      </port>");
        writeln_checked!(xml, "    </ports>");

        writeln_checked!(xml, "    <times srtt=\"0\" rttvar=\"0\" to=\"100000\"/>");
        writeln_checked!(xml, "  </host>");
    }

    writeln_checked!(xml, "  <runstats>");
    writeln_checked!(xml, "    <finished elapsed=\"1\" exit=\"success\"/>");
    writeln_checked!(
        xml,
        "    <hosts up=\"{}\" down=\"0\" total=\"{}\"/>",
        results.len(),
        results.len()
    );
    writeln_checked!(xml, "  </runstats>");
    writeln_checked!(xml, "</nmaprun>");

    xml
}

/// Generate grepable output in nmap -oG format
pub fn generate_grepable(results: &[NseOutput]) -> String {
    let mut output = String::new();

    writeln_checked!(output, "# Nmap scan report generated by Eggsec");

    for result in results {
        writeln_checked!(output, "Host: {} () Status: Up", result.target);
        let ports_str = result.ports.as_deref().unwrap_or("80/open/tcp//http///");
        writeln_checked!(
            output,
            "Host: {} ()     Ports: {}",
            result.target,
            ports_str
        );

        let script_output = result.output.replace('\n', "\\n");
        writeln_checked!(output, "| {}: {}", result.scripts, script_output);
    }

    writeln_checked!(
        output,
        "# Scan done: {} IP address (1 host up) scanned in 0.01 seconds",
        results.len()
    );

    output
}

/// Generate normal output in nmap format
pub fn generate_normal(results: &[NseOutput]) -> String {
    let mut output = String::new();

    writeln_checked!(
        output,
        "Starting Eggsec NSE scan at {}",
        chrono_lite_timestamp()
    );
    writeln_checked!(
        output,
        "NSE Timing: About {}% done",
        (results.len() as f32 * 33.0).min(100.0)
    );
    writeln_checked!(output);

    for result in results {
        writeln_checked!(output, "Nmap scan report for {}", result.target);
        writeln_checked!(output, "Host is up (0.0010s latency).");
        writeln_checked!(output, "PORT     STATE SERVICE");
        let _ports_result = write_ports(&mut output, result.ports.as_deref());
        debug_assert!(
            _ports_result.is_ok(),
            "writing to a String buffer is infallible"
        );

        writeln_checked!(output, "| {}:", result.scripts);
        for line in result.output.lines() {
            writeln_checked!(output, "|   {}", line);
        }

        writeln_checked!(output);
    }

    writeln_checked!(
        output,
        "Nmap done: {} IP address ({} host up) scanned",
        results.len(),
        results.len()
    );

    output
}

fn write_ports(output: &mut String, ports: Option<&str>) -> std::fmt::Result {
    match ports {
        Some(ports) => {
            for raw in ports.lines().map(str::trim).filter(|line| !line.is_empty()) {
                if raw.contains('/') {
                    writeln!(output, "{}", raw)?;
                } else {
                    writeln!(output, "{}/tcp   open  unknown", raw)?;
                }
            }
        }
        None => {
            writeln!(output, "80/tcp   open  http")?;
        }
    }
    Ok(())
}

fn escape_xml(s: &str) -> String {
    let mut escaped = String::new();
    for c in s.chars() {
        match c {
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '&' => escaped.push_str("&amp;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            _ => escaped.push(c),
        }
    }
    escaped
}

fn chrono_lite_timestamp() -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    format!("{}", now.as_secs())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_xml_output() {
        let results = vec![NseOutput {
            target: "example.com".to_string(),
            scripts: "http-title".to_string(),
            output: "Example Domain".to_string(),
            ports: Some("80".to_string()),
            timing: 3,
            debug: 0,
        }];

        let xml = generate_xml(&results);
        assert!(xml.contains("<?xml"));
        assert!(xml.contains("example.com"));
    }

    #[test]
    fn test_xml_output_escapes_target() {
        // Regression test: attacker-influenced targets must not break XML
        // structure or inject attributes.
        let results = vec![NseOutput {
            target: "example.com\"/><injected>&".to_string(),
            scripts: "http-title".to_string(),
            output: "Example Domain".to_string(),
            ports: Some("80".to_string()),
            timing: 3,
            debug: 0,
        }];

        let xml = generate_xml(&results);
        assert!(!xml.contains("<injected>"));
        assert!(xml.contains("example.com&quot;/&gt;&lt;injected&gt;&amp;"));
    }

    #[test]
    fn test_grepable_output() {
        let results = vec![NseOutput {
            target: "example.com".to_string(),
            scripts: "http-title".to_string(),
            output: "Example Domain".to_string(),
            ports: Some("80".to_string()),
            timing: 3,
            debug: 0,
        }];

        let grepable = generate_grepable(&results);
        assert!(grepable.contains("example.com"));
    }

    #[test]
    fn test_normal_output() {
        let results = vec![NseOutput {
            target: "example.com".to_string(),
            scripts: "http-title".to_string(),
            output: "Example Domain".to_string(),
            ports: Some("80".to_string()),
            timing: 3,
            debug: 0,
        }];

        let normal = generate_normal(&results);
        assert!(normal.contains("example.com"));
    }

    #[test]
    fn test_normal_output_uses_ports_field() {
        let results = vec![NseOutput {
            target: "example.com".to_string(),
            scripts: "http-title".to_string(),
            output: "Example Domain".to_string(),
            ports: Some("443/tcp   open  https".to_string()),
            timing: 3,
            debug: 0,
        }];

        let normal = generate_normal(&results);
        assert!(normal.contains("443/tcp   open  https"));
        assert!(!normal.contains("80/tcp   open  http"));
    }
}