nmap-mcp 0.1.0

Nmap network scanner and NSE scripting engine control for AI assistants via MCP
//! Execution wrapper around the nmap binary.
//!
//! The runner locates nmap (env `NMAP_MCP_BIN` override, then `PATH`), runs
//! it with explicit argument arrays (never a shell, so target strings cannot
//! inject commands), enforces a per-scan timeout, and parses `-oX -` XML
//! output into JSON via [`crate::nmap_xml`].
//!
//! Test hooks:
//! - `NMAP_MCP_BIN` — path to the nmap executable (tests point this at a
//!   fixture shim or a locally installed real nmap).
//! - `NMAP_MCP_SCRIPT_DB` — path to script.db (tests point this at a fixture).

use std::env;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use serde_json::Value;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;

use crate::nmap_xml;

/// Outcome of running nmap: exit status plus captured streams.
#[derive(Debug)]
pub struct RunOutput {
    /// Process exit code, if the process exited normally.
    pub exit_code: Option<i32>,
    /// Captured stdout.
    pub stdout: String,
    /// Captured stderr.
    pub stderr: String,
}

/// Wraps a resolved nmap executable path.
#[derive(Debug, Clone)]
pub struct NmapRunner {
    bin: PathBuf,
}

impl Default for NmapRunner {
    fn default() -> Self {
        Self::new()
    }
}

impl NmapRunner {
    /// Resolve the nmap executable: `NMAP_MCP_BIN` env override first, then
    /// `nmap` from `PATH`.
    pub fn new() -> Self {
        let bin = env::var("NMAP_MCP_BIN")
            .ok()
            .filter(|p| !p.is_empty())
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("nmap"));
        Self { bin }
    }

    /// The resolved executable path (for display in tool output).
    pub fn bin(&self) -> String {
        self.bin.to_string_lossy().into_owned()
    }

    /// Run nmap with the given args; returns stdout/stderr and exit code.
    pub async fn run(&self, args: &[&str], timeout_secs: u64) -> Result<RunOutput, String> {
        let mut cmd = Command::new(&self.bin);
        cmd.args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);

        let mut child = cmd.spawn().map_err(|e| {
            format!(
                "failed to start nmap ({e}); install nmap or set NMAP_MCP_BIN to the executable path"
            )
        })?;

        let stdout = child.stdout.take().expect("stdout piped");
        let stderr = child.stderr.take().expect("stderr piped");

        let deadline = Duration::from_secs(timeout_secs.clamp(1, 3600));
        let result = timeout(deadline, async {
            let (out, err) = tokio::join!(read_all(stdout), read_all_err(stderr));
            let status = child
                .wait()
                .await
                .map_err(|e| format!("wait failed: {e}"))?;
            Ok::<RunOutput, String>(RunOutput {
                exit_code: status.code(),
                stdout: out,
                stderr: err,
            })
        })
        .await;

        match result {
            Ok(Ok(output)) => Ok(output),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(format!(
                "nmap timed out after {timeout_secs}s (command: {} {})",
                self.bin(),
                args.join(" ")
            )),
        }
    }

    /// Run a scan: build `nmap -oX - <args>`, parse the XML result into JSON.
    ///
    /// Returns `Err` when nmap fails to start, exits non-zero, or produces
    /// output that is not nmap XML. A non-zero exit with valid XML (e.g. a
    /// warning plus results) still parses; the stderr is attached under
    /// `"stderr"` when non-empty.
    pub async fn scan(&self, args: &[String], timeout_secs: u64) -> Result<Value, String> {
        let mut full: Vec<String> = Vec::with_capacity(args.len() + 2);
        full.push("-oX".to_string());
        full.push("-".to_string());
        full.extend_from_slice(args);

        let refs: Vec<&str> = full.iter().map(|s| s.as_str()).collect();
        let out = self.run(&refs, timeout_secs).await?;
        if out.stdout.trim().is_empty() {
            let detail = if out.stderr.trim().is_empty() {
                String::new()
            } else {
                format!(": {}", out.stderr.trim())
            };
            return Err(format!(
                "nmap produced no output (exit {:?}){detail}",
                out.exit_code
            ));
        }
        if !out.stdout.trim_start().starts_with('<') {
            return Err(format!(
                "nmap output is not XML (exit {:?}): {}",
                out.exit_code,
                preview(&out.stdout, 400)
            ));
        }

        let mut value = nmap_xml::parse_nmap_xml(&out.stdout)?;
        if let Some(obj) = value.as_object_mut() {
            if !out.stderr.trim().is_empty() {
                obj.insert(
                    "stderr".to_string(),
                    Value::String(out.stderr.trim().to_string()),
                );
            }
            if let Some(code) = out.exit_code {
                obj.insert("exit_code".to_string(), Value::from(code));
            }
        }
        Ok(value)
    }

    /// Run `nmap --version` and parse the version line.
    pub async fn version(&self) -> Result<(String, String), String> {
        let out = self.run(&["--version"], 30).await?;
        let first = out.stdout.lines().next().unwrap_or("").trim().to_string();
        if first.starts_with("Nmap version") {
            let version = first
                .trim_start_matches("Nmap version")
                .split_whitespace()
                .next()
                .unwrap_or("unknown")
                .to_string();
            Ok((version, first))
        } else {
            Err(format!(
                "unexpected nmap --version output: {}",
                preview(&out.stdout, 200)
            ))
        }
    }

    /// Run `nmap --script-help <names>` and return the raw stdout.
    pub async fn script_help(&self, names: &[&str], timeout_secs: u64) -> Result<String, String> {
        let mut args = vec!["--script-help"];
        args.extend_from_slice(names);
        let out = self.run(&args, timeout_secs).await?;
        if out.stdout.trim().is_empty() {
            return Err(format!(
                "nmap --script-help produced no output: {}",
                out.stderr.trim()
            ));
        }
        Ok(out.stdout)
    }
}

async fn read_all(mut r: tokio::process::ChildStdout) -> String {
    let mut s = String::new();
    let _ = r.read_to_string(&mut s).await;
    s
}

async fn read_all_err(mut r: tokio::process::ChildStderr) -> String {
    let mut s = String::new();
    let _ = r.read_to_string(&mut s).await;
    s
}

/// First `max` chars of a string with an ellipsis marker if truncated.
fn preview(s: &str, max: usize) -> String {
    let mut out = s.trim().chars().take(max).collect::<String>();
    if s.trim().chars().count() > max {
        out.push_str("...");
    }
    out
}

/// Locate script.db for the resolved nmap binary. Env override
/// `NMAP_MCP_SCRIPT_DB` wins; otherwise walk up from the binary's directory
/// looking for `share/nmap/scripts/script.db` (covers extracted packages and
/// custom prefixes), then fall back to the standard system locations.
pub fn script_db_path(runner: &NmapRunner) -> Option<PathBuf> {
    if let Ok(p) = env::var("NMAP_MCP_SCRIPT_DB") {
        if !p.is_empty() && Path::new(&p).is_file() {
            return Some(PathBuf::from(p));
        }
    }

    let bin_path = Path::new(&runner.bin);
    if bin_path.is_absolute() {
        let mut dir = bin_path.parent();
        while let Some(d) = dir {
            let candidate = d
                .join("share")
                .join("nmap")
                .join("scripts")
                .join("script.db");
            if candidate.is_file() {
                return Some(candidate);
            }
            dir = d.parent();
        }
    }
    for cand in [
        "/usr/share/nmap/scripts/script.db",
        "/usr/local/share/nmap/scripts/script.db",
        "/opt/homebrew/share/nmap/scripts/script.db",
    ] {
        if Path::new(cand).is_file() {
            return Some(PathBuf::from(cand));
        }
    }
    None
}

/// Directory containing the NSE script files (`*.nse`), derived from the
/// script.db location; falls back to listing from the binary prefix.
pub fn scripts_dir(runner: &NmapRunner) -> Option<PathBuf> {
    if let Some(db) = script_db_path(runner) {
        if let Some(dir) = db.parent() {
            if dir.join("script.db").is_file() {
                return Some(dir.to_path_buf());
            }
        }
    }
    let bin_path = Path::new(&runner.bin);
    if bin_path.is_absolute() {
        let mut dir = bin_path.parent();
        while let Some(d) = dir {
            let candidate = d.join("share").join("nmap").join("scripts");
            if candidate.is_dir() {
                return Some(candidate);
            }
            dir = d.parent();
        }
    }
    None
}

/// Number of `.nse` files in the scripts directory, if it can be found.
pub fn script_file_count(runner: &NmapRunner) -> Option<usize> {
    let dir = scripts_dir(runner)?;
    let entries = std::fs::read_dir(dir).ok()?;
    let count = entries
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().map(|x| x == "nse").unwrap_or(false))
        .count();
    Some(count)
}

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

    #[test]
    fn preview_truncates() {
        let s = "a".repeat(500);
        let p = preview(&s, 400);
        assert_eq!(p.chars().count(), 403);
        assert!(p.ends_with("..."));
        assert_eq!(preview("short", 400), "short");
    }

    #[tokio::test]
    async fn runner_reports_missing_binary() {
        let runner = NmapRunner {
            bin: PathBuf::from("/nonexistent/nmap-xyz"),
        };
        let err = runner.run(&["--version"], 5).await.unwrap_err();
        assert!(err.contains("failed to start nmap"));
    }
}