Buckets:

download
raw
94.6 kB
""" Pentest Engine - Core orchestration engine for the pentest lifecycle. Manages phases: Reconnaissance -> Scanning -> Exploitation -> Post-Exploitation -> Reporting Integrates with MCP Server for tool execution and AI for decision making. Author: AI-Pentest-Framework Version: 1.0.0 """ import asyncio import hashlib import json import logging import subprocess import time import uuid from dataclasses import asdict, dataclass, field from datetime import datetime from enum import Enum, auto from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple # Configure logging logger = logging.getLogger("pentest_engine") class PentestPhase(Enum): """Enumeration of all pentest lifecycle phases.""" INITIALIZATION = auto() SCOPE_VALIDATION = auto() RECONNAISSANCE = auto() SCANNING = auto() EXPLOITATION = auto() POST_EXPLOITATION = auto() ANALYSIS = auto() REPORTING = auto() COMPLETED = auto() ERROR = auto() PAUSED = auto() class PentestStatus(Enum): """Enumeration of pentest session status values.""" PENDING = "pending" RUNNING = "running" COMPLETED = "completed" FAILED = "failed" PAUSED = "paused" CANCELLED = "cancelled" class SeverityLevel(Enum): """CVSS severity classification levels.""" CRITICAL = "critical" HIGH = "high" MEDIUM = "medium" LOW = "low" INFO = "info" @dataclass class Target: """ Represents a target for penetration testing. Attributes: host: Target hostname or IP address. ip: Resolved IP address (filled during recon). ports: List of discovered open ports. scope_type: Type of testing scope - blackbox, greybox, or whitebox. auth_creds: Optional authentication credentials for greybox/whitebox. tech_stack: Detected technologies on the target. """ host: str ip: Optional[str] = None ports: List[int] = field(default_factory=list) scope_type: str = "blackbox" # blackbox, greybox, whitebox auth_creds: Optional[Dict[str, str]] = None tech_stack: List[str] = field(default_factory=list) def to_dict(self) -> Dict[str, Any]: """Convert target to dictionary representation.""" return { "host": self.host, "ip": self.ip, "ports": self.ports, "scope_type": self.scope_type, "auth_creds": "***redacted***" if self.auth_creds else None, "tech_stack": self.tech_stack, } @dataclass class Finding: """ Represents a security finding discovered during pentesting. Attributes: id: Unique identifier for the finding. title: Human-readable title of the finding. severity: Severity classification (critical/high/medium/low/info). cvss_score: CVSS base score (0.0-10.0). cvss_vector: CVSS vector string (e.g., CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H). epss_score: EPSS probability score (0.0-1.0). description: Detailed description of the vulnerability. evidence: List of evidence files or screenshots. remediation: Recommended remediation steps. references: External references (CVE, CWE, etc.). tool_source: Tool that discovered the finding. confirmed: Whether the finding is manually confirmed. timestamp: ISO timestamp when the finding was created. """ id: str title: str severity: str # critical, high, medium, low, info cvss_score: float cvss_vector: str epss_score: Optional[float] = None description: str = "" evidence: List[str] = field(default_factory=list) remediation: str = "" references: List[str] = field(default_factory=list) tool_source: str = "" confirmed: bool = False timestamp: str = field(default_factory=lambda: datetime.now().isoformat()) def to_dict(self) -> Dict[str, Any]: """Convert finding to dictionary representation.""" return { "id": self.id, "title": self.title, "severity": self.severity, "cvss_score": self.cvss_score, "cvss_vector": self.cvss_vector, "epss_score": self.epss_score, "description": self.description, "evidence": self.evidence, "remediation": self.remediation, "references": self.references, "tool_source": self.tool_source, "confirmed": self.confirmed, "timestamp": self.timestamp, } @dataclass class AuditLogEntry: """Represents a single audit log entry for compliance tracking.""" timestamp: str phase: str action: str details: Dict[str, Any] tool_used: str approved_by: str = "auto" def to_dict(self) -> Dict[str, Any]: """Convert audit log entry to dictionary.""" return { "timestamp": self.timestamp, "phase": self.phase, "action": self.action, "details": self.details, "tool_used": self.tool_used, "approved_by": self.approved_by, } @dataclass class PentestSession: """ Represents an active penetration testing session. Attributes: session_id: Unique session identifier. target: Target object containing target details. phase: Current pentest phase. status: Current session status. findings: List of discovered findings. recon_data: Collected reconnaissance data. scan_results: Results from vulnerability scanning. exploit_results: Results from exploitation attempts. ai_recommendations: AI-generated recommendations. audit_log: Compliance audit log entries. start_time: ISO timestamp when session started. end_time: ISO timestamp when session ended (if completed). auth_token: Authentication token for session. scope_verified: Whether scope validation passed. compliance_passed: Whether compliance checks passed. config: Session-specific configuration overrides. """ session_id: str target: Target phase: PentestPhase = PentestPhase.INITIALIZATION status: PentestStatus = PentestStatus.PENDING findings: List[Finding] = field(default_factory=list) recon_data: Dict[str, Any] = field(default_factory=dict) scan_results: Dict[str, Any] = field(default_factory=dict) exploit_results: Dict[str, Any] = field(default_factory=dict) ai_recommendations: List[str] = field(default_factory=list) audit_log: List[AuditLogEntry] = field(default_factory=list) start_time: str = field(default_factory=lambda: datetime.now().isoformat()) end_time: Optional[str] = None auth_token: str = "" scope_verified: bool = False compliance_passed: bool = False config: Dict[str, Any] = field(default_factory=dict) def to_dict(self) -> Dict[str, Any]: """Convert session to dictionary representation.""" return { "session_id": self.session_id, "target": self.target.to_dict(), "phase": self.phase.name, "status": self.status.value, "findings_count": len(self.findings), "findings": [f.to_dict() for f in self.findings], "recon_data": self.recon_data, "scan_results": self.scan_results, "exploit_results": self.exploit_results, "ai_recommendations": self.ai_recommendations, "audit_log": [entry.to_dict() for entry in self.audit_log], "start_time": self.start_time, "end_time": self.end_time, "auth_token": "***redacted***" if self.auth_token else "", "scope_verified": self.scope_verified, "compliance_passed": self.compliance_passed, } class PentestEngine: """ Core pentest engine managing the complete lifecycle. Orchestrates all phases of a penetration test from initialization through reporting, integrating with MCP tools and AI decision-making. Attributes: config: Engine configuration dictionary. sessions: Active pentest sessions keyed by session ID. phase_handlers: Mapping of phases to handler methods. tool_paths: Paths to installed security tools. ai_enabled: Whether AI decision-making is enabled. Example: >>> engine = PentestEngine(config={"ai_enabled": True}) >>> session = await engine.create_session(target=Target(host="example.com"), auth_token="token123") >>> results = await engine.run_full_pentest(session.session_id) """ SEVERITY_ORDER = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0} REQUIRED_TOOLS = [ "subfinder", "katana", "httpx", "nmap", "nuclei", "zap-cli", "nikto", "sqlmap", "searchsploit", ] def __init__(self, config: Optional[Dict[str, Any]] = None) -> None: """ Initialize the Pentest Engine. Args: config: Configuration dictionary with optional settings: - ai_enabled: Enable AI decision-making (default: True) - auto_approve_low_risk: Auto-approve low-risk exploits (default: False) - tool_timeout: Default timeout for tool execution in seconds (default: 300) - max_concurrent_tools: Maximum concurrent tool executions (default: 3) - output_dir: Directory for output files (default: ./output) - scope_file: Path to scope definition file """ self.config = config or {} self.logger = logging.getLogger("pentest_engine") self.sessions: Dict[str, PentestSession] = {} self.phase_handlers: Dict[PentestPhase, Any] = { PentestPhase.INITIALIZATION: self._phase_init, PentestPhase.SCOPE_VALIDATION: self._phase_scope_validation, PentestPhase.RECONNAISSANCE: self._phase_recon, PentestPhase.SCANNING: self._phase_scanning, PentestPhase.EXPLOITATION: self._phase_exploitation, PentestPhase.POST_EXPLOITATION: self._phase_post_exploit, PentestPhase.ANALYSIS: self._phase_analysis, PentestPhase.REPORTING: self._phase_reporting, } self.tool_paths: Dict[str, str] = {} self.ai_enabled: bool = self.config.get("ai_enabled", True) self.auto_approve_low_risk: bool = self.config.get("auto_approve_low_risk", False) self.tool_timeout: int = self.config.get("tool_timeout", 300) self.max_concurrent_tools: int = self.config.get("max_concurrent_tools", 3) self.output_dir: Path = Path(self.config.get("output_dir", "./output")) self.output_dir.mkdir(parents=True, exist_ok=True) self._semaphore = asyncio.Semaphore(self.max_concurrent_tools) self.logger.info( f"PentestEngine initialized | AI: {self.ai_enabled} | " f"Auto-approve: {self.auto_approve_low_risk} | " f"Timeout: {self.tool_timeout}s | Concurrent: {self.max_concurrent_tools}" ) async def create_session(self, target: Target, auth_token: str) -> PentestSession: """ Create a new pentest session with scope validation. Args: target: Target object containing host and scope information. auth_token: Authentication token for the session. Returns: PentestSession: The newly created session. Raises: ValueError: If target host is empty or invalid. """ if not target or not target.host: raise ValueError("Target host is required") session_id = str(uuid.uuid4())[:8] session = PentestSession( session_id=session_id, target=target, auth_token=auth_token, config=self.config.copy(), ) self.sessions[session_id] = session self.logger.info(f"Session {session_id} created | Target: {target.host} | Scope: {target.scope_type}") self._write_audit_log(session, "SESSION_CREATED", {"target": target.host, "scope_type": target.scope_type}, "engine") return session async def run_phase(self, session_id: str, phase: PentestPhase) -> Dict[str, Any]: """ Execute a specific pentest phase. Args: session_id: The session identifier. phase: The pentest phase to execute. Returns: Dictionary containing phase execution results. Raises: ValueError: If session or phase handler not found. RuntimeError: If session is in an invalid state. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] if session.status == PentestStatus.CANCELLED: raise RuntimeError(f"Session {session_id} is cancelled") if phase not in self.phase_handlers: raise ValueError(f"No handler for phase: {phase.name}") session.phase = phase session.status = PentestStatus.RUNNING self.logger.info(f"Session {session_id}: Starting phase {phase.name}") try: handler = self.phase_handlers[phase] result = await handler(session) if session.status != PentestStatus.PAUSED: session.status = PentestStatus.COMPLETED self.logger.info(f"Session {session_id}: Phase {phase.name} completed | Findings: {len(session.findings)}") return result except Exception as e: session.phase = PentestPhase.ERROR session.status = PentestStatus.FAILED self.logger.error(f"Session {session_id}: Phase {phase.name} failed - {str(e)}") raise RuntimeError(f"Phase {phase.name} failed: {str(e)}") from e async def run_full_pentest(self, session_id: str) -> Dict[str, Any]: """ Run the complete pentest lifecycle from initialization to reporting. Args: session_id: The session identifier. Returns: Dictionary containing complete pentest results. Raises: ValueError: If session not found. RuntimeError: If any phase fails critically. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] phase_order = [ PentestPhase.INITIALIZATION, PentestPhase.SCOPE_VALIDATION, PentestPhase.RECONNAISSANCE, PentestPhase.SCANNING, PentestPhase.EXPLOITATION, PentestPhase.POST_EXPLOITATION, PentestPhase.ANALYSIS, PentestPhase.REPORTING, ] self.logger.info(f"Session {session_id}: Starting full pentest lifecycle") results: Dict[str, Any] = {"session_id": session_id, "phases": {}} for phase in phase_order: if session.status == PentestStatus.CANCELLED: self.logger.warning(f"Session {session_id}: Pentest cancelled") results["cancelled_at"] = phase.name break while session.status == PentestStatus.PAUSED: self.logger.info(f"Session {session_id}: Waiting for resume...") await asyncio.sleep(5) try: phase_result = await self.run_phase(session_id, phase) results["phases"][phase.name] = phase_result except RuntimeError as e: if phase in (PentestPhase.INITIALIZATION, PentestPhase.SCOPE_VALIDATION): self.logger.error(f"Session {session_id}: Critical phase failed - {str(e)}") raise self.logger.warning(f"Session {session_id}: Phase {phase.name} failed - {str(e)}") results["phases"][phase.name] = {"status": "failed", "error": str(e)} if session.status not in (PentestStatus.CANCELLED, PentestStatus.PAUSED): session.phase = PentestPhase.COMPLETED session.end_time = datetime.now().isoformat() session.status = PentestStatus.COMPLETED results["final_status"] = session.status.value results["findings_count"] = len(session.findings) results["end_time"] = session.end_time self.logger.info( f"Session {session_id}: Full pentest completed | " f"Status: {session.status.value} | Findings: {len(session.findings)}" ) return results async def _execute_tool( self, command: List[str], session: PentestSession, timeout: Optional[int] = None, env: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: """ Execute a security tool via subprocess with semaphore-controlled concurrency. Args: command: Command and arguments as list. session: Current pentest session for audit logging. timeout: Optional timeout override (seconds). env: Optional environment variables. Returns: Dictionary with stdout, stderr, returncode, and execution time. """ async with self._semaphore: tool_name = command[0] if command else "unknown" timeout_val = timeout or self.tool_timeout start_time = time.time() self.logger.debug(f"Executing: {' '.join(command)}") try: process = await asyncio.create_subprocess_exec( *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env, ) stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_val) exec_time = time.time() - start_time result = { "tool": tool_name, "command": " ".join(command), "stdout": stdout.decode("utf-8", errors="replace"), "stderr": stderr.decode("utf-8", errors="replace"), "returncode": process.returncode, "execution_time": round(exec_time, 2), } self._write_audit_log( session, "TOOL_EXECUTED", {"tool": tool_name, "returncode": process.returncode, "duration": exec_time}, tool_name, ) self.logger.info(f"Tool {tool_name} completed | RC: {process.returncode} | Time: {exec_time:.2f}s") return result except asyncio.TimeoutError: exec_time = time.time() - start_time self.logger.warning(f"Tool {tool_name} timed out after {timeout_val}s") if process and process.returncode is None: process.kill() return { "tool": tool_name, "command": " ".join(command), "stdout": "", "stderr": f"Timeout after {timeout_val} seconds", "returncode": -1, "execution_time": round(exec_time, 2), } except Exception as e: self.logger.error(f"Tool {tool_name} execution failed: {str(e)}") return { "tool": tool_name, "command": " ".join(command), "stdout": "", "stderr": str(e), "returncode": -1, "execution_time": 0, } def _create_finding( self, session: PentestSession, title: str, severity: str, cvss_score: float, cvss_vector: str, description: str, tool_source: str, remediation: str = "", references: Optional[List[str]] = None, epss_score: Optional[float] = None, evidence: Optional[List[str]] = None, ) -> Finding: """ Create and register a new security finding. Args: session: Current pentest session. title: Finding title. severity: Severity level string. cvss_score: CVSS score (0.0-10.0). cvss_vector: CVSS vector string. description: Detailed description. tool_source: Tool that discovered the finding. remediation: Remediation recommendation. references: External references. epss_score: EPSS probability score. evidence: Evidence file paths. Returns: The created Finding object. """ finding_id = f"FIND-{session.session_id}-{len(session.findings) + 1:04d}" finding = Finding( id=finding_id, title=title, severity=severity.lower(), cvss_score=cvss_score, cvss_vector=cvss_vector, epss_score=epss_score, description=description, evidence=evidence or [], remediation=remediation, references=references or [], tool_source=tool_source, ) session.findings.append(finding) self.logger.info( f"New finding: {finding_id} | {title} | Severity: {severity} | CVSS: {cvss_score} | Source: {tool_source}" ) self._write_audit_log( session, "FINDING_DISCOVERED", { "finding_id": finding_id, "title": title, "severity": severity, "cvss_score": cvss_score, "tool": tool_source, }, tool_source, ) return finding def _write_audit_log( self, session: PentestSession, action: str, details: Dict[str, Any], tool_used: str, approved_by: str = "auto", ) -> None: """Write an entry to the session audit log.""" entry = AuditLogEntry( timestamp=datetime.now().isoformat(), phase=session.phase.name, action=action, details=details, tool_used=tool_used, approved_by=approved_by, ) session.audit_log.append(entry) def _check_pause_or_cancel(self, session: PentestSession) -> bool: """Check if session is paused or cancelled. Returns True if should abort.""" return session.status in (PentestStatus.PAUSED, PentestStatus.CANCELLED) async def _phase_init(self, session: PentestSession) -> Dict[str, Any]: """ Initialize session, verify tools, load configuration. Args: session: Current pentest session. Returns: Dictionary with initialization results. """ self.logger.info(f"Session {session.session_id}: Phase - Initialization") results: Dict[str, Any] = { "phase": "initialization", "tool_verification": {}, "config_loaded": False, "errors": [], } # Verify required tools for tool in self.REQUIRED_TOOLS: try: proc = await asyncio.create_subprocess_exec( "which", tool, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, _ = await proc.communicate() tool_path = stdout.decode().strip() if tool_path: self.tool_paths[tool] = tool_path results["tool_verification"][tool] = {"available": True, "path": tool_path} self.logger.debug(f"Tool found: {tool} at {tool_path}") else: results["tool_verification"][tool] = {"available": False, "path": None} results["errors"].append(f"Tool not found: {tool}") self.logger.warning(f"Tool missing: {tool}") except Exception as e: results["tool_verification"][tool] = {"available": False, "error": str(e)} results["errors"].append(f"Tool check failed for {tool}: {str(e)}") # Load session configuration scope_file = session.config.get("scope_file") or self.config.get("scope_file") if scope_file and Path(scope_file).exists(): try: with open(scope_file, "r") as f: scope_data = json.load(f) session.config.update(scope_data) results["config_loaded"] = True self.logger.info(f"Scope config loaded from {scope_file}") except Exception as e: results["errors"].append(f"Failed to load scope file: {str(e)}") self.logger.error(f"Failed to load scope config: {str(e)}") results["tools_available"] = sum(1 for v in results["tool_verification"].values() if v.get("available")) results["tools_required"] = len(self.REQUIRED_TOOLS) results["status"] = "completed" if results["tools_available"] > 0 else "failed" self._write_audit_log( session, "PHASE_COMPLETED", {"phase": "initialization", "tools_available": results["tools_available"]}, "engine", ) return results async def _phase_scope_validation(self, session: PentestSession) -> Dict[str, Any]: """ Validate target scope and compliance rules. Performs DNS resolution, ownership verification, and compliance rule checking. Args: session: Current pentest session. Returns: Dictionary with scope validation results. """ self.logger.info(f"Session {session.session_id}: Phase - Scope Validation") results: Dict[str, Any] = { "phase": "scope_validation", "target": session.target.host, "dns_resolved": False, "ip_address": None, "scope_included": False, "compliance_passed": False, "errors": [], } try: # DNS Resolution nslookup_cmd = ["nslookup", session.target.host] ns_result = await self._execute_tool(nslookup_cmd, session, timeout=30) if ns_result["returncode"] == 0: import re ip_match = re.search(r"Address:\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)", ns_result["stdout"]) if ip_match: session.target.ip = ip_match.group(1) results["ip_address"] = session.target.ip results["dns_resolved"] = True self.logger.info(f"DNS resolved: {session.target.host} -> {session.target.ip}") if not results["dns_resolved"]: # Fallback: use host command host_cmd = ["host", session.target.host] host_result = await self._execute_tool(host_cmd, session, timeout=30) if host_result["returncode"] == 0: import re ip_match = re.search(r"has address (\\d+\\.\\d+\\.\\d+\\.\\d+)", host_result["stdout"]) if ip_match: session.target.ip = ip_match.group(1) results["ip_address"] = session.target.ip results["dns_resolved"] = True except Exception as e: results["errors"].append(f"DNS resolution failed: {str(e)}") self.logger.error(f"DNS resolution failed: {str(e)}") # Validate scope allowed_domains = session.config.get("allowed_domains", []) excluded_hosts = session.config.get("excluded_hosts", []) target_host = session.target.host.lower() # Check exclusions if any(excl.lower() in target_host for excl in excluded_hosts): results["scope_included"] = False results["errors"].append(f"Target {target_host} is in exclusion list") self.logger.error(f"Target excluded: {target_host}") # Check inclusions elif not allowed_domains or any(domain.lower() in target_host for domain in allowed_domains): results["scope_included"] = True session.scope_verified = True else: results["scope_included"] = False results["errors"].append(f"Target {target_host} not in allowed domains") self.logger.error(f"Target not in scope: {target_host}") # Compliance check compliance_rules = session.config.get("compliance_rules", {}) if compliance_rules: results["compliance_passed"] = True for rule_name, rule_value in compliance_rules.items(): if rule_name == "max_cvss_threshold" and rule_value < 0: results["compliance_passed"] = False results["errors"].append("Invalid compliance configuration") session.compliance_passed = results["compliance_passed"] else: results["compliance_passed"] = True session.compliance_passed = True results["status"] = "completed" if results["scope_included"] and results["compliance_passed"] else "failed" self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "scope_validation", "dns_resolved": results["dns_resolved"], "scope_included": results["scope_included"], "compliance_passed": results["compliance_passed"], }, "nslookup", ) return results async def _phase_recon(self, session: PentestSession) -> Dict[str, Any]: """ Run reconnaissance phase using multiple tools. Tools: subfinder, katana, httpx, nmap, whois, dig Collects subdomains, endpoints, technologies, and port information. Args: session: Current pentest session. Returns: Dictionary with reconnaissance results. """ self.logger.info(f"Session {session.session_id}: Phase - Reconnaissance") target = session.target.host output_prefix = str(self.output_dir / f"{session.session_id}_recon") results: Dict[str, Any] = { "phase": "reconnaissance", "subdomains": [], "endpoints": [], "technologies": [], "open_ports": [], "dns_records": {}, "whois_info": {}, "errors": [], } tasks = [] # Task 1: Subfinder - subdomain enumeration if "subfinder" in self.tool_paths: subfinder_cmd = ["subfinder", "-d", target, "-o", f"{output_prefix}_subdomains.txt", "-all", "-silent"] tasks.append(self._execute_tool(subfinder_cmd, session, timeout=120)) # Task 2: Katana - endpoint crawling if "katana" in self.tool_paths: katana_cmd = ["katana", "-u", f"https://{target}", "-o", f"{output_prefix}_endpoints.txt", "-silent", "-d", "3"] tasks.append(self._execute_tool(katana_cmd, session, timeout=180)) # Task 3: Nmap - port scanning nmap_cmd = [ "nmap", "-sS", "-sV", "-O", "--top-ports", "1000", "-oX", f"{output_prefix}_nmap.xml", "-oN", f"{output_prefix}_nmap.txt", session.target.ip or target, ] tasks.append(self._execute_tool(nmap_cmd, session, timeout=300)) # Task 4: DNS records dig_cmd = ["dig", "+nocmd", target, "ANY", "+noall", "+answer"] tasks.append(self._execute_tool(dig_cmd, session, timeout=30)) # Execute all recon tasks concurrently task_results = await asyncio.gather(*tasks, return_exceptions=True) # Process subfinder results subfinder_file = f"{output_prefix}_subdomains.txt" if Path(subfinder_file).exists(): with open(subfinder_file, "r") as f: subdomains = [line.strip() for line in f if line.strip()] results["subdomains"] = subdomains session.recon_data["subdomains"] = subdomains self.logger.info(f"Discovered {len(subdomains)} subdomains") # Process katana results katana_file = f"{output_prefix}_endpoints.txt" if Path(katana_file).exists(): with open(katana_file, "r") as f: endpoints = [line.strip() for line in f if line.strip()] results["endpoints"] = endpoints session.recon_data["endpoints"] = endpoints self.logger.info(f"Discovered {len(endpoints)} endpoints") # Process nmap results nmap_file = f"{output_prefix}_nmap.txt" if Path(nmap_file).exists(): with open(nmap_file, "r") as f: nmap_output = f.read() results["nmap_raw"] = nmap_output session.recon_data["nmap_raw"] = nmap_output # Parse open ports import re port_pattern = r"(\\d+)/(tcp|udp)\\s+(open|filtered|closed)\\s+(\\S+)" port_matches = re.findall(port_pattern, nmap_output) for match in port_matches: port_num = int(match[0]) port_state = match[2] port_service = match[3] if port_state == "open": results["open_ports"].append( { "port": port_num, "service": port_service, "protocol": match[1], } ) if port_num not in session.target.ports: session.target.ports.append(port_num) self.logger.info(f"Discovered {len(results['open_ports'])} open ports") # Process DNS results for task_result in task_results: if isinstance(task_result, dict) and task_result.get("tool") == "dig": results["dns_records"]["raw"] = task_result["stdout"] session.recon_data["dns_records"] = results["dns_records"] # HTTPX - Probe discovered endpoints if results["subdomains"] and "httpx" in self.tool_paths: subdomains_file = f"{output_prefix}_subdomains.txt" httpx_cmd = [ "httpx", "-l", subdomains_file, "-o", f"{output_prefix}_httpx.json", "-json", "-silent", "-tech-detect", "-status-code", "-title", ] httpx_result = await self._execute_tool(httpx_cmd, session, timeout=120) httpx_file = f"{output_prefix}_httpx.json" if Path(httpx_file).exists(): try: with open(httpx_file, "r") as f: for line in f: if line.strip(): httpx_data = json.loads(line) if "tech" in httpx_data: for tech in httpx_data["tech"]: if tech not in results["technologies"]: results["technologies"].append(tech) if tech not in session.target.tech_stack: session.target.tech_stack.append(tech) if "status_code" in httpx_data: results.setdefault("http_status", []).append( { "url": httpx_data.get("url", ""), "status": httpx_data["status_code"], "title": httpx_data.get("title", ""), } ) except json.JSONDecodeError: self.logger.warning("Failed to parse httpx JSON output") # Store recon data in session session.recon_data.update(results) # Create informational findings if results["open_ports"]: self._create_finding( session=session, title=f"Open Ports Discovered on {target}", severity="info", cvss_score=0.0, cvss_vector="CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", description=f"Reconnaissance discovered {len(results['open_ports'])} open ports: " f"{', '.join(str(p['port']) for p in results['open_ports'][:10])}", tool_source="nmap", remediation="Review open ports and close unnecessary services.", ) if results["subdomains"]: self._create_finding( session=session, title=f"Subdomains Enumerated for {target}", severity="info", cvss_score=0.0, cvss_vector="CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", description=f"Found {len(results['subdomains'])} subdomains for {target}.", tool_source="subfinder", remediation="Review subdomain exposure and remove unnecessary DNS records.", ) results["status"] = "completed" results["findings_count"] = len(session.findings) self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "reconnaissance", "subdomains": len(results["subdomains"]), "endpoints": len(results["endpoints"]), "open_ports": len(results["open_ports"]), "technologies": results["technologies"], }, "multi-tool", ) self.logger.info( f"Recon completed | Subdomains: {len(results['subdomains'])} | " f"Endpoints: {len(results['endpoints'])} | " f"Ports: {len(results['open_ports'])}" ) return results async def _phase_scanning(self, session: PentestSession) -> Dict[str, Any]: """ Run vulnerability scanning using multiple tools. Tools: nuclei, zap, nikto Scans for known vulnerabilities, misconfigurations, and security issues. Args: session: Current pentest session. Returns: Dictionary with scanning results. """ self.logger.info(f"Session {session.session_id}: Phase - Scanning") target = session.target.host target_ip = session.target.ip or target output_prefix = str(self.output_dir / f"{session.session_id}_scan") results: Dict[str, Any] = { "phase": "scanning", "vulnerabilities": [], "misconfigurations": [], "security_headers": {}, "ssl_info": {}, "errors": [], } tasks = [] # Task 1: Nuclei - vulnerability scanning if "nuclei" in self.tool_paths: nuclei_cmd = [ "nuclei", "-u", f"https://{target}", "-o", f"{output_prefix}_nuclei.json", "-jsonl", "-severity", "critical,high,medium,low", "-silent", ] tasks.append(self._execute_tool(nuclei_cmd, session, timeout=600)) # Task 2: Nuclei on subdomains subdomains_file = f"{self.output_dir}/{session.session_id}_recon_subdomains.txt" if Path(subdomains_file).exists() and "nuclei" in self.tool_paths: nuclei_sub_cmd = [ "nuclei", "-l", str(subdomains_file), "-o", f"{output_prefix}_nuclei_subs.json", "-jsonl", "-silent", "-severity", "critical,high", ] tasks.append(self._execute_tool(nuclei_sub_cmd, session, timeout=600)) # Task 3: Nikto - web server scanning if "nikto" in self.tool_paths: nikto_cmd = [ "nikto", "-h", target, "-o", f"{output_prefix}_nikto.json", "-Format", "json", ] tasks.append(self._execute_tool(nikto_cmd, session, timeout=300)) # Task 4: SSL/TLS scan with nmap nmap_ssl_cmd = [ "nmap", "--script", "ssl-enum-ciphers,ssl-cert", "-p", "443,8443", "-oN", f"{output_prefix}_ssl_scan.txt", target_ip, ] tasks.append(self._execute_tool(nmap_ssl_cmd, session, timeout=120)) # Task 5: HTTP security headers curl_headers_cmd = [ "curl", "-sI", f"https://{target}", ] tasks.append(self._execute_tool(curl_headers_cmd, session, timeout=30)) # Execute all scanning tasks scan_results = await asyncio.gather(*tasks, return_exceptions=True) # Parse nuclei results nuclei_file = f"{output_prefix}_nuclei.json" if Path(nuclei_file).exists(): try: with open(nuclei_file, "r") as f: for line in f: if line.strip(): vuln = json.loads(line) severity = vuln.get("info", {}).get("severity", "unknown") vuln_entry = { "template_id": vuln.get("template-id", ""), "name": vuln.get("info", {}).get("name", "Unknown"), "severity": severity, "host": vuln.get("host", ""), "matched_at": vuln.get("matched-at", ""), "description": vuln.get("info", {}).get("description", ""), } results["vulnerabilities"].append(vuln_entry) # Create finding for significant vulnerabilities if severity in ("critical", "high", "medium"): cvss_map = {"critical": 9.8, "high": 8.1, "medium": 5.3} cvss_score = cvss_map.get(severity, 5.0) cvss_vectors = { "critical": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "high": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:L", "medium": "CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N", } references = vuln.get("info", {}).get("reference", []) if isinstance(references, str): references = [references] self._create_finding( session=session, title=f"[{severity.upper()}] {vuln_entry['name']}", severity=severity, cvss_score=cvss_score, cvss_vector=cvss_vectors.get(severity, "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L"), description=vuln_entry["description"] or f"{vuln_entry['name']} detected at {vuln_entry['matched_at']}", tool_source="nuclei", remediation=f"Review and remediate {vuln_entry['template_id']}. " f"Check references for specific fix instructions.", references=references, ) except (json.JSONDecodeError, KeyError) as e: results["errors"].append(f"Nuclei parsing error: {str(e)}") self.logger.warning(f"Nuclei output parsing failed: {str(e)}") # Parse nikto results nikto_file = f"{output_prefix}_nikto.json" if Path(nikto_file).exists(): try: with open(nikto_file, "r") as f: nikto_data = json.load(f) for vuln in nikto_data.get("vulnerabilities", []): results["vulnerabilities"].append( { "name": vuln.get("msg", "Unknown"), "severity": "medium", "method": vuln.get("method", ""), "url": vuln.get("url", ""), "source": "nikto", } ) except (json.JSONDecodeError, KeyError) as e: self.logger.warning(f"Nikto output parsing failed: {str(e)}") # Parse SSL results ssl_file = f"{output_prefix}_ssl_scan.txt" if Path(ssl_file).exists(): with open(ssl_file, "r") as f: results["ssl_info"]["raw"] = f.read() ssl_raw = results["ssl_info"]["raw"] # Check for weak ciphers weak_ciphers = ["DES", "RC4", "MD5", "EXPORT", "NULL"] found_weak = [c for c in weak_ciphers if c in ssl_raw.upper()] if found_weak: self._create_finding( session=session, title=f"Weak SSL/TLS Ciphers Enabled on {target}", severity="high", cvss_score=7.5, cvss_vector="CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N", description=f"The SSL/TLS configuration on {target} supports weak cipher suites: " f"{', '.join(found_weak)}. These ciphers are vulnerable to various " f"attacks including BEAST, CRIME, and SWEET32.", tool_source="nmap-ssl", remediation="Disable weak cipher suites in web server configuration. " "Use only TLS 1.2+ with strong cipher suites (AES-GCM, ChaCha20).", references=[ "https://cwe.mitre.org/data/definitions/326.html", "https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/01-Testing_for_Weak_SSL_TLS_Ciphers_Insufficient_Transport_Layer_Protection", ], ) # Parse HTTP headers for task_result in scan_results: if isinstance(task_result, dict) and task_result.get("tool") == "curl": headers_raw = task_result.get("stdout", "") headers = {} for line in headers_raw.split("\\n"): if ":" in line: key, value = line.split(":", 1) headers[key.strip().lower()] = value.strip() results["security_headers"] = { "x-frame-options": headers.get("x-frame-options", "MISSING"), "x-xss-protection": headers.get("x-xss-protection", "MISSING"), "x-content-type-options": headers.get("x-content-type-options", "MISSING"), "content-security-policy": headers.get("content-security-policy", "MISSING"), "strict-transport-security": headers.get("strict-transport-security", "MISSING"), "referrer-policy": headers.get("referrer-policy", "MISSING"), } # Check for missing security headers missing_headers = [k for k, v in results["security_headers"].items() if v == "MISSING"] if missing_headers: self._create_finding( session=session, title=f"Missing Security Headers on {target}", severity="medium", cvss_score=5.0, cvss_vector="CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", description=f"The following security headers are missing from {target}: " f"{', '.join(missing_headers)}. " f"These headers help protect against XSS, clickjacking, " f"MIME-type sniffing, and other web-based attacks.", tool_source="curl", remediation="Implement the missing security headers in your web server configuration. " "For Apache: use Header directives. For Nginx: use add_header directives.", references=[ "https://owasp.org/www-project-secure-headers/", "https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html", ], ) # Store scan results session.scan_results.update(results) results["status"] = "completed" results["findings_count"] = len(session.findings) results["vulnerabilities_count"] = len(results["vulnerabilities"]) self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "scanning", "vulnerabilities_found": len(results["vulnerabilities"]), "findings_created": len(session.findings), }, "multi-tool", ) self.logger.info( f"Scanning completed | Vulnerabilities: {len(results['vulnerabilities'])} | " f"Total findings: {len(session.findings)}" ) return results async def _phase_exploitation(self, session: PentestSession) -> Dict[str, Any]: """ Run exploitation phase with approval guardrails. Tools: sqlmap, metasploit Requires explicit approval for exploitation attempts. Only exploits confirmed vulnerabilities from scanning phase. Args: session: Current pentest session. Returns: Dictionary with exploitation results. """ self.logger.info(f"Session {session.session_id}: Phase - Exploitation") results: Dict[str, Any] = { "phase": "exploitation", "approved_exploits": [], "executed_exploits": [], "exploit_findings": [], "errors": [], "approval_required": True, "auto_approved": False, } # Check if exploitation should be auto-approved for low-risk if self.auto_approve_low_risk: critical_high = [f for f in session.findings if f.severity in ("critical", "high") and not f.confirmed] if not critical_high: results["auto_approved"] = True results["approval_required"] = False self.logger.info("Auto-approved: No critical/high unconfirmed findings") # Build list of potential exploits based on findings potential_exploits: List[Dict[str, Any]] = [] for finding in session.findings: if finding.severity in ("critical", "high") and not finding.confirmed: exploit_plan: Dict[str, Any] = { "target_finding": finding.id, "title": finding.title, "severity": finding.severity, "cvss_score": finding.cvss_score, "proposed_action": "manual_verification", "tools": [], } if "sql" in finding.title.lower() or "injection" in finding.title.lower(): exploit_plan["proposed_action"] = "sqlmap_injection_test" exploit_plan["tools"] = ["sqlmap"] exploit_plan["risk_level"] = "high" elif "xss" in finding.title.lower() or "cross-site" in finding.title.lower(): exploit_plan["proposed_action"] = "xss_payload_test" exploit_plan["tools"] = ["manual"] exploit_plan["risk_level"] = "medium" elif "lfi" in finding.title.lower() or "path traversal" in finding.title.lower(): exploit_plan["proposed_action"] = "lfi_path_traversal_test" exploit_plan["tools"] = ["manual"] exploit_plan["risk_level"] = "medium" elif "rce" in finding.title.lower() or "code execution" in finding.title.lower(): exploit_plan["proposed_action"] = "rce_verification" exploit_plan["tools"] = ["manual"] exploit_plan["risk_level"] = "critical" else: exploit_plan["proposed_action"] = "searchsploit_lookup" exploit_plan["tools"] = ["searchsploit"] exploit_plan["risk_level"] = finding.severity potential_exploits.append(exploit_plan) results["potential_exploits"] = potential_exploits self.logger.info(f"Identified {len(potential_exploits)} potential exploits requiring approval") # If no exploits to run, return early if not potential_exploits: results["status"] = "completed" results["message"] = "No exploitable findings identified" self.logger.info("No exploitation targets identified") return results # Simulated approval (in production, this would require human approval via MCP) approved_exploits = [] if results["auto_approved"]: approved_exploits = [e for e in potential_exploits if e["risk_level"] in ("medium", "low")] else: # For critical findings, log approval requirement for exploit in potential_exploits: if exploit["risk_level"] == "critical": self.logger.warning(f"CRITICAL exploit requires approval: {exploit['title']}") self._write_audit_log( session, "EXPLOIT_APPROVAL_REQUIRED", { "finding_id": exploit["target_finding"], "title": exploit["title"], "risk_level": exploit["risk_level"], }, exploit["tools"][0] if exploit["tools"] else "unknown", ) else: # Auto-approve medium/low risk approved_exploits.append(exploit) results["approved_exploits"] = approved_exploits # Execute approved exploits for exploit in approved_exploits: if self._check_pause_or_cancel(session): self.logger.info("Session paused or cancelled during exploitation") break self.logger.info(f"Executing exploit: {exploit['title']}") exploit_result: Dict[str, Any] = { "target_finding": exploit["target_finding"], "title": exploit["title"], "action": exploit["proposed_action"], "status": "pending", "output": "", } try: if exploit["proposed_action"] == "sqlmap_injection_test": # Safe SQLMap test with limited tamper scripts target_url = f"https://{session.target.host}" sqlmap_cmd = [ "sqlmap", "-u", target_url, "--batch", "--level=1", "--risk=1", "--timeout=30", "--smart", ] sqlmap_result = await self._execute_tool(sqlmap_cmd, session, timeout=180) exploit_result["output"] = sqlmap_result["stdout"] exploit_result["status"] = "success" if sqlmap_result["returncode"] == 0 else "failed" if "is vulnerable" in sqlmap_result["stdout"]: self._create_finding( session=session, title=f"[CONFIRMED] SQL Injection on {session.target.host}", severity="critical", cvss_score=9.8, cvss_vector="CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", description=f"SQL injection vulnerability confirmed on {target_url}. " f"SQLMap detected injectable parameters.", tool_source="sqlmap", remediation="Use parameterized queries/prepared statements. " "Implement input validation and output encoding. " "Apply least privilege to database accounts.", references=[ "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html", "https://cwe.mitre.org/data/definitions/89.html", ], ) exploit_result["confirmed_vulnerability"] = True elif exploit["proposed_action"] == "searchsploit_lookup": # Search for known exploits search_term = exploit["title"].replace("[", "").replace("]", "").split()[:3] searchsploit_cmd = ["searchsploit", "--json", " ".join(search_term)] ss_result = await self._execute_tool(searchsploit_cmd, session, timeout=60) exploit_result["output"] = ss_result["stdout"] exploit_result["status"] = "success" if ss_result["returncode"] == 0 else "failed" else: # Manual verification - document the finding exploit_result["status"] = "manual_verification_required" exploit_result["output"] = ( f"Manual verification required for: {exploit['title']}. " f"Risk level: {exploit['risk_level']}. " f"Review finding {exploit['target_finding']} for details." ) # Mark finding as requiring manual confirmation for finding in session.findings: if finding.id == exploit["target_finding"]: finding.confirmed = False results["executed_exploits"].append(exploit_result) self._write_audit_log( session, "EXPLOIT_EXECUTED", { "finding_id": exploit["target_finding"], "action": exploit["proposed_action"], "status": exploit_result["status"], }, exploit["tools"][0] if exploit["tools"] else "manual", approved_by="auto" if results["auto_approved"] else "pending", ) except Exception as e: exploit_result["status"] = "error" exploit_result["output"] = str(e) results["executed_exploits"].append(exploit_result) results["errors"].append(f"Exploit failed for {exploit['title']}: {str(e)}") self.logger.error(f"Exploit execution failed: {str(e)}") # Store results session.exploit_results.update(results) results["status"] = "completed" results["findings_count"] = len(session.findings) self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "exploitation", "potential_exploits": len(potential_exploits), "approved_exploits": len(approved_exploits), "executed_exploits": len(results["executed_exploits"]), }, "multi-tool", ) self.logger.info( f"Exploitation completed | Approved: {len(approved_exploits)} | " f"Executed: {len(results['executed_exploits'])} | " f"Total findings: {len(session.findings)}" ) return results async def _phase_post_exploit(self, session: PentestSession) -> Dict[str, Any]: """ Post-exploitation phase: privilege escalation and lateral movement analysis. Analyzes post-exploitation potential without executing actual lateral movement (requires explicit approval). Args: session: Current pentest session. Returns: Dictionary with post-exploitation analysis results. """ self.logger.info(f"Session {session.session_id}: Phase - Post-Exploitation") results: Dict[str, Any] = { "phase": "post_exploitation", "privesc_paths": [], "lateral_movement": [], "persistence_mechanisms": [], "data_exposure": [], "errors": [], "requires_approval": True, } # Analyze confirmed findings for post-exploitation impact confirmed_findings = [f for f in session.findings if f.confirmed] for finding in confirmed_findings: impact_analysis: Dict[str, Any] = { "finding_id": finding.id, "title": finding.title, "impact_areas": [], } if "rce" in finding.title.lower() or "code execution" in finding.title.lower(): impact_analysis["impact_areas"].append("privilege_escalation") impact_analysis["impact_areas"].append("lateral_movement") impact_analysis["impact_areas"].append("persistence") if "sql" in finding.title.lower(): impact_analysis["impact_areas"].append("data_exposure") impact_analysis["impact_areas"].append("data_manipulation") if "xss" in finding.title.lower(): impact_analysis["impact_areas"].append("session_hijacking") impact_analysis["impact_areas"].append("credential_theft") if "lfi" in finding.title.lower() or "path traversal" in finding.title.lower(): impact_analysis["impact_areas"].append("data_exposure") impact_analysis["impact_areas"].append("config_disclosure") if impact_analysis["impact_areas"]: results["privesc_paths"].append(impact_analysis) # Generate post-exploitation findings if results["privesc_paths"]: self._create_finding( session=session, title=f"Post-Exploitation Impact Analysis for {session.target.host}", severity="high", cvss_score=8.0, cvss_vector="CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H", description=f"Confirmed vulnerabilities on {session.target.host} could lead to " f"{len(results['privesc_paths'])} post-exploitation paths including: " f"privilege escalation, lateral movement, and data exposure. " f"Chained exploitation could result in full system compromise.", tool_source="analysis_engine", remediation="Address all confirmed vulnerabilities immediately. " "Implement network segmentation. " "Apply principle of least privilege. " "Enable comprehensive logging and monitoring.", references=[ "https://attack.mitre.org/tactics/TA0004/", "https://attack.mitre.org/tactics/TA0008/", ], ) # Lateral movement analysis based on recon data if session.recon_data.get("subdomains"): subdomains = session.recon_data["subdomains"] results["lateral_movement"].append( { "type": "subdomain_pivot", "description": f"{len(subdomains)} subdomains identified as potential lateral targets", "subdomains": subdomains[:10], # Limit for safety "risk": "potential_lateral_surface", } ) # Data exposure analysis if session.target.tech_stack: results["data_exposure"].append( { "type": "tech_stack_disclosure", "technologies": session.target.tech_stack, "risk": "information_disclosure_aiding_targeting", } ) # Store results session.exploit_results["post_exploitation"] = results results["status"] = "completed" results["findings_count"] = len(session.findings) self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "post_exploitation", "privesc_paths": len(results["privesc_paths"]), "lateral_targets": len(results["lateral_movement"]), }, "analysis_engine", ) self.logger.info( f"Post-exploitation completed | Privesc paths: {len(results['privesc_paths'])} | " f"Lateral targets: {len(results['lateral_movement'])}" ) return results async def _phase_analysis(self, session: PentestSession) -> Dict[str, Any]: """ AI-powered analysis of all findings with risk scoring and recommendations. Correlates findings, calculates aggregate risk scores, and generates prioritized remediation recommendations. Args: session: Current pentest session. Returns: Dictionary with analysis results. """ self.logger.info(f"Session {session.session_id}: Phase - Analysis") results: Dict[str, Any] = { "phase": "analysis", "risk_score": 0.0, "risk_rating": "low", "findings_summary": {}, "correlated_findings": [], "remediation_priority": [], "ai_recommendations": [], "attack_paths": [], "compliance_gaps": [], } # Severity distribution severity_counts: Dict[str, int] = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} total_cvss = 0.0 max_cvss = 0.0 for finding in session.findings: severity = finding.severity.lower() if severity in severity_counts: severity_counts[severity] += 1 total_cvss += finding.cvss_score if finding.cvss_score > max_cvss: max_cvss = finding.cvss_score results["findings_summary"] = severity_counts results["total_findings"] = len(session.findings) results["avg_cvss"] = round(total_cvss / len(session.findings), 2) if session.findings else 0.0 results["max_cvss"] = max_cvss # Calculate aggregate risk score (weighted) risk_weights = {"critical": 10, "high": 7, "medium": 4, "low": 1, "info": 0} weighted_score = sum(count * risk_weights.get(sev, 0) for sev, count in severity_counts.items()) # Normalize to 0-10 scale max_possible = len(session.findings) * 10 if session.findings else 1 normalized_risk = min(10.0, (weighted_score / max_possible) * 10) if max_possible > 0 else 0 results["risk_score"] = round(normalized_risk, 1) # Risk rating if results["risk_score"] >= 8: results["risk_rating"] = "critical" elif results["risk_score"] >= 6: results["risk_rating"] = "high" elif results["risk_score"] >= 4: results["risk_rating"] = "medium" elif results["risk_score"] >= 2: results["risk_rating"] = "low" else: results["risk_rating"] = "minimal" # Correlate findings - identify attack chains web_vulns = [ f for f in session.findings if any(kw in f.title.lower() for kw in ["xss", "csrf", "injection", "sqli", "lfi", "rce", "ssrf"]) ] infra_vulns = [ f for f in session.findings if any(kw in f.title.lower() for kw in ["ssl", "port", "cipher", "header", "dns", "certificate"]) ] if web_vulns and infra_vulns: results["correlated_findings"].append( { "correlation_type": "web_infra_chain", "description": "Web application vulnerabilities combined with " "infrastructure weaknesses increase overall attack surface", "web_vulns": [f.id for f in web_vulns[:5]], "infra_vulns": [f.id for f in infra_vulns[:5]], "chained_risk": "elevated", } ) # Identify attack paths if severity_counts["critical"] > 0: results["attack_paths"].append( { "path": "direct_exploitation", "description": f"{severity_counts['critical']} critical vulnerabilities allow " "direct exploitation without prerequisites", "entry_points": [f.id for f in session.findings if f.severity == "critical"], } ) if severity_counts["high"] > 0 and severity_counts["medium"] > 0: results["attack_paths"].append( { "path": "multi_stage_attack", "description": "High-severity vulnerabilities can be chained with " "medium-severity findings for elevated impact", "prerequisites": [f.id for f in session.findings if f.severity == "medium"], "exploitation": [f.id for f in session.findings if f.severity == "high"], } ) # Generate remediation priority sorted_findings = sorted( session.findings, key=lambda f: (self.SEVERITY_ORDER.get(f.severity, 0), f.cvss_score), reverse=True, ) for i, finding in enumerate(sorted_findings[:10], 1): results["remediation_priority"].append( { "priority": i, "finding_id": finding.id, "title": finding.title, "severity": finding.severity, "cvss_score": finding.cvss_score, "remediation": finding.remediation, "estimated_effort": self._estimate_effort(finding), } ) # AI-powered recommendations if self.ai_enabled: ai_recs = self._generate_ai_recommendations(session, results) results["ai_recommendations"] = ai_recs session.ai_recommendations.extend(ai_recs) # Compliance gap analysis compliance_frameworks = session.config.get("compliance_frameworks", []) if "owasp_top10" in compliance_frameworks: owasp_covered = set() for finding in session.findings: title_lower = finding.title.lower() if "injection" in title_lower or "sql" in title_lower: owasp_covered.add("A03:2021 - Injection") if "auth" in title_lower or "session" in title_lower: owasp_covered.add("A07:2021 - Identification and Authentication Failures") if "crypto" in title_lower or "ssl" in title_lower or "cipher" in title_lower: owasp_covered.add("A02:2021 - Cryptographic Failures") if "header" in title_lower or "cors" in title_lower: owasp_covered.add("A05:2021 - Security Misconfiguration") results["compliance_gaps"].append( { "framework": "OWASP Top 10 2021", "categories_covered": list(owasp_covered), "coverage_summary": f"Findings map to {len(owasp_covered)} OWASP categories", } ) results["status"] = "completed" self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "analysis", "risk_score": results["risk_score"], "risk_rating": results["risk_rating"], "total_findings": len(session.findings), "attack_paths": len(results["attack_paths"]), }, "analysis_engine", ) self.logger.info( f"Analysis completed | Risk score: {results['risk_score']}/10 ({results['risk_rating']}) | " f"Attack paths: {len(results['attack_paths'])}" ) return results def _estimate_effort(self, finding: Finding) -> str: """ Estimate remediation effort based on finding characteristics. Args: finding: The security finding to analyze. Returns: Estimated effort level string. """ if finding.cvss_score >= 9.0: return "high" # Requires architecture changes elif finding.cvss_score >= 7.0: return "medium-high" # Significant code/configuration changes elif finding.cvss_score >= 4.0: return "medium" # Standard patching/configuration else: return "low" # Quick fixes def _generate_ai_recommendations(self, session: PentestSession, analysis: Dict[str, Any]) -> List[str]: """ Generate AI-powered security recommendations. Args: session: Current pentest session. analysis: Analysis results dictionary. Returns: List of recommendation strings. """ recommendations: List[str] = [] # Risk-based recommendations if analysis["risk_rating"] in ("critical", "high"): recommendations.append( f"CRITICAL: Immediate action required. The overall risk score of " f"{analysis['risk_score']}/10 indicates severe security exposure. " f"Prioritize remediation of all {analysis['findings_summary'].get('critical', 0)} " f"critical findings within 24-48 hours." ) # Technology-specific recommendations if session.target.tech_stack: recommendations.append( f"Technology stack detected: {', '.join(session.target.tech_stack[:5])}. " f"Ensure all components are running latest stable versions with security patches applied." ) # Attack path recommendations if analysis["attack_paths"]: recommendations.append( f"{len(analysis['attack_paths'])} attack paths identified. " f"Implement defense-in-depth strategies including network segmentation, " f"WAF deployment, and enhanced monitoring for critical entry points." ) # Finding-specific recommendations critical_high = analysis["findings_summary"].get("critical", 0) + analysis["findings_summary"].get("high", 0) if critical_high > 3: recommendations.append( f"High volume of critical/high findings ({critical_high}) suggests " f"systematic security weaknesses. Recommend comprehensive security audit " f"and implementation of secure development lifecycle (SDLC) practices." ) # Compliance recommendations if analysis["compliance_gaps"]: recommendations.append( "Compliance gap analysis reveals areas requiring attention. " "Review findings against applicable security frameworks and develop " "remediation roadmap aligned with compliance requirements." ) return recommendations async def _phase_reporting(self, session: PentestSession) -> Dict[str, Any]: """ Generate comprehensive pentest report in multiple formats. Generates JSON summary, markdown report, and CSV findings export. Args: session: Current pentest session. Returns: Dictionary with report generation results. """ self.logger.info(f"Session {session.session_id}: Phase - Reporting") report_prefix = str(self.output_dir / f"report_{session.session_id}") results: Dict[str, Any] = { "phase": "reporting", "reports_generated": [], "errors": [], } # Sort findings by severity sorted_findings = sorted( session.findings, key=lambda f: (self.SEVERITY_ORDER.get(f.severity, 0), f.cvss_score), reverse=True, ) # 1. Generate JSON report json_report_path = f"{report_prefix}.json" try: report_data = { "metadata": { "session_id": session.session_id, "target": session.target.to_dict(), "start_time": session.start_time, "end_time": session.end_time or datetime.now().isoformat(), "scope_type": session.target.scope_type, }, "executive_summary": self._generate_executive_summary(session, sorted_findings), "findings": [f.to_dict() for f in sorted_findings], "risk_assessment": { "total_findings": len(session.findings), "severity_breakdown": { sev: len([f for f in session.findings if f.severity == sev]) for sev in ["critical", "high", "medium", "low", "info"] }, }, "reconnaissance": session.recon_data, "scanning": session.scan_results, "exploitation": session.exploit_results, "ai_recommendations": session.ai_recommendations, "audit_log": [entry.to_dict() for entry in session.audit_log], } with open(json_report_path, "w") as f: json.dump(report_data, f, indent=2, default=str) results["reports_generated"].append( { "format": "json", "path": json_report_path, } ) self.logger.info(f"JSON report generated: {json_report_path}") except Exception as e: results["errors"].append(f"JSON report generation failed: {str(e)}") self.logger.error(f"JSON report failed: {str(e)}") # 2. Generate Markdown report md_report_path = f"{report_prefix}.md" try: md_content = self._generate_markdown_report(session, sorted_findings) with open(md_report_path, "w") as f: f.write(md_content) results["reports_generated"].append( { "format": "markdown", "path": md_report_path, } ) self.logger.info(f"Markdown report generated: {md_report_path}") except Exception as e: results["errors"].append(f"Markdown report generation failed: {str(e)}") self.logger.error(f"Markdown report failed: {str(e)}") # 3. Generate CSV findings export csv_path = f"{report_prefix}_findings.csv" try: import csv with open(csv_path, "w", newline="") as f: writer = csv.writer(f) writer.writerow( [ "ID", "Title", "Severity", "CVSS Score", "CVSS Vector", "Description", "Remediation", "Tool Source", "Confirmed", "Timestamp", ] ) for finding in sorted_findings: writer.writerow( [ finding.id, finding.title, finding.severity.upper(), finding.cvss_score, finding.cvss_vector, finding.description[:200], finding.remediation[:200], finding.tool_source, finding.confirmed, finding.timestamp, ] ) results["reports_generated"].append( { "format": "csv", "path": csv_path, } ) self.logger.info(f"CSV export generated: {csv_path}") except Exception as e: results["errors"].append(f"CSV export generation failed: {str(e)}") self.logger.error(f"CSV export failed: {str(e)}") results["status"] = "completed" results["total_findings"] = len(session.findings) self._write_audit_log( session, "PHASE_COMPLETED", { "phase": "reporting", "reports_generated": len(results["reports_generated"]), "total_findings": len(session.findings), }, "reporting_engine", ) self.logger.info( f"Reporting completed | Reports: {len(results['reports_generated'])} | Findings: {len(session.findings)}" ) return results def _generate_executive_summary(self, session: PentestSession, sorted_findings: List[Finding]) -> Dict[str, Any]: """ Generate executive summary for the report. Args: session: Current pentest session. sorted_findings: Findings sorted by severity. Returns: Executive summary dictionary. """ severity_counts = { sev: len([f for f in session.findings if f.severity == sev]) for sev in ["critical", "high", "medium", "low", "info"] } total_cvss = sum(f.cvss_score for f in session.findings) if session.findings else 0 avg_cvss = round(total_cvss / len(session.findings), 1) if session.findings else 0 risk_level = "minimal" if severity_counts["critical"] > 0: risk_level = "critical" elif severity_counts["high"] > 0: risk_level = "high" elif severity_counts["medium"] > 2: risk_level = "medium" elif severity_counts["medium"] > 0: risk_level = "low-medium" return { "target": session.target.host, "scope_type": session.target.scope_type, "assessment_period": { "start": session.start_time, "end": session.end_time or datetime.now().isoformat(), }, "overall_risk": risk_level, "findings_summary": severity_counts, "total_findings": len(session.findings), "average_cvss": avg_cvss, "top_findings": [ {"id": f.id, "title": f.title, "severity": f.severity, "cvss": f.cvss_score} for f in sorted_findings[:5] ], "key_recommendations": session.ai_recommendations[:3] if self.ai_enabled else [], } def _generate_markdown_report(self, session: PentestSession, sorted_findings: List[Finding]) -> str: """ Generate full markdown report content. Args: session: Current pentest session. sorted_findings: Findings sorted by severity. Returns: Complete markdown report string. """ severity_counts = { sev: len([f for f in session.findings if f.severity == sev]) for sev in ["critical", "high", "medium", "low", "info"] } md = f"""# Penetration Test Report ## Target Information | Field | Value | |-------|-------| | **Target** | {session.target.host} | | **IP Address** | {session.target.ip or "N/A"} | | **Scope Type** | {session.target.scope_type} | | **Start Time** | {session.start_time} | | **End Time** | {session.end_time or "In Progress"} | | **Session ID** | {session.session_id} | ## Executive Summary This penetration test was conducted against **{session.target.host}** using an AI-augmented methodology covering reconnaissance, vulnerability scanning, exploitation testing, and post-exploitation analysis. ### Risk Overview | Severity | Count | Visual | |----------|-------|--------| | Critical | {severity_counts["critical"]} | {"&#9608;" * severity_counts["critical"]} | | High | {severity_counts["high"]} | {"&#9608;" * severity_counts["high"]} | | Medium | {severity_counts["medium"]} | {"&#9608;" * severity_counts["medium"]} | | Low | {severity_counts["low"]} | {"&#9608;" * severity_counts["low"]} | | Info | {severity_counts["info"]} | {"&#9608;" * severity_counts["info"]} | **Total Findings:** {len(session.findings)} ### AI Recommendations """ if session.ai_recommendations: for i, rec in enumerate(session.ai_recommendations, 1): md += f"{i}. {rec}\n" else: md += "_AI recommendations were not generated for this assessment._\n" md += """ ## Detailed Findings """ for finding in sorted_findings: md += f"""### {finding.id}: {finding.title} **Severity:** {finding.severity.upper()} | **CVSS:** {finding.cvss_score} | **Tool:** {finding.tool_source} | **Confirmed:** {"Yes" if finding.confirmed else "No"} **CVSS Vector:** `{finding.cvss_vector}` {f"**EPSS Score:** {finding.epss_score}" if finding.epss_score else ""} #### Description {finding.description} #### Remediation {finding.remediation} #### References """ if finding.references: for ref in finding.references: md += f"- {ref}\n" else: md += "_No external references provided._\n" md += "\n---\n\n" md += """## Reconnaissance Summary """ if session.recon_data.get("subdomains"): md += f"**Subdomains Discovered:** {len(session.recon_data['subdomains'])}\n\n" if session.recon_data.get("open_ports"): md += f"**Open Ports:** {len(session.recon_data['open_ports'])}\n\n" for port_info in session.recon_data["open_ports"][:10]: md += f"- Port {port_info['port']}/{port_info['protocol']} - {port_info['service']}\n" md += "\n" if session.recon_data.get("technologies"): md += f"**Technologies Detected:** {', '.join(session.recon_data['technologies'][:10])}\n\n" md += """## Audit Log | Timestamp | Phase | Action | Tool | Approved By | |-----------|-------|--------|------|-------------| """ for entry in session.audit_log[-20:]: # Last 20 entries md += f"| {entry.timestamp} | {entry.phase} | {entry.action} | {entry.tool_used} | {entry.approved_by} |\n" md += f""" --- *Report generated by AI-Pentest-Framework | Session: {session.session_id}* """ return md def get_findings(self, session_id: str, min_severity: str = "low") -> List[Finding]: """ Get findings filtered by minimum severity level. Args: session_id: The session identifier. min_severity: Minimum severity to include (critical/high/medium/low/info). Returns: List of findings meeting the severity threshold. Raises: ValueError: If session not found. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") min_level = self.SEVERITY_ORDER.get(min_severity.lower(), 0) return [f for f in self.sessions[session_id].findings if self.SEVERITY_ORDER.get(f.severity, 0) >= min_level] def get_session_status(self, session_id: str) -> Dict[str, Any]: """ Get current session status and summary. Args: session_id: The session identifier. Returns: Dictionary with session status information. Raises: ValueError: If session not found. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] return { "session_id": session.session_id, "target": session.target.host, "current_phase": session.phase.name, "status": session.status.value, "findings_count": len(session.findings), "severity_breakdown": { sev: len([f for f in session.findings if f.severity == sev]) for sev in ["critical", "high", "medium", "low", "info"] }, "start_time": session.start_time, "end_time": session.end_time, "scope_verified": session.scope_verified, "compliance_passed": session.compliance_passed, "elapsed_time": ( (datetime.now() - datetime.fromisoformat(session.start_time)).total_seconds() if session.start_time else 0 ), } async def pause_session(self, session_id: str) -> Dict[str, str]: """ Pause an active session. Args: session_id: The session identifier. Returns: Status confirmation dictionary. Raises: ValueError: If session not found or not running. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] if session.status != PentestStatus.RUNNING: raise ValueError(f"Session {session_id} is not running (status: {session.status.value})") session.status = PentestStatus.PAUSED session.phase = PentestPhase.PAUSED self.logger.info(f"Session {session_id} paused at phase {session.phase.name}") self._write_audit_log(session, "SESSION_PAUSED", {}, "engine") return {"status": "paused", "session_id": session_id} async def resume_session(self, session_id: str) -> Dict[str, str]: """ Resume a paused session. Args: session_id: The session identifier. Returns: Status confirmation dictionary. Raises: ValueError: If session not found or not paused. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] if session.status != PentestStatus.PAUSED: raise ValueError(f"Session {session_id} is not paused (status: {session.status.value})") session.status = PentestStatus.RUNNING self.logger.info(f"Session {session_id} resumed") self._write_audit_log(session, "SESSION_RESUMED", {}, "engine") return {"status": "resumed", "session_id": session_id} async def cancel_session(self, session_id: str) -> Dict[str, str]: """ Cancel an active session. Args: session_id: The session identifier. Returns: Status confirmation dictionary. Raises: ValueError: If session not found. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] session.status = PentestStatus.CANCELLED session.end_time = datetime.now().isoformat() self.logger.info(f"Session {session_id} cancelled") self._write_audit_log( session, "SESSION_CANCELLED", {"phase_at_cancel": session.phase.name, "findings_count": len(session.findings)}, "engine", ) return {"status": "cancelled", "session_id": session_id} def list_sessions(self) -> List[Dict[str, Any]]: """ List all active sessions with summary information. Returns: List of session summary dictionaries. """ return [ { "session_id": sid, "target": session.target.host, "phase": session.phase.name, "status": session.status.value, "findings": len(session.findings), } for sid, session in self.sessions.items() ] def export_session(self, session_id: str, format: str = "json") -> str: """ Export complete session data to a file. Args: session_id: The session identifier. format: Export format (json). Returns: Path to the exported file. Raises: ValueError: If session not found. """ if session_id not in self.sessions: raise ValueError(f"Session {session_id} not found") session = self.sessions[session_id] export_path = str(self.output_dir / f"export_{session_id}.{format}") if format == "json": with open(export_path, "w") as f: json.dump(session.to_dict(), f, indent=2, default=str) self.logger.info(f"Session exported to {export_path}") return export_path
"""
Pentest Engine - Core orchestration engine for the pentest lifecycle.
Manages phases: Reconnaissance -> Scanning -> Exploitation -> Post-Exploitation -> Reporting
Integrates with MCP Server for tool execution and AI for decision making.
Author: AI-Pentest-Framework
Version: 1.0.0
"""
import asyncio
import hashlib
import json
import logging
import subprocess
import time
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime
from enum import Enum, auto
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
# Configure logging
logger = logging.getLogger("pentest_engine")
class PentestPhase(Enum):
"""Enumeration of all pentest lifecycle phases."""
INITIALIZATION = auto()
SCOPE_VALIDATION = auto()
RECONNAISSANCE = auto()
SCANNING = auto()
EXPLOITATION = auto()
POST_EXPLOITATION = auto()
ANALYSIS = auto()
REPORTING = auto()
COMPLETED = auto()
ERROR = auto()
PAUSED = auto()
class PentestStatus(Enum):
"""Enumeration of pentest session status values."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
PAUSED = "paused"
CANCELLED = "cancelled"
class SeverityLevel(Enum):
"""CVSS severity classification levels."""
CRITICAL = "critical"
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
INFO = "info"
@dataclass
class Target:
"""
Represents a target for penetration testing.
Attributes:
host: Target hostname or IP address.
ip: Resolved IP address (filled during recon).
ports: List of discovered open ports.
scope_type: Type of testing scope - blackbox, greybox, or whitebox.
auth_creds: Optional authentication credentials for greybox/whitebox.
tech_stack: Detected technologies on the target.
"""
host: str
ip: Optional[str] = None
ports: List[int] = field(default_factory=list)
scope_type: str = "blackbox" # blackbox, greybox, whitebox
auth_creds: Optional[Dict[str, str]] = None
tech_stack: List[str] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
"""Convert target to dictionary representation."""
return {
"host": self.host,
"ip": self.ip,
"ports": self.ports,
"scope_type": self.scope_type,
"auth_creds": "***redacted***" if self.auth_creds else None,
"tech_stack": self.tech_stack,
}
@dataclass
class Finding:
"""
Represents a security finding discovered during pentesting.

Xet Storage Details

Size:
94.6 kB
·
Xet hash:
08c99ed47452297493e791ebfcef72557abd48f94f5b54195f562666b56f1fa9

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