diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c1935f..16d0ab8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,27 +2,37 @@ name: CI on: push: - branches: [main, "feat/**"] + branches: [main, "feat/**", "fix/**"] pull_request: branches: [main] jobs: test: - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python-version: ["3.10", "3.11", "3.12"] + runs-on: ${{ matrix.os }} steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Python - uses: actions/setup-python@v5 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: - python-version: "3.11" - - - name: Install async scanner dependency - run: python -m pip install --upgrade pip aiohttp - + python-version: ${{ matrix.python-version }} + cache: pip + - name: Install dependencies + run: python -m pip install --upgrade pip -r requirements.txt - name: Compile Python sources run: python -m compileall -q . - - - name: Run tests + - name: Startup/import smoke test + run: python -c "import SpectraScan; from modules.async_scanner import AsyncPortScanner; from modules.vuln_scanner import VulnScanner" + - name: Run unit and integration tests run: python -m unittest discover -s tests -p "test_*.py" + - name: Dependency audit + run: | + python -m pip install pip-audit + python -m pip_audit -r requirements.txt + - name: Static security analysis + run: | + python -m pip install bandit + python -m bandit -q -r SpectraScan.py modules -x modules/darkweb.py diff --git a/SpectraScan.py b/SpectraScan.py index 71082f1..27643b8 100644 --- a/SpectraScan.py +++ b/SpectraScan.py @@ -4296,22 +4296,40 @@ def darkweb_menu() -> None: # ============== Report Manager ============== class ReportManager: def __init__(self): - self.report_dir = os.path.expanduser("~/.local/share/SpectraScan") + self.report_dir = os.path.abspath(os.path.expanduser( + os.environ.get("SPECTRASCAN_HOME", "~/.local/share/SpectraScan") + )) os.makedirs(self.report_dir, exist_ok=True) self.current_file = None self.append_file = False - def save_output(self): - # In CLI mode, we might skip auto-prompting if not explicitly asked, - # but we keep the logic for consistency. - pass - + def save_output(self, filename=None, content=None): + """Atomically save report content under the configured report directory.""" + if filename is None or content is None: + return None + safe_name = os.path.basename(str(filename)) + if not safe_name or safe_name in {".", ".."}: + raise ValueError("invalid report filename") + os.makedirs(self.report_dir, exist_ok=True) + destination = os.path.join(self.report_dir, safe_name) + temporary = destination + ".tmp" + try: + with open(temporary, "w", encoding="utf-8", newline="") as handle: + handle.write(str(content)) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + finally: + if os.path.exists(temporary): + os.remove(temporary) + return destination + def write(self, text): # In CLI mode, we can just print to console directly print(text) def read_report(self): - report_files = [f for f in os.listdir(self.report_dir) if f.startswith('SS-report')] + report_files = [f for f in os.listdir(self.report_dir) if f.startswith(('SS-report', 'SS-portscan'))] if not report_files: print(f"{RED}No reports found.{RESET}") return @@ -5205,105 +5223,88 @@ def get_results(self) -> Dict: "vulnerabilities": self.vulnerabilities, } - def export_json(self, filename: str): - with open(filename, "w") as f: - json.dump(self.get_results(), f, indent=2, default=str) - print(f"{GREEN}[+] JSON report saved: {filename}") - - def export_html(self, filename: str): - results = self.get_results() - target = html.escape(str(results.get("target", ""))) - scan_type = html.escape(str(results.get("scan_type", ""))) - resolved_ip = html.escape(str(results.get("resolved_ip", "") or "")) - timestamp = html.escape(str(results.get("timestamp", ""))) - duration = f"{results.get('duration', 0):.2f}" - - parts = [f""" - - - - SpectraScan Report - {target} - - - -
-

SpectraScan Report

-
-

Target: {target}

-

Resolved IP: {resolved_ip}

-

Scan Type: {scan_type}

-

Timestamp: {timestamp}

-

Duration: {duration}s

-

Open Ports: {len(results.get('open_ports', []))}

-

Vulnerabilities: {len(results.get('vulnerabilities', []))}

-
-

Open Ports

- - """] - - for port in results.get("open_ports", []): - port_num = html.escape(str(port.get("port", ""))) - service = port.get("service", "") - if isinstance(service, tuple): - service = service if service else "" - service = html.escape(str(service)) - state = html.escape(str(port.get("state", ""))) - banner = html.escape((port.get("banner", "") or "N/A")[:50]) - parts.append( - f"" - f"" - ) - - parts.append("""
PortServiceStateBanner
{port_num}{service}{state}{banner}
-
- -""") - - with open(filename, "w") as f: - f.write("".join(parts)) - print(f"{GREEN}[+] HTML report saved: {filename}") - - def export_csv(self, filename: str): - with open(filename, "w", newline="") as f: - writer = csv.writer(f) - writer.writerow( - ["Port", "Protocol", "State", "Service", "Banner", "Vulnerabilities"] - ) - for port in self.results: - service = port.get("service", "") - if isinstance(service, tuple): - service = service if service else "" - banner = port.get("banner", "") or "None" - vulns = ( - "; ".join( - [v["vulnerability"] for v in port.get("vulnerabilities", [])] - ) - or "None" - ) - writer.writerow( - [ - port["port"], - "tcp", - port["state"], - service, - banner[:50], - vulns, - ] - ) - print(f"{GREEN}[+] CSV report saved: {filename}") - + @staticmethod + def _atomic_write(filename: str, writer): + """Write report to a sibling temporary file and atomically replace destination.""" + destination = os.path.abspath(filename) + os.makedirs(os.path.dirname(destination), exist_ok=True) + temporary = destination + ".tmp" + try: + writer(temporary) + with open(temporary, "rb") as handle: + os.fsync(handle.fileno()) + os.replace(temporary, destination) + finally: + if os.path.exists(temporary): + os.remove(temporary) + + def export_json(self, filename: str): + payload = json.dumps(self.get_results(), indent=2, default=str) + self._atomic_write(filename, lambda path: open(path, "w", encoding="utf-8").write(payload)) + print(f"{GREEN}[+] JSON report saved: {filename}") + + def export_html(self, filename: str): + results = self.get_results() + target = html.escape(str(results.get("target", ""))) + scan_type = html.escape(str(results.get("scan_type", ""))) + resolved_ip = html.escape(str(results.get("resolved_ip", "") or "")) + timestamp = html.escape(str(results.get("timestamp", ""))) + duration = f"{results.get('duration', 0):.2f}" + rows = [] + for item in results.get("open_ports", []): + port = html.escape(str(item.get("port", ""))) + service = item.get("service", "") + if isinstance(service, tuple): + service = service if service else "" + service = html.escape(str(service)) + state = html.escape(str(item.get("state", ""))) + banner = html.escape(str(item.get("banner", "") or "N/A")[:200]) + rows.append(f"{port}{service}{state}{banner}") + document = f""" +SpectraScan Report - {target} + + +

SpectraScan Report

+

Target: {target}

Resolved IP: {resolved_ip}

Scan type: {scan_type}

+

Timestamp: {timestamp}

Duration: {duration}s

+

Open ports ({len(results.get('open_ports', []))})

+ +{''.join(rows)}
PortServiceStateBanner
""" + def write(path): + with open(path, "w", encoding="utf-8", newline="") as handle: + handle.write(document) + self._atomic_write(filename, write) + print(f"{GREEN}[+] HTML report saved: {filename}") + + @staticmethod + def _csv_safe(value): + text_value = str(value if value is not None else "") + # Prevent spreadsheet formula execution from untrusted banners or service data. + if text_value.lstrip().startswith(("=", "+", "-", "@", "\t", "\r")): + return "'" + text_value + return text_value + + def export_csv(self, filename: str): + def write(path): + with open(path, "w", newline="", encoding="utf-8") as handle: + writer = csv.writer(handle) + writer.writerow(["Port", "Protocol", "State", "Service", "Banner", "Vulnerabilities"]) + for item in self.results: + service = item.get("service", "") + if isinstance(service, tuple): + service = service if service else "" + banner = item.get("banner", "") or "None" + vulnerabilities = "; ".join( + str(v.get("vulnerability", "")) for v in item.get("vulnerabilities", []) + ) or "None" + writer.writerow([item.get("port", ""), item.get("protocol", "tcp"), + self._csv_safe(item.get("state", "")), + self._csv_safe(service), self._csv_safe(banner[:200]), + self._csv_safe(vulnerabilities)]) + self._atomic_write(filename, write) + print(f"{GREEN}[+] CSV report saved: {filename}") + # ============== Network Scanner ============== class NetworkScanner: @staticmethod @@ -6473,135 +6474,66 @@ def parse_ports(ports_input: str): return sorted(ports) if ports else None -def run_network_port_scan( - network_target: str, - scan_kwargs: dict, -): - """Scan each usable host in a CIDR network.""" - - try: - network = ipaddress.ip_network( - network_target, - strict=False, - ) - except ValueError as exc: - console.print( - f"[!] Invalid network: {exc}", - style="bold red", - ) - return [] - - hosts = list(network.hosts()) - - if not hosts: - console.print( - "[!] No usable hosts found.", - style="bold red", - ) - return [] - - if len(hosts) > 256: - proceed = Confirm.ask( - f"[!] Network contains {len(hosts)} hosts. Continue?", - default=False, - ) - if not proceed: - console.print( - "[*] Network scan cancelled.", - style="yellow", - ) - return [] - - console.print( - "\n[bold cyan]" - "============================================================" - "[/bold cyan]" - ) - console.print( - f"[bold green][+] Network Scan: {network}[/bold green]" - ) - console.print( - f"[cyan][*] Hosts: {len(hosts)}[/cyan]" - ) - console.print( - "[bold cyan]" - "============================================================" - "[/bold cyan]\n" - ) - - all_results = [] - - for index, host in enumerate(hosts, start=1): - host_ip = str(host) - - console.print( - f"\n[bold yellow]" - f"[{index}/{len(hosts)}] Scanning {host_ip}" - f"[/bold yellow]" - ) - - try: - resolved_ip = resolve_host(host_ip) - - scanner = PortScanner( - host_ip, - **scan_kwargs, - ) - - scanner.resolved_ip = resolved_ip - scanner.scan() - - result = scanner.get_results() - - if isinstance(result, dict): - all_results.append(result) - - scanner.print_summary() - - except KeyboardInterrupt: - console.print( - "\n[!] Network scan interrupted.", - style="yellow", - ) - break - - except Exception as exc: - console.print( - f"[!] {host_ip}: {exc}", - style="red", - ) - - total_open = sum( - len(result.get("open_ports", [])) - for result in all_results - if isinstance(result, dict) - ) - - console.print( - "\n[bold cyan]" - "============================================================" - "[/bold cyan]" - ) - console.print( - "[bold green][✓] Network scan complete[/bold green]" - ) - console.print( - f"[cyan][*] Hosts processed: " - f"{len(all_results)}/{len(hosts)}[/cyan]" - ) - console.print( - f"[cyan][*] Total open ports: {total_open}[/cyan]" - ) - console.print( - "[bold cyan]" - "============================================================" - "[/bold cyan]" - ) - - return all_results - - -@guard_interrupt +def run_network_port_scan( + network_target: str, + scan_kwargs: dict, +): + """Scan a bounded CIDR host stream; never materialize the full host list.""" + try: + network = ipaddress.ip_network(network_target, strict=False) + except ValueError as exc: + console.print(f"[!] Invalid network: {exc}", style="bold red") + return [] + + usable_count = network.num_addresses + if network.version == 4 and network.prefixlen < 31: + usable_count -= 2 + max_hosts = int(scan_kwargs.pop("max_hosts", 4096)) + if max_hosts < 1: + console.print("[!] max_hosts must be positive.", style="bold red") + return [] + if usable_count > max_hosts: + console.print( + f"[!] Network has {usable_count} addresses, exceeding max_hosts={max_hosts}. " + "Narrow the CIDR or explicitly raise the limit.", + style="bold red", + ) + return [] + + exclusions = [] + for value in scan_kwargs.pop("exclude_ranges", []): + try: + exclusions.append(ipaddress.ip_network(value, strict=False)) + except ValueError: + console.print(f"[!] Ignoring invalid exclusion range: {value}", style="yellow") + + if usable_count > 256 and not Confirm.ask( + f"[!] Network contains {usable_count} addresses. Continue?", default=False + ): + console.print("[*] Network scan cancelled.", style="yellow") + return [] + + results = [] + host_count = sum(1 for host in network.hosts() + if not any(host in excluded for excluded in exclusions)) + for index, host in enumerate(network.hosts(), start=1): + if any(host in excluded for excluded in exclusions): + continue + host_ip = str(host) + console.print(f"\\n[bold yellow][{len(results) + 1}/{host_count}] Scanning {host_ip}[/bold yellow]") + try: + scanner = PortScanner(host_ip, **scan_kwargs) + scanner.resolved_ip = host_ip + scanner.scan() + if scanner.results: + results.append({"ip": host_ip, "hostname": reverse_dns(host_ip), + "ports": scanner.results}) + except (OSError, ValueError) as exc: + console.print(f"[!] Host scan failed for {host_ip}: {type(exc).__name__}", style="yellow") + return results + + + def run_port_scan_cli(): """Interactive Port Scan Menu.""" @@ -6870,63 +6802,129 @@ def print_main_menu(): console.print("[bold red]4.[/bold red] Exit") -def main(): - # Legacy CLI args for backward compatibility / scripting - if len(sys.argv) > 1: - parser = argparse.ArgumentParser(description="SpectraScan Legacy CLI") - parser.add_argument("-t", "--target", help="Target") - parser.add_argument("-d", "--domain", help="Domain") - parser.add_argument("-i", "--ip", help="IP") - parser.add_argument("--async-scan", action="store_true", help="Use the asyncio/aiohttp scanner engine for TCP scans") - parser.add_argument("--async-concurrency", type=int, default=100, help="Maximum concurrent async connections (default: 100)") - parser.add_argument("--async-timeout", type=float, default=1.0, help="Async connection timeout in seconds (default: 1.0)") - args, _ = parser.parse_known_args() +def _udp_scan(target: str, ports: List[int], timeout: float) -> List[Dict]: + """Conservative UDP probe: only replies are marked open; silence is inconclusive.""" + resolved = resolve_host(target) + found = [] + for port in ports: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.settimeout(timeout) + try: + sock.sendto(b"\x00", (resolved, port)) + try: + data, _ = sock.recvfrom(1024) + found.append({"port": port, "protocol": "udp", "state": "open", + "service": COMMON_PORTS.get(port, "unknown"), + "banner": data[:256].decode("utf-8", errors="replace")}) + except socket.timeout: + continue + except OSError: + continue + finally: + sock.close() + return found - if args.target: + +def main(): + parser = argparse.ArgumentParser(description="SpectraScan network scanner") + parser.add_argument("-t", "--target", help="Target hostname, IP, or URL") + parser.add_argument("-d", "--domain", help="Target domain (alias for --target)") + parser.add_argument("-i", "--ip", help="Target IP address (alias for --target)") + parser.add_argument("-p", "--ports", default="common", help="Ports: common, all, 80,443, or 1-1024") + parser.add_argument("--scan-type", choices=("tcp", "udp"), default="tcp", + help="Scan protocol (default: tcp)") + parser.add_argument("--timing", choices=tuple(TIMING_PROFILES), default="T3") + parser.add_argument("--timeout", type=float, default=None) + parser.add_argument("--threads", type=int, default=None) + parser.add_argument("--output", help="Report output path") + parser.add_argument("--format", choices=("json", "html", "csv"), + help="Report format; inferred from --output extension if omitted") + parser.add_argument("--async-scan", action="store_true", + help="Use the asynchronous TCP scanner") + parser.add_argument("--async-concurrency", type=int, default=100) + parser.add_argument("--async-timeout", type=float, default=1.0) + args = parser.parse_args() + + target = args.target or args.domain or args.ip + if not target: + if len(sys.argv) > 1: + parser.error("one of --target, --domain, or --ip is required") + print_banner() + while True: + print_main_menu() try: - target = normalize_target(args.target) - resolved_ip = resolve_host(target) + choice = input(f"{CYAN}root@spectra:~#{RESET} Select Option: ").strip() + except (KeyboardInterrupt, EOFError): + console.print("\\n[*] Exiting SpectraScan.", style="yellow") + break + if choice == "4": + console.print("[*] Exiting SpectraScan.", style="yellow") + break + elif choice in MENU_ACTIONS: + MENU_ACTIONS[choice][1]() + else: + console.print("[!] Invalid Option. Please try again.", style="red") + return + + ports = parse_ports(args.ports) + if ports is None: + parser.error(f"invalid --ports value: {args.ports!r}") + timeout = args.timeout if args.timeout is not None else TIMING_PROFILES[args.timing]["timeout"] + threads = args.threads if args.threads is not None else TIMING_PROFILES[args.timing]["threads"] + if not 0 < timeout <= 60: + parser.error("--timeout must be between 0 and 60 seconds") + if not 1 <= threads <= 512: + parser.error("--threads must be between 1 and 512") + if not 1 <= args.async_concurrency <= 512: + parser.error("--async-concurrency must be between 1 and 512") + if not 0 < args.async_timeout <= 60: + parser.error("--async-timeout must be between 0 and 60 seconds") + if args.async_scan and args.scan_type != "tcp": + parser.error("--async-scan currently supports TCP only") + + try: + try: + target = str(ipaddress.ip_address(target)) + except ValueError: + target = normalize_target(target) + if "/" in target: + parser.error("a single target is required; use the network-scan menu for CIDR ranges") + resolved_ip = resolve_host(target) + if args.scan_type == "udp": + if args.async_scan: + parser.error("UDP is not supported by --async-scan") + scanner = PortScanner(target, ports=ports, scan_type="udp", timeout=timeout, + threads=threads, timing=args.timing) + scanner.resolved_ip = resolved_ip + scanner.results = _udp_scan(target, ports, timeout) + scanner.start_time = time.time() + console.print(f"[green][+] UDP probe complete; {len(scanner.results)} responding ports[/green]") + elif args.async_scan: + scanner = AsyncPortScanner(target, ports=ports, timeout=args.async_timeout, + concurrency=args.async_concurrency) + scanner.resolved_ip = resolved_ip + asyncio.run(scanner.scan_async()) + scanner.results = scanner.get_results()["open_ports"] + scanner.start_time = time.time() - scanner.get_results()["duration"] + console.print(f"[green][+] Async TCP scan complete; {len(scanner.results)} open ports[/green]") + else: + scanner = PortScanner(target, ports=ports, scan_type="tcp", timeout=args.timeout, + threads=args.threads, timing=args.timing) + scanner.resolved_ip = resolved_ip + scanner.scan() + scanner.print_summary() + + if args.output: + report_format = args.format or os.path.splitext(args.output)[1].lower().lstrip(".") + if report_format not in {"json", "html", "csv"}: + parser.error("--format is required when --output has no .json, .html, or .csv extension") + os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) + {"json": scanner.export_json, "html": scanner.export_html, + "csv": scanner.export_csv}[report_format](args.output) + except (ValueError, OSError, socket.gaierror) as exc: + console.print(f"[!] Scan failed: {type(exc).__name__}: {exc}", style="bold red") + sys.exit(1) + - if args.async_scan: - scanner = AsyncPortScanner(target, ports=list(COMMON_PORTS.keys()), timeout=args.async_timeout, concurrency=args.async_concurrency) - scanner.resolved_ip = resolved_ip - asyncio.run(scanner.scan_async()) - result = scanner.get_results() - console.print(f"[green][✓] Async scan completed in {result['duration']:.2f}s — {len(result['open_ports'])} open ports[/green]") - for item in sorted(result["open_ports"], key=lambda value: value["port"]): - console.print(f"[green][+] {item['port']}/tcp {item.get('service', 'unknown')} {item.get('banner', '')[:80]}[/green]") - else: - scanner = PortScanner(target) - scanner.resolved_ip = resolved_ip - scanner.scan() - scanner.print_summary() - except Exception as exc: - console.print( - f"[!] Scan failed: {exc}", - style="bold red", - ) - sys.exit(1) - - return - - print_banner() - - while True: - print_main_menu() - try: - choice = input(f"{CYAN}root@spectra:~#{RESET} Select Option: ").strip() - except (KeyboardInterrupt, EOFError): - console.print("\n[*] Exiting SpectraScan. Stay Anonymous.", style="yellow") - break - - if choice == "4": - console.print("[*] Exiting SpectraScan. Stay Anonymous.", style="yellow") - break - elif choice in MENU_ACTIONS: - MENU_ACTIONS[choice][1]() - else: - console.print("[!] Invalid Option. Please try again.", style="red") - - if __name__ == "__main__": main() \ No newline at end of file diff --git a/modules/async_scanner.py b/modules/async_scanner.py index 6135a31..92c77b5 100644 --- a/modules/async_scanner.py +++ b/modules/async_scanner.py @@ -1,49 +1,37 @@ -"""Asynchronous TCP/HTTP scanning engine for SpectraScan. - -This module is additive: the legacy PortScanner remains unchanged and callers -can opt into AsyncPortScanner when they want asyncio/aiohttp concurrency. -""" - +"""Bounded asynchronous TCP/HTTP scanner.""" from __future__ import annotations import asyncio import socket +import ssl import time -from typing import Any, Dict, Iterable, List, Optional, Tuple +from typing import Any, Dict, Iterable, List, Optional import aiohttp - HTTP_PORTS = {80, 443, 8000, 8080, 8081, 8443, 8888} +MAX_PORTS = 65535 +MAX_CONCURRENCY = 512 class AsyncPortScanner: - """Concurrent TCP scanner with optional aiohttp HTTP enrichment. - - The result schema intentionally mirrors the useful subset of PortScanner: - target, resolved_ip, scan_type, timestamp, duration, open_ports and - vulnerabilities. - """ - - def __init__( - self, - target: str, - ports: Optional[Iterable[int]] = None, - timeout: float = 1.0, - concurrency: int = 100, - check_http: bool = True, - user_agent: str = "SpectraScan/async", - ) -> None: - if timeout <= 0: - raise ValueError("timeout must be greater than 0") - if concurrency <= 0: - raise ValueError("concurrency must be greater than 0") - - self.target = target - self.ports = sorted({int(port) for port in (ports or [])}) + def __init__(self, target: str, ports: Optional[Iterable[int]] = None, + timeout: float = 1.0, concurrency: int = 100, + check_http: bool = True, user_agent: str = "SpectraScan/async") -> None: + if not target or not target.strip(): + raise ValueError("target must not be empty") + if not 0 < float(timeout) <= 60: + raise ValueError("timeout must be between 0 and 60 seconds") + if not 0 < int(concurrency) <= MAX_CONCURRENCY: + raise ValueError(f"concurrency must be between 1 and {MAX_CONCURRENCY}") + normalized = sorted({int(port) for port in (ports or [])}) + if any(port < 1 or port > MAX_PORTS for port in normalized): + raise ValueError("ports must be in the range 1..65535") + self.target = target.strip() + self.ports = normalized self.timeout = float(timeout) self.concurrency = int(concurrency) - self.check_http = check_http + self.check_http = bool(check_http) self.user_agent = user_agent self.resolved_ip: Optional[str] = None self.results: List[Dict[str, Any]] = [] @@ -51,222 +39,138 @@ def __init__( self.start_time: Optional[float] = None async def resolve(self) -> str: - """Resolve the target without blocking the event loop.""" loop = asyncio.get_running_loop() - infos = await loop.getaddrinfo( - self.target, - None, - family=socket.AF_INET, - type=socket.SOCK_STREAM, - ) + infos = await loop.getaddrinfo(self.target, None, type=socket.SOCK_STREAM) if not infos: raise ValueError(f"Cannot resolve target: {self.target}") - self.resolved_ip = infos[0][4][0] return self.resolved_ip - async def _probe_tcp( - self, - port: int, - semaphore: asyncio.Semaphore, - ) -> Dict[str, Any]: - result: Dict[str, Any] = { - "port": port, - "protocol": "tcp", - "state": "closed", - "service": self._service_name(port), - "banner": "", - "error": None, - } - + async def _probe_tcp(self, port: int, semaphore: asyncio.Semaphore) -> Dict[str, Any]: + result = {"port": port, "protocol": "tcp", "state": "closed", + "service": self._service_name(port), "banner": "", "error": None} async with semaphore: - writer: Optional[asyncio.StreamWriter] = None + writer = None try: + use_tls = port in {443, 8443} reader, writer = await asyncio.wait_for( - asyncio.open_connection(self.resolved_ip, port), - timeout=self.timeout, - ) + asyncio.open_connection(self.resolved_ip, port, ssl=use_tls, + server_hostname=self.target if use_tls else None), + timeout=self.timeout) result["state"] = "open" - if port in HTTP_PORTS: - request = ( - f"HEAD / HTTP/1.1\r\n" - f"Host: {self.target}\r\n" - f"User-Agent: {self.user_agent}\r\n" - "Connection: close\r\n\r\n" - ) + request = (f"HEAD / HTTP/1.1\r\nHost: {self.target}\r\n" + f"User-Agent: {self.user_agent}\r\nConnection: close\r\n\r\n") writer.write(request.encode("ascii", errors="ignore")) await writer.drain() - try: - data = await asyncio.wait_for( - reader.read(1024), - timeout=min(self.timeout, 1.5), - ) - result["banner"] = data.decode( - "utf-8", errors="replace" - ).strip()[:4096] + data = await asyncio.wait_for(reader.read(1024), timeout=min(self.timeout, 1.5)) + result["banner"] = data.decode("utf-8", errors="replace").strip()[:4096] except asyncio.TimeoutError: pass - + except asyncio.CancelledError: + raise except asyncio.TimeoutError: result["state"] = "filtered" except (ConnectionRefusedError, ConnectionResetError): result["state"] = "closed" - except OSError as exc: - if getattr(exc, "errno", None) in {111, 61, 10061}: - result["state"] = "closed" - else: - result["state"] = "error" - result["error"] = str(exc) + except (OSError, ssl.SSLError) as exc: + result["state"] = "error" + result["error"] = type(exc).__name__ finally: if writer is not None: writer.close() try: await writer.wait_closed() - except (AttributeError, OSError): + except (AttributeError, OSError, asyncio.CancelledError): pass - return result - async def _http_enrich( - self, - result: Dict[str, Any], - session: aiohttp.ClientSession, - semaphore: asyncio.Semaphore, - ) -> Dict[str, Any]: + async def _http_enrich(self, result: Dict[str, Any], session: aiohttp.ClientSession, + semaphore: asyncio.Semaphore) -> Dict[str, Any]: port = int(result["port"]) scheme = "https" if port in {443, 8443} else "http" url = f"{scheme}://{self.target}:{port}/" - async with semaphore: try: - async with session.get( - url, - allow_redirects=False, - ssl=False, - timeout=aiohttp.ClientTimeout(total=self.timeout), - ) as response: + async with session.get(url, allow_redirects=False, + timeout=aiohttp.ClientTimeout(total=self.timeout)) as response: result["http"] = { "status_code": response.status, "server": response.headers.get("Server"), "content_type": response.headers.get("Content-Type"), "location": response.headers.get("Location"), - "security_headers": { - name: response.headers.get(name) - for name in ( - "Strict-Transport-Security", - "Content-Security-Policy", - "X-Frame-Options", - "X-Content-Type-Options", - ) - if response.headers.get(name) is not None - }, + "security_headers": {name: response.headers[name] for name in ( + "Strict-Transport-Security", "Content-Security-Policy", + "X-Frame-Options", "X-Content-Type-Options") if name in response.headers}, } + except asyncio.CancelledError: + raise except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as exc: - result["http_error"] = str(exc) - + result["http_error"] = type(exc).__name__ return result async def scan_async(self) -> List[Dict[str, Any]]: - """Run the asynchronous scan and return open-port results.""" self.start_time = time.monotonic() await self.resolve() - semaphore = asyncio.Semaphore(self.concurrency) - tasks = [ - asyncio.create_task(self._probe_tcp(port, semaphore)) - for port in self.ports - ] - scanned = await asyncio.gather(*tasks) - - open_results = [ - result for result in scanned if result["state"] == "open" - ] + # A fixed worker pool avoids allocating one Task per port for large scans. + queue: asyncio.Queue = asyncio.Queue(maxsize=max(self.concurrency * 2, 1)) + scanned: List[Dict[str, Any]] = [] + async def worker() -> None: + while True: + port = await queue.get() + try: + if port is None: + return + scanned.append(await self._probe_tcp(port, semaphore)) + finally: + queue.task_done() + + workers = [asyncio.create_task(worker()) for _ in range(min(self.concurrency, max(1, len(self.ports))))] + try: + for port in self.ports: + await queue.put(port) + for _ in workers: + await queue.put(None) + await queue.join() + await asyncio.gather(*workers) + except BaseException: + for task in workers: + task.cancel() + await asyncio.gather(*workers, return_exceptions=True) + raise + + open_results = [r for r in scanned if r["state"] == "open"] if self.check_http and open_results: http_results = [r for r in open_results if r["port"] in HTTP_PORTS] if http_results: - connector = aiohttp.TCPConnector( - limit=self.concurrency, - ssl=False, - ) - timeout = aiohttp.ClientTimeout(total=self.timeout) - async with aiohttp.ClientSession( - connector=connector, - timeout=timeout, - headers={"User-Agent": self.user_agent}, - ) as session: - await asyncio.gather( - *( - self._http_enrich(r, session, semaphore) - for r in http_results - ) - ) - - self.results = open_results + connector = aiohttp.TCPConnector(limit=self.concurrency) + async with aiohttp.ClientSession(connector=connector, + timeout=aiohttp.ClientTimeout(total=self.timeout), + headers={"User-Agent": self.user_agent}) as session: + await asyncio.gather(*(self._http_enrich(r, session, semaphore) for r in http_results)) + self.results = sorted(open_results, key=lambda item: item["port"]) return self.results def scan(self) -> List[Dict[str, Any]]: - """Synchronous compatibility entry point for scripts.""" return asyncio.run(self.scan_async()) def get_results(self) -> Dict[str, Any]: - duration = ( - time.monotonic() - self.start_time - if self.start_time is not None - else 0.0 - ) - return { - "target": self.target, - "resolved_ip": self.resolved_ip, - "scan_type": "async-tcp", - "timestamp": time.time(), - "duration": duration, - "open_ports": self.results, - "vulnerabilities": self.vulnerabilities, - } + return {"target": self.target, "resolved_ip": self.resolved_ip, + "scan_type": "async-tcp", "timestamp": time.time(), + "duration": time.monotonic() - self.start_time if self.start_time is not None else 0.0, + "open_ports": self.results, "vulnerabilities": self.vulnerabilities} @staticmethod def _service_name(port: int) -> str: - services = { - 21: "FTP", - 22: "SSH", - 25: "SMTP", - 53: "DNS", - 80: "HTTP", - 110: "POP3", - 143: "IMAP", - 443: "HTTPS", - 445: "SMB", - 993: "IMAPS", - 995: "POP3S", - 1433: "MSSQL", - 3306: "MySQL", - 3389: "RDP", - 5432: "PostgreSQL", - 5900: "VNC", - 6379: "Redis", - 8080: "HTTP-Alt", - 8443: "HTTPS-Alt", - 27017: "MongoDB", - } - return services.get(port, "unknown") + return {21:"FTP",22:"SSH",25:"SMTP",53:"DNS",80:"HTTP",110:"POP3",143:"IMAP", + 443:"HTTPS",445:"SMB",993:"IMAPS",995:"POP3S",1433:"MSSQL",3306:"MySQL", + 3389:"RDP",5432:"PostgreSQL",5900:"VNC",6379:"Redis",8080:"HTTP-Alt", + 8443:"HTTPS-Alt",27017:"MongoDB"}.get(port, "unknown") -async def scan( - target: str, - ports: Iterable[int], - timeout: float = 1.0, - concurrency: int = 100, - check_http: bool = True, -) -> List[Dict[str, Any]]: - """Small functional API for callers that already run an event loop.""" - scanner = AsyncPortScanner( - target, - ports=ports, - timeout=timeout, - concurrency=concurrency, - check_http=check_http, - ) - return await scanner.scan_async() +async def scan(target: str, ports: Iterable[int], timeout: float = 1.0, + concurrency: int = 100, check_http: bool = True) -> List[Dict[str, Any]]: + return await AsyncPortScanner(target, ports, timeout, concurrency, check_http).scan_async() diff --git a/modules/brute_forcer.py b/modules/brute_forcer.py index 6313d2c..287ce07 100644 --- a/modules/brute_forcer.py +++ b/modules/brute_forcer.py @@ -1,82 +1,122 @@ -import socket -import threading -import queue +"""Credential audit helpers with verified SSH host identity and redacted results.""" import logging +import queue +import threading + +logger = logging.getLogger(__name__) -logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') class BruteForcer: + """Test explicitly authorized credentials; successful records never contain passwords. + + SSH attempts require host keys already present in the user's known_hosts file. + """ def __init__(self, target, port, service, wordlist_path, max_threads=10): - self.target = target - self.port = port - self.service = service - self.wordlist_path = wordlist_path - self.max_threads = max_threads + if not isinstance(max_threads, int) or not 1 <= max_threads <= 64: + raise ValueError("max_threads must be between 1 and 64") + self.target, self.port, self.service = target, int(port), str(service).lower() + if self.service not in {"ssh", "ftp"}: + raise ValueError("service must be 'ssh' or 'ftp'") + self.wordlist_path, self.max_threads = wordlist_path, max_threads self.results = [] + self.errors = [] self.lock = threading.Lock() def load_wordlist(self): try: - with open(self.wordlist_path, 'r', errors='ignore') as f: - return [line.strip() for line in f if line.strip()] - except FileNotFoundError: - logging.error(f"Wordlist not found: {self.wordlist_path}") + with open(self.wordlist_path, "r", encoding="utf-8", errors="ignore") as handle: + return [line.strip() for line in handle if line.strip()] + except OSError as exc: + logger.warning("Cannot read credential wordlist (%s)", type(exc).__name__) + with self.lock: + self.errors.append({"category": "wordlist_error", "reason": type(exc).__name__}) return [] def check_ssh(self, username, password): + client = None try: import paramiko client = paramiko.SSHClient() - client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - client.connect(self.target, port=self.port, username=username, password=password, timeout=2) + client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.RejectPolicy()) + client.connect(self.target, port=self.port, username=username, password=password, + timeout=3, banner_timeout=3, auth_timeout=3, allow_agent=False, + look_for_keys=False) with self.lock: - self.results.append({'status': 'SUCCESS', 'user': username, 'pass': password}) - logging.info(f"[+] SSH Success: {username}:{password}") - client.close() + record = {"status": "SUCCESS", "service": "ssh", "user": username, + "host": self.target, "port": self.port} + if record not in self.results: + self.results.append(record) return True - except Exception: + except Exception as exc: + category = "host_key_error" if exc.__class__.__name__ in { + "BadHostKeyException", "SSHException"} else ( + "authentication_failed" if exc.__class__.__name__ == "AuthenticationException" + else "connection_error") + with self.lock: + self.errors.append({"category": category, "service": "ssh", + "error_type": type(exc).__name__}) return False + finally: + if client is not None: + client.close() def check_ftp(self, username, password): + ftp = None try: import ftplib ftp = ftplib.FTP() - ftp.connect(self.target, self.port, timeout=2) + ftp.connect(self.target, self.port, timeout=3) ftp.login(username, password) with self.lock: - self.results.append({'status': 'SUCCESS', 'user': username, 'pass': password}) - logging.info(f"[+] FTP Success: {username}:{password}") - ftp.quit() + record = {"status": "SUCCESS", "service": "ftp", "user": username, + "host": self.target, "port": self.port} + if record not in self.results: + self.results.append(record) return True - except Exception: + except Exception as exc: + category = "authentication_failed" if isinstance(exc, ftplib.error_perm) else "connection_error" + with self.lock: + self.errors.append({"category": category, "service": "ftp", + "error_type": type(exc).__name__}) return False + finally: + if ftp is not None: + try: + ftp.close() + except Exception: + pass def run(self): wordlist = self.load_wordlist() if not wordlist: - return - + return self.results tasks = queue.Queue() - threads = [] - - def worker(): - while not tasks.empty(): - username, password = tasks.get() - if self.service == 'ssh': - self.check_ssh(username, password) - elif self.service == 'ftp': - self.check_ftp(username, password) - tasks.task_done() - + # Fill queue before workers start; sentinel shutdown is deterministic. + for password in wordlist: + tasks.put(("admin", password)) + tasks.put(("root", password)) for _ in range(self.max_threads): - t = threading.Thread(target=worker) - t.daemon = True - t.start() - threads.append(t) + tasks.put(None) - for pwd in wordlist: - tasks.put(('admin', pwd)) - tasks.put(('root', pwd)) + def worker(): + while True: + task = tasks.get() + try: + if task is None: + return + username, password = task + if self.service == "ssh": + self.check_ssh(username, password) + else: + self.check_ftp(username, password) + finally: + tasks.task_done() + threads = [threading.Thread(target=worker, daemon=True) for _ in range(self.max_threads)] + for thread in threads: + thread.start() tasks.join() - return self.results \ No newline at end of file + for thread in threads: + thread.join() + return self.results diff --git a/modules/vuln_scanner.py b/modules/vuln_scanner.py index 49a26e4..68f2697 100644 --- a/modules/vuln_scanner.py +++ b/modules/vuln_scanner.py @@ -1,33 +1,151 @@ -import requests +"""Evidence-oriented NVD CVE lookup with conservative classification.""" import logging +import time +from urllib.parse import urlencode + +import requests +from packaging.version import InvalidVersion, Version + +logger = logging.getLogger(__name__) +NVD_URL = "https://services.nvd.nist.gov/rest/json/cves/2.0" + + +def _severity(cve): + metrics = cve.get("metrics") or {} + for key in ("cvssMetricV40", "cvssMetricV31", "cvssMetricV30", "cvssMetricV2"): + entries = metrics.get(key) + if isinstance(entries, list) and entries: + data = entries[0].get("cvssData") or {} + value = data.get("baseSeverity") or data.get("baseScore") + if value is not None: + return value + return "UNKNOWN" + + +def _description(cve): + for item in cve.get("descriptions") or []: + if item.get("lang") == "en" and isinstance(item.get("value"), str): + return item["value"][:1000] + return "" -logging.basicConfig(level=logging.WARNING) class VulnScanner: - def __init__(self, service_name, version): - self.service = service_name.lower() - self.version = version + def __init__(self, service_name, version, vendor=None, product=None, cpe_name=None, + session=None, max_pages=10, sleep=time.sleep): + self.service = str(service_name or "").strip().lower() + self.version = str(version or "").strip() + self.vendor = str(vendor or "").strip().lower() or None + self.product = str(product or service_name or "").strip().lower() or None + self.cpe_name = cpe_name self.cves = [] + self.errors = [] + self.session = session or requests.Session() + self.max_pages = max(1, min(int(max_pages), 100)) + self.sleep = sleep + + def _matches_cpe(self, cve): + configurations = cve.get("configurations") or [] + if not configurations: + return None + terms = [] + def walk(node): + for match in node.get("cpeMatch") or []: + if match.get("vulnerable") and match.get("criteria"): + terms.append(match) + for child in node.get("children") or []: + walk(child) + for config in configurations: + for node in config.get("nodes") or []: + walk(node) + if not terms: + return None + if self.cpe_name: + terms = [term for term in terms if term.get("criteria") == self.cpe_name] + elif self.product: + needle = self.product.replace(" ", "_") + terms = [term for term in terms if needle in term.get("criteria", "").lower()] + if self.vendor: + terms = [term for term in terms if self.vendor.replace(" ", "_") in term.get("criteria", "").lower()] + else: + return None + if not terms: + return False + if not self.version: + return None + for term in terms: + criteria = term.get("criteria", "") + parts = criteria.split(":") + cpe_version = parts[5] if len(parts) > 5 else "*" + start_inc, start_exc = term.get("versionStartIncluding"), term.get("versionStartExcluding") + end_inc, end_exc = term.get("versionEndIncluding"), term.get("versionEndExcluding") + try: + detected = Version(self.version) + if cpe_version not in {"*", "-", ""}: + return detected == Version(cpe_version) + if start_inc and detected < Version(start_inc): + continue + if start_exc and detected <= Version(start_exc): + continue + if end_inc and detected > Version(end_inc): + continue + if end_exc and detected >= Version(end_exc): + continue + if any((start_inc, start_exc, end_inc, end_exc)): + return True + except InvalidVersion: + # Version schemes that packaging cannot parse must not be confirmed. + return None + return False def check_nvd_api(self): - url = f"https://services.nvd.nist.gov/rest/json/cves/2.0?keywordSearch={self.service}&versionStartInclude={self.version}" - headers = {'Accept': 'application/json'} - try: - response = requests.get(url, headers=headers, timeout=5) - if response.status_code == 200: + self.cves = [] + params = {"cpeName": self.cpe_name} if self.cpe_name else {"keywordSearch": " ".join(x for x in (self.vendor, self.product, self.service, self.version) if x)} + start_index = 0 + seen = set() + for _ in range(self.max_pages): + try: + response = self.session.get(NVD_URL, params={**params, "startIndex": start_index, "resultsPerPage": 100}, + headers={"Accept": "application/json"}, timeout=(3.05, 15)) + if response.status_code == 429: + retry = response.headers.get("Retry-After", "2") + try: + self.sleep(min(max(float(retry), 1), 30)) + except (TypeError, ValueError): + self.sleep(2) + response = self.session.get(NVD_URL, params={**params, "startIndex": start_index, "resultsPerPage": 100}, + headers={"Accept": "application/json"}, timeout=(3.05, 15)) + response.raise_for_status() data = response.json() - for item in data.get('vulnerabilities', []): - cve_id = item['cve']['id'] - severity = item['cve']['metrics']['cvssMetricV3'][0]['cvssData']['baseSeverity'] - self.cves.append({ - 'id': cve_id, - 'severity': severity, - 'description': item['cve']['descriptions'][0]['value'][:100] - }) - else: - logging.warning(f"NVD API Error: {response.status_code}") - except Exception as e: - logging.error(f"API Request Failed: {e}") + entries = data.get("vulnerabilities") + if not isinstance(entries, list): + raise ValueError("NVD response has no valid vulnerabilities list") + except (requests.RequestException, ValueError, TypeError) as exc: + self.errors.append({"category": "nvd_api_error", "error_type": type(exc).__name__}) + logger.warning("NVD query failed (%s)", type(exc).__name__) + break + + for item in entries: + cve = item.get("cve") if isinstance(item, dict) else None + if not isinstance(cve, dict): + continue + cve_id = cve.get("id") + if not cve_id or cve_id in seen: + continue + seen.add(cve_id) + match = self._matches_cpe(cve) + classification = "confirmed" if match is True else "potential" if match is None else "informational" + self.cves.append({"id": cve_id, "severity": _severity(cve), + "description": _description(cve), "classification": classification, + "evidence": {"vendor": self.vendor, "product": self.product, + "detected_version": self.version, "cpe_name": self.cpe_name}, + "reason": ("CPE and detected version match available evidence" if match is True else + "Search result; affected version could not be confirmed" if match is None else + "No matching vulnerable CPE found for the supplied product")}) + total = data.get("totalResults", len(entries)) + start_index += len(entries) + if not entries or start_index >= total: + break + return self.cves def get_results(self): - return self.cves \ No newline at end of file + return list(self.cves) diff --git a/requirements.txt b/requirements.txt index 24a36b7..5847ed7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,6 +9,7 @@ scapy python-nmap paramiko requests +packaging>=23.2 fpdf pyyaml rich>=13.0 diff --git a/tests/test_brute_forcer.py b/tests/test_brute_forcer.py new file mode 100644 index 0000000..4f0af0f --- /dev/null +++ b/tests/test_brute_forcer.py @@ -0,0 +1,39 @@ +import tempfile +import threading +import unittest +from pathlib import Path +from unittest.mock import patch + +from modules.brute_forcer import BruteForcer + + +class TestBruteForcerQueue(unittest.TestCase): + def test_all_queued_credentials_are_processed_and_results_are_redacted(self): + with tempfile.TemporaryDirectory() as temp: + wordlist = Path(temp) / "passwords.txt" + wordlist.write_text("one\ntwo\n", encoding="utf-8") + scanner = BruteForcer("127.0.0.1", 22, "ssh", str(wordlist), max_threads=3) + attempted = [] + lock = threading.Lock() + + def fake_check(username, password): + with lock: + attempted.append((username, password)) + scanner.results.append({"status": "SUCCESS", "service": "ssh", + "user": username, "host": scanner.target, + "port": scanner.port}) + return True + + with patch.object(scanner, "check_ssh", side_effect=fake_check): + results = scanner.run() + + self.assertCountEqual(attempted, [ + ("admin", "one"), ("root", "one"), + ("admin", "two"), ("root", "two") + ]) + self.assertEqual(len(results), 4) + self.assertTrue(all("pass" not in result and "password" not in result for result in results)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cli_integration.py b/tests/test_cli_integration.py new file mode 100644 index 0000000..a5ea937 --- /dev/null +++ b/tests/test_cli_integration.py @@ -0,0 +1,55 @@ +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "SpectraScan.py" + + +class TestCliIntegration(unittest.TestCase): + def run_cli(self, *args): + env = os.environ.copy() + env["PYTHONPATH"] = str(ROOT) + os.pathsep + env.get("PYTHONPATH", "") + return subprocess.run([sys.executable, str(SCRIPT), *args], cwd=ROOT, + env=env, capture_output=True, text=True, timeout=30) + + def test_unknown_arguments_are_rejected(self): + result = self.run_cli("--target", "127.0.0.1", "--not-a-real-option") + self.assertNotEqual(result.returncode, 0) + self.assertIn("unrecognized arguments", result.stderr) + + def test_invalid_ports_are_rejected(self): + result = self.run_cli("--target", "127.0.0.1", "--ports", "80,nope") + self.assertNotEqual(result.returncode, 0) + self.assertIn("invalid --ports", result.stderr) + + def test_tcp_scan_honors_port_selection_and_writes_json(self): + with tempfile.TemporaryDirectory() as temp: + output = Path(temp) / "scan.json" + result = self.run_cli("--target", "127.0.0.1", "--ports", "1", + "--timeout", "0.1", "--output", str(output)) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + self.assertTrue(output.exists()) + report = json.loads(output.read_text(encoding="utf-8")) + self.assertEqual(report["target"], "127.0.0.1") + self.assertEqual(report["scan_type"], "tcp") + self.assertTrue(all(item["port"] == 1 for item in report["open_ports"])) + + def test_udp_scan_type_is_recorded_and_exported(self): + with tempfile.TemporaryDirectory() as temp: + output = Path(temp) / "udp.json" + result = self.run_cli("--target", "127.0.0.1", "--ports", "1", + "--scan-type", "udp", "--timeout", "0.1", + "--output", str(output)) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + report = json.loads(output.read_text(encoding="utf-8")) + self.assertEqual(report["scan_type"], "udp") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_report_exports.py b/tests/test_report_exports.py new file mode 100644 index 0000000..f79bfd8 --- /dev/null +++ b/tests/test_report_exports.py @@ -0,0 +1,40 @@ +import csv +import tempfile +import unittest +from pathlib import Path + +from SpectraScan import PortScanner, ReportManager + + +class TestReportExports(unittest.TestCase): + def test_csv_formula_payload_is_neutralized(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "report.csv" + scanner = PortScanner("127.0.0.1", ports=[80]) + scanner.results = [{"port": 80, "state": "open", "service": "http", + "banner": "=HYPERLINK(\"https://example.invalid\")", + "vulnerabilities": []}] + scanner.export_csv(str(path)) + with path.open(encoding="utf-8", newline="") as handle: + rows = list(csv.reader(handle)) + self.assertTrue(rows[1][4].startswith("'=")) + + def test_report_directory_respects_environment(self): + import os + with tempfile.TemporaryDirectory() as temp: + old = os.environ.get("SPECTRASCAN_HOME") + os.environ["SPECTRASCAN_HOME"] = temp + try: + manager = ReportManager() + self.assertEqual(Path(manager.report_dir), Path(temp)) + self.assertEqual(manager.save_output("atomic.txt", "safe"), str(Path(temp) / "atomic.txt")) + self.assertEqual((Path(temp) / "atomic.txt").read_text(encoding="utf-8"), "safe") + finally: + if old is None: + os.environ.pop("SPECTRASCAN_HOME", None) + else: + os.environ["SPECTRASCAN_HOME"] = old + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vuln_scanner.py b/tests/test_vuln_scanner.py new file mode 100644 index 0000000..ada2e47 --- /dev/null +++ b/tests/test_vuln_scanner.py @@ -0,0 +1,27 @@ +import unittest +from unittest.mock import Mock + +from modules.vuln_scanner import VulnScanner, _severity + + +class TestVulnScanner(unittest.TestCase): + def test_handles_missing_cvss_metrics(self): + self.assertEqual(_severity({"metrics": {}}), "UNKNOWN") + + def test_keyword_result_is_not_confirmed_without_cpe_evidence(self): + scanner = VulnScanner("nginx", "1.2.3", session=Mock()) + self.assertIsNone(scanner._matches_cpe({"configurations": []})) + + def test_malformed_api_response_is_structured_error(self): + session = Mock() + response = Mock() + response.raise_for_status.return_value = None + response.json.return_value = {"vulnerabilities": "not-a-list"} + session.get.return_value = response + scanner = VulnScanner("nginx", "1.2.3", session=session) + self.assertEqual(scanner.check_nvd_api(), []) + self.assertEqual(scanner.errors[0]["category"], "nvd_api_error") + + +if __name__ == "__main__": + unittest.main()