nmap-mcp 0.1.0

Nmap network scanner and NSE scripting engine control for AI assistants via MCP
//! Parser for nmap's script database (`script.db`), which lists every NSE
//! script shipped with the installation and its categories.
//!
//! Each line of script.db is one `Entry { ... }` record:
//!
//! ```text
//! Entry { filename = "acarsd-info.nse", categories = { "discovery", "safe", } }
//! ```
//!
//! The parser is a pure function over the file text; no I/O, no dependency on
//! the live nmap install, so it is fully unit-testable.

use serde_json::{Map, Value};

/// The fourteen canonical NSE script categories defined by the Nmap Scripting
/// Engine. Scripts may belong to several; the `default` category runs with
/// `-sC` or `-A`.
pub const SCRIPT_CATEGORIES: [&str; 14] = [
    "auth",
    "broadcast",
    "brute",
    "default",
    "discovery",
    "dos",
    "exploit",
    "external",
    "fuzzer",
    "intrusive",
    "malware",
    "safe",
    "version",
    "vuln",
];

/// One entry of script.db.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptEntry {
    /// Script file name, e.g. `http-title.nse`.
    pub filename: String,
    /// Categories the script belongs to (lowercase).
    pub categories: Vec<String>,
}

impl ScriptEntry {
    /// The script's base name without the `.nse` extension, e.g. `http-title`.
    pub fn base_name(&self) -> &str {
        self.filename.strip_suffix(".nse").unwrap_or(&self.filename)
    }
}

/// Parse the full text of script.db into entries, in file order.
/// Malformed lines are skipped rather than failing the whole parse.
pub fn parse_script_db(input: &str) -> Vec<ScriptEntry> {
    input.lines().filter_map(parse_entry_line).collect()
}

/// Parse a single `Entry { ... }` line; `None` if the line is not a valid
/// entry (blank lines, comments, trailing garbage).
pub fn parse_entry_line(line: &str) -> Option<ScriptEntry> {
    let line = line.trim();
    let body = line.strip_prefix("Entry {")?.strip_suffix('}')?.trim();
    let mut filename = None;
    let mut categories = Vec::new();

    // Split the body into `key = value` fields. The categories value is a
    // brace-delimited list that may contain commas, so walk the body field by
    // field on `=` boundaries instead of splitting on commas.
    let mut rest = body;
    while !rest.trim().is_empty() {
        let eq = rest.find('=')?;
        // The key may carry a leading comma from the previous field.
        let key = rest[..eq].trim().trim_start_matches(',').trim();
        rest = rest[eq + 1..].trim();
        match key {
            "filename" => {
                let end = rest.find(',').unwrap_or(rest.len());
                filename = Some(strip_quotes(rest[..end].trim()).to_string());
                rest = &rest[end..];
            }
            "categories" => {
                if let Some(open) = rest.find('{') {
                    if let Some(close) = rest[open..].find('}') {
                        let inner = &rest[open + 1..open + close];
                        categories = inner
                            .split(',')
                            .map(str::trim)
                            .filter(|s| !s.is_empty())
                            .map(|s| strip_quotes(s).to_string())
                            .collect();
                    }
                }
                break;
            }
            _ => break,
        }
    }

    Some(ScriptEntry {
        filename: filename?,
        categories,
    })
}

fn strip_quotes(s: &str) -> &str {
    s.trim_matches('"')
}

/// Filter entries by category (exact match) and/or name substring.
/// Category matching is case-insensitive.
pub fn filter_entries<'a>(
    entries: &'a [ScriptEntry],
    category: Option<&str>,
    name: Option<&str>,
) -> Vec<&'a ScriptEntry> {
    entries
        .iter()
        .filter(|e| match category {
            Some(c) => e.categories.iter().any(|cat| cat.eq_ignore_ascii_case(c)),
            None => true,
        })
        .filter(|e| match name {
            Some(n) => e.filename.to_lowercase().contains(&n.to_lowercase()),
            None => true,
        })
        .collect()
}

/// Summarize the distinct categories present in a set of entries, with counts.
pub fn category_counts(entries: &[ScriptEntry]) -> Vec<Value> {
    let mut counts: Vec<(String, usize)> = Vec::new();
    for e in entries {
        for c in &e.categories {
            match counts.iter_mut().find(|(name, _)| name == c) {
                Some((_, n)) => *n += 1,
                None => counts.push((c.clone(), 1)),
            }
        }
    }
    counts.sort_by(|a, b| a.0.cmp(&b.0));
    counts
        .into_iter()
        .map(|(category, count)| {
            let mut m = Map::new();
            m.insert("category".to_string(), Value::String(category));
            m.insert("count".to_string(), Value::from(count as u64));
            Value::Object(m)
        })
        .collect()
}

/// Convert an entry to a JSON row for tool output.
pub fn entry_json(e: &ScriptEntry) -> Value {
    let mut m = Map::new();
    m.insert("name".to_string(), Value::String(e.base_name().to_string()));
    m.insert("filename".to_string(), Value::String(e.filename.clone()));
    m.insert(
        "categories".to_string(),
        Value::Array(
            e.categories
                .iter()
                .map(|c| Value::String(c.clone()))
                .collect(),
        ),
    );
    Value::Object(m)
}

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

    const SAMPLE_DB: &str = r#"Entry { filename = "acarsd-info.nse", categories = { "discovery", "safe", } }
Entry { filename = "address-info.nse", categories = { "default", "safe", } }
Entry { filename = "afp-brute.nse", categories = { "brute", "intrusive", } }
Entry { filename = "http-title.nse", categories = { "default", "discovery", } }
"#;

    #[test]
    fn parses_all_entries() {
        let entries = parse_script_db(SAMPLE_DB);
        assert_eq!(entries.len(), 4);
        assert_eq!(entries[0].filename, "acarsd-info.nse");
        assert_eq!(entries[0].categories, vec!["discovery", "safe"]);
        assert_eq!(entries[2].categories, vec!["brute", "intrusive"]);
    }

    #[test]
    fn base_name_strips_extension() {
        let entries = parse_script_db(SAMPLE_DB);
        assert_eq!(entries[3].base_name(), "http-title");
    }

    #[test]
    fn skips_garbage_lines() {
        let text = "Entry { filename = \"ok.nse\", categories = { \"safe\", } }\nnot an entry\n\n";
        let entries = parse_script_db(text);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].filename, "ok.nse");
    }

    #[test]
    fn filters_by_category_and_name() {
        let entries = parse_script_db(SAMPLE_DB);
        let discovery = filter_entries(&entries, Some("discovery"), None);
        assert_eq!(discovery.len(), 2);
        assert!(discovery
            .iter()
            .all(|e| e.categories.contains(&"discovery".to_string())));

        let titled = filter_entries(&entries, None, Some("title"));
        assert_eq!(titled.len(), 1);
        assert_eq!(titled[0].filename, "http-title.nse");

        // Case-insensitive category match.
        let brute = filter_entries(&entries, Some("BRUTE"), None);
        assert_eq!(brute.len(), 1);
    }

    #[test]
    fn category_counts_are_sorted() {
        let entries = parse_script_db(SAMPLE_DB);
        let counts = category_counts(&entries);
        assert!(counts
            .iter()
            .any(|c| c["category"] == "default" && c["count"] == 2));
        assert!(counts
            .iter()
            .any(|c| c["category"] == "safe" && c["count"] == 2));
        // Sorted by name.
        let names: Vec<&str> = counts
            .iter()
            .map(|c| c["category"].as_str().unwrap())
            .collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }

    #[test]
    fn canonical_categories_are_complete() {
        assert_eq!(SCRIPT_CATEGORIES.len(), 14);
        assert!(SCRIPT_CATEGORIES.contains(&"default"));
        assert!(SCRIPT_CATEGORIES.contains(&"vuln"));
        assert!(SCRIPT_CATEGORIES.contains(&"safe"));
    }
}