nmap-mcp 0.1.0

Nmap network scanner and NSE scripting engine control for AI assistants via MCP
//! Input validation for tool parameters.
//!
//! nmap is executed with explicit argument arrays (no shell), so nothing the
//! user passes can become a shell command. These validators still reject
//! malformed input early with clear messages, and keep nmap from being
//! confused by whitespace or out-of-range values.

/// Default scan timeout in seconds.
pub const DEFAULT_TIMEOUT_SECS: u64 = 120;
/// Upper bound for any single scan timeout.
pub const MAX_TIMEOUT_SECS: u64 = 3600;

/// Validate a scan target (hostname, IP, CIDR, or comma-separated list).
/// Rejects empty strings and anything containing whitespace (nmap splits
/// targets on whitespace; a single argument with spaces is never valid).
pub fn validate_target(target: &str) -> Result<(), String> {
    let t = target.trim();
    if t.is_empty() {
        return Err("target must not be empty".to_string());
    }
    if t.chars().any(char::is_whitespace) {
        return Err(
            "target must not contain whitespace; pass one target or a comma-separated list"
                .to_string(),
        );
    }
    if t.len() > 256 {
        return Err("target is too long (max 256 chars)".to_string());
    }
    Ok(())
}

/// Validate a ports expression: comma-separated entries of the form `N`,
/// `N-M`, or `N,M`, all within 1..=65535. nmap also accepts service names
/// (`ssh`, `http`) and the `-` wildcard; those are allowed too.
pub fn validate_ports(ports: &str) -> Result<(), String> {
    let p = ports.trim();
    if p.is_empty() {
        return Err("ports must not be empty".to_string());
    }
    if p.len() > 1024 {
        return Err("ports expression too long".to_string());
    }
    for token in p.split(',') {
        let token = token.trim();
        if token == "-" {
            continue;
        }
        // Service name (letters only) or numeric range.
        if token.chars().all(|c| c.is_ascii_alphabetic()) {
            continue;
        }
        let mut parts = token.split('-');
        let lo = parts.next().unwrap_or("");
        let hi = parts.next();
        let lo: u32 = lo
            .trim()
            .parse()
            .map_err(|_| format!("invalid port or range '{token}'"))?;
        if !(1..=65535).contains(&lo) {
            return Err(format!("port {lo} out of range 1-65535"));
        }
        if let Some(hi) = hi {
            if parts.next().is_some() || hi.contains('-') {
                return Err(format!("invalid port range '{token}'"));
            }
            let hi: u32 = hi
                .trim()
                .parse()
                .map_err(|_| format!("invalid port range '{token}'"))?;
            if !(1..=65535).contains(&hi) {
                return Err(format!("port {hi} out of range 1-65535"));
            }
            if hi < lo {
                return Err(format!("port range '{token}' is reversed"));
            }
        }
    }
    Ok(())
}

/// Validate a timing template value: nmap accepts `-T0` through `-T5`.
pub fn validate_timing(timing: u8) -> Result<(), String> {
    if timing > 5 {
        return Err("timing must be 0-5 (paranoid..insane)".to_string());
    }
    Ok(())
}

/// Validate version detection intensity: `--version-intensity 0..9`.
pub fn validate_intensity(intensity: u8) -> Result<(), String> {
    if intensity > 9 {
        return Err("version_intensity must be 0-9".to_string());
    }
    Ok(())
}

/// Validate `--top-ports` count.
pub fn validate_top_ports(n: u32) -> Result<(), String> {
    if n == 0 || n > 10000 {
        return Err("top_ports must be 1-10000".to_string());
    }
    Ok(())
}

/// Resolve an optional timeout (seconds) to a bounded default.
pub fn timeout_secs(requested: Option<u64>) -> u64 {
    requested
        .unwrap_or(DEFAULT_TIMEOUT_SECS)
        .clamp(1, MAX_TIMEOUT_SECS)
}

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

    #[test]
    fn targets() {
        assert!(validate_target("127.0.0.1").is_ok());
        assert!(validate_target("scanme.nmap.org").is_ok());
        assert!(validate_target("10.0.0.0/24").is_ok());
        assert!(validate_target("192.168.1.1,192.168.1.2").is_ok());
        assert!(validate_target("").is_err());
        assert!(validate_target("   ").is_err());
        assert!(validate_target("10.0.0.1 10.0.0.2").is_err());
        assert!(validate_target("host with space").is_err());
    }

    #[test]
    fn ports() {
        assert!(validate_ports("22").is_ok());
        assert!(validate_ports("22,80,443").is_ok());
        assert!(validate_ports("1-1024").is_ok());
        assert!(validate_ports("22,80,8000-9000").is_ok());
        assert!(validate_ports("ssh,http").is_ok());
        assert!(validate_ports("-").is_ok());
        assert!(validate_ports("").is_err());
        assert!(validate_ports("0").is_err());
        assert!(validate_ports("65536").is_err());
        assert!(validate_ports("1024-1").is_err());
        assert!(validate_ports("1-2-3").is_err());
        assert!(validate_ports("abc-def").is_err());
        assert!(validate_ports("22x").is_err());
        // Service names are valid nmap tokens and may mix with numbers.
        assert!(validate_ports("22,foo,80").is_ok());
    }

    #[test]
    fn timing_and_intensity() {
        assert!(validate_timing(0).is_ok());
        assert!(validate_timing(5).is_ok());
        assert!(validate_timing(6).is_err());
        assert!(validate_intensity(0).is_ok());
        assert!(validate_intensity(9).is_ok());
        assert!(validate_intensity(10).is_err());
        assert!(validate_top_ports(100).is_ok());
        assert!(validate_top_ports(0).is_err());
        assert!(validate_top_ports(10001).is_err());
    }

    #[test]
    fn timeouts_are_bounded() {
        assert_eq!(timeout_secs(None), 120);
        assert_eq!(timeout_secs(Some(5)), 5);
        assert_eq!(timeout_secs(Some(0)), 1);
        assert_eq!(timeout_secs(Some(99999)), 3600);
    }
}