Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /benchmarks /comparison /autopentest_comparison.py
| """ | |
| AutoPentest-DRL Comparison Module | |
| Provides comprehensive comparison capabilities against AutoPentest-DRL, | |
| a deep reinforcement learning-based automated penetration testing tool. | |
| Reference: https://github.com/crond-jaist/AutoPentest-DRL | |
| Paper: "Autonomous Penetration Testing using Deep Reinforcement Learning" | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import re | |
| import subprocess | |
| import time | |
| from dataclasses import asdict, dataclass, field | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional | |
| from .common_benchmarks import ( | |
| BenchmarkTestCase, | |
| CompetitorAdapter, | |
| CompetitorResult, | |
| FindingResult, | |
| TestCategory, | |
| TestStatus, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class AutoPentestCapabilities: | |
| """AutoPentest-DRL tool capabilities.""" | |
| # Core capabilities | |
| network_scanning: bool = True | |
| vulnerability_scanning: bool = True | |
| exploitation: bool = True | |
| post_exploitation: bool = True | |
| lateral_movement: bool = True | |
| # Scope limitations | |
| web_scanning: bool = False # Limited web support | |
| api_scanning: bool = False | |
| cloud_scanning: bool = False | |
| container_scanning: bool = False | |
| mobile_scanning: bool = False | |
| # AI features | |
| uses_drl: bool = True # Deep Reinforcement Learning | |
| uses_llm: bool = False | |
| autonomous_planning: bool = True | |
| attack_graph_generation: bool = True | |
| # Exploitation specifics | |
| metasploit_integration: bool = True | |
| custom_exploit_support: bool = False | |
| # Output formats | |
| supports_json: bool = True | |
| supports_xml: bool = True | |
| supports_html: bool = True | |
| supports_markdown: bool = False | |
| # Integration | |
| has_api: bool = False | |
| ci_cd_support: bool = False | |
| def to_dict(self) -> Dict[str, Any]: | |
| return asdict(self) | |
| class AutoPentestConfig: | |
| """Configuration for AutoPentest-DRL execution.""" | |
| # Network configuration | |
| target_network: str = "" | |
| target_hosts: List[str] = field(default_factory=list) | |
| # DRL parameters | |
| model_path: Optional[str] = None | |
| training_mode: bool = False | |
| episodes: int = 100 | |
| max_steps_per_episode: int = 50 | |
| # Attack configuration | |
| attack_depth: str = "standard" # "shallow", "standard", "deep" | |
| privilege_escalation: bool = True | |
| lateral_movement: bool = True | |
| # Metasploit settings | |
| msf_rpc_host: str = "127.0.0.1" | |
| msf_rpc_port: int = 55553 | |
| msf_rpc_user: str = "msf" | |
| msf_rpc_pass: str = "" | |
| # Output settings | |
| output_format: str = "json" # "json", "xml", "html" | |
| output_path: Optional[str] = None | |
| generate_attack_graph: bool = True | |
| # Timeouts | |
| max_scan_duration: int = 7200 # 2 hours | |
| exploit_timeout: int = 300 # 5 minutes per exploit | |
| class AutoPentestResultParser: | |
| """Parser for AutoPentest-DRL output.""" | |
| # Vulnerability patterns | |
| VULN_PATTERNS = { | |
| "remote_code_execution": [ | |
| r"remote\s+code\s+execution", | |
| r"RCE", | |
| r"command\s+execution", | |
| r"shell\s+access", | |
| ], | |
| "privilege_escalation": [ | |
| r"privilege\s+escalation", | |
| r"root\s+access", | |
| r"administrator\s+access", | |
| r"elevation\s+of\s+privilege", | |
| ], | |
| "credential_exposure": [ | |
| r"credential", | |
| r"password", | |
| r"hash\s+captured", | |
| r"ticket\s+captured", | |
| ], | |
| "service_exploit": [ | |
| r"service\s+exploited", | |
| r"exploit\s+successful", | |
| r"vulnerability\s+exploited", | |
| ], | |
| "lateral_movement": [ | |
| r"lateral\s+movement", | |
| r"pivot\s+established", | |
| r"network\s+access", | |
| ], | |
| "information_gathering": [ | |
| r"host\s+discovered", | |
| r"service\s+detected", | |
| r"vulnerability\s+detected", | |
| ], | |
| } | |
| SEVERITY_MAPPING = { | |
| "remote_code_execution": "critical", | |
| "privilege_escalation": "critical", | |
| "credential_exposure": "high", | |
| "service_exploit": "high", | |
| "lateral_movement": "high", | |
| "information_gathering": "medium", | |
| } | |
| def parse_json_report(self, report_path: Path) -> List[FindingResult]: | |
| """Parse AutoPentest JSON report.""" | |
| findings = [] | |
| try: | |
| with open(report_path, "r") as f: | |
| report = json.load(f) | |
| # Parse attack path | |
| attack_path = report.get("attack_path", []) | |
| for step in attack_path: | |
| finding = self._parse_attack_step(step) | |
| if finding: | |
| findings.append(finding) | |
| # Parse discovered vulnerabilities | |
| vulns = report.get("vulnerabilities", []) | |
| for vuln in vulns: | |
| finding = self._parse_vulnerability(vuln) | |
| if finding: | |
| findings.append(finding) | |
| # Parse hosts/compromised systems | |
| hosts = report.get("compromised_hosts", []) | |
| for host in hosts: | |
| finding = self._parse_compromised_host(host) | |
| if finding: | |
| findings.append(finding) | |
| except Exception as e: | |
| logger.error(f"Error parsing AutoPentest report: {e}") | |
| return findings | |
| def _parse_attack_step(self, step: Dict[str, Any]) -> Optional[FindingResult]: | |
| """Parse an attack step from the attack path.""" | |
| action = step.get("action", "") | |
| module = step.get("module", "") | |
| target = step.get("target", "") | |
| result = step.get("result", "") | |
| # Determine vulnerability type from action | |
| vuln_type = "unknown" | |
| for vtype, patterns in self.VULN_PATTERNS.items(): | |
| for pattern in patterns: | |
| if re.search(pattern, action + " " + module, re.IGNORECASE): | |
| vuln_type = vtype | |
| break | |
| if vuln_type != "unknown": | |
| break | |
| # Determine severity | |
| severity = self.SEVERITY_MAPPING.get(vuln_type, "medium") | |
| # Check if successful | |
| success = result.lower() in [ | |
| "success", | |
| "successful", | |
| "compromised", | |
| "exploited", | |
| ] | |
| return FindingResult( | |
| vuln_type=vuln_type, | |
| severity=severity, | |
| location=target, | |
| confidence=0.9 if success else 0.6, | |
| description=f"Attack step: {action} using {module}", | |
| verified=success, | |
| exploited=success, | |
| ) | |
| def _parse_vulnerability(self, vuln: Dict[str, Any]) -> Optional[FindingResult]: | |
| """Parse a vulnerability entry.""" | |
| vuln_type = vuln.get("type", "unknown") | |
| return FindingResult( | |
| vuln_type=vuln_type, | |
| severity=vuln.get("severity", "medium").lower(), | |
| location=vuln.get("host", vuln.get("location", "unknown")), | |
| confidence=vuln.get("confidence", 0.7), | |
| description=vuln.get("description", ""), | |
| cwe_id=vuln.get("cwe_id"), | |
| verified=vuln.get("exploitable", False), | |
| exploited=vuln.get("exploited", False), | |
| ) | |
| def _parse_compromised_host(self, host: Dict[str, Any]) -> Optional[FindingResult]: | |
| """Parse a compromised host entry.""" | |
| hostname = host.get("hostname", host.get("ip", "unknown")) | |
| access_level = host.get("access_level", "user") | |
| severity = "critical" if access_level in ["root", "system", "administrator"] else "high" | |
| return FindingResult( | |
| vuln_type="host_compromise", | |
| severity=severity, | |
| location=hostname, | |
| confidence=1.0, | |
| description=f"Host compromised with {access_level} access", | |
| verified=True, | |
| exploited=True, | |
| ) | |
| def parse_console_output(self, output: str) -> List[FindingResult]: | |
| """Parse AutoPentest console output.""" | |
| findings = [] | |
| # Look for successful exploits | |
| exploit_pattern = r"\[\+\]\s+(.+?)\s+exploit\s+successful\s+on\s+(.+)" | |
| for match in re.finditer(exploit_pattern, output, re.IGNORECASE): | |
| vuln_type = match.group(1).strip() | |
| target = match.group(2).strip() | |
| finding = FindingResult( | |
| vuln_type=vuln_type, | |
| severity="critical", | |
| location=target, | |
| confidence=0.95, | |
| description=f"Successful {vuln_type} exploit", | |
| verified=True, | |
| exploited=True, | |
| ) | |
| findings.append(finding) | |
| # Look for detected vulnerabilities | |
| vuln_pattern = r"\[\*\]\s+Vulnerability\s+found:\s+(.+?)\s+on\s+(.+)" | |
| for match in re.finditer(vuln_pattern, output, re.IGNORECASE): | |
| vuln_type = match.group(1).strip() | |
| target = match.group(2).strip() | |
| finding = FindingResult( | |
| vuln_type=vuln_type, | |
| severity="high", | |
| location=target, | |
| confidence=0.75, | |
| description=f"Vulnerability detected: {vuln_type}", | |
| verified=False, | |
| exploited=False, | |
| ) | |
| findings.append(finding) | |
| return findings | |
| def parse_attack_graph(self, graph_path: Path) -> Dict[str, Any]: | |
| """Parse attack graph visualization data.""" | |
| try: | |
| with open(graph_path, "r") as f: | |
| graph_data = json.load(f) | |
| return { | |
| "nodes": graph_data.get("nodes", []), | |
| "edges": graph_data.get("edges", []), | |
| "attack_paths": graph_data.get("attack_paths", []), | |
| "critical_nodes": graph_data.get("critical_nodes", []), | |
| } | |
| except Exception as e: | |
| logger.error(f"Error parsing attack graph: {e}") | |
| return {} | |
| class AutoPentestComparator(CompetitorAdapter): | |
| """Adapter for comparing against AutoPentest-DRL.""" | |
| def __init__(self, config: Optional[AutoPentestConfig] = None): | |
| self.config = config or AutoPentestConfig() | |
| self.parser = AutoPentestResultParser() | |
| self.capabilities = AutoPentestCapabilities() | |
| # Metadata | |
| self.metadata = { | |
| "name": "AutoPentest-DRL", | |
| "version": "1.0", | |
| "vendor": "JAIST (Japan Advanced Institute of Science and Technology)", | |
| "license": "MIT", | |
| "github": "https://github.com/crond-jaist/AutoPentest-DRL", | |
| "paper": "https://doi.org/10.1109/ACCESS.2022.3160389", | |
| "category": "DRL-Based Automated Penetration Testing", | |
| } | |
| def is_available(self) -> bool: | |
| """Check if AutoPentest-DRL is installed and available.""" | |
| try: | |
| # Check for main script | |
| result = subprocess.run( | |
| ["python", "AutoPentest-DRL.py", "--help"], | |
| capture_output=True, | |
| timeout=10, | |
| cwd=self._get_install_path(), | |
| ) | |
| return result.returncode == 0 | |
| except (subprocess.SubprocessError, FileNotFoundError): | |
| return False | |
| def _get_install_path(self) -> Optional[str]: | |
| """Get AutoPentest installation path.""" | |
| # Check common locations | |
| common_paths = [ | |
| "/opt/AutoPentest-DRL", | |
| "/usr/local/AutoPentest-DRL", | |
| str(Path.home() / "AutoPentest-DRL"), | |
| str(Path.home() / "tools" / "AutoPentest-DRL"), | |
| ] | |
| for path in common_paths: | |
| if Path(path).exists(): | |
| return path | |
| return None | |
| def get_capabilities(self) -> Dict[str, Any]: | |
| """Get AutoPentest-DRL capabilities.""" | |
| return self.capabilities.to_dict() | |
| def get_metadata(self) -> Dict[str, Any]: | |
| """Get AutoPentest-DRL metadata.""" | |
| return self.metadata | |
| async def execute_test(self, test_case: BenchmarkTestCase, timeout_seconds: int = 7200) -> CompetitorResult: | |
| """Execute a benchmark test using AutoPentest-DRL.""" | |
| result = CompetitorResult( | |
| tool_name="AutoPentest-DRL", | |
| tool_version=self.metadata["version"], | |
| test_case_id=test_case.id, | |
| status=TestStatus.PENDING, | |
| start_time=datetime.now(timezone.utc), | |
| ) | |
| install_path = self._get_install_path() | |
| if not install_path: | |
| result.status = TestStatus.ERROR | |
| result.error_message = "AutoPentest-DRL is not installed" | |
| return result | |
| # Check if test is compatible | |
| if test_case.category not in [ | |
| TestCategory.NETWORK_SECURITY, | |
| TestCategory.RECONNAISSANCE, | |
| ]: | |
| result.status = TestStatus.SKIPPED | |
| result.error_message = f"AutoPentest-DRL does not support {test_case.category.value} tests" | |
| return result | |
| try: | |
| # Build target | |
| target = test_case.target_host or self._extract_host(test_case.target_url) | |
| if not target: | |
| result.status = TestStatus.ERROR | |
| result.error_message = "No valid target specified" | |
| return result | |
| # Build command | |
| cmd = self._build_command(target) | |
| logger.info(f"Running AutoPentest-DRL: {' '.join(cmd)}") | |
| result.status = TestStatus.RUNNING | |
| # Execute with timeout | |
| start_time = time.time() | |
| process = await asyncio.create_subprocess_exec( | |
| *cmd, | |
| stdout=asyncio.subprocess.PIPE, | |
| stderr=asyncio.subprocess.PIPE, | |
| cwd=install_path, | |
| ) | |
| try: | |
| stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_seconds) | |
| output = stdout.decode("utf-8", errors="ignore") | |
| error_output = stderr.decode("utf-8", errors="ignore") | |
| except asyncio.TimeoutError: | |
| process.kill() | |
| result.status = TestStatus.TIMEOUT | |
| result.error_message = f"Test timed out after {timeout_seconds}s" | |
| return result | |
| end_time = time.time() | |
| result.scan_duration_seconds = end_time - start_time | |
| # Parse results | |
| # Try JSON report first | |
| report_path = Path(install_path) / "reports" / "report.json" | |
| if report_path.exists(): | |
| findings = self.parser.parse_json_report(report_path) | |
| else: | |
| # Fall back to console output | |
| findings = self.parser.parse_console_output(output) | |
| result.findings = findings | |
| result.raw_output = { | |
| "stdout": output, | |
| "stderr": error_output, | |
| "returncode": process.returncode, | |
| } | |
| if process.returncode == 0 or findings: | |
| result.status = TestStatus.PASSED | |
| result.calculate_metrics(test_case.expected_findings) | |
| else: | |
| result.status = TestStatus.FAILED | |
| result.error_message = f"AutoPentest-DRL exited with code {process.returncode}" | |
| except Exception as e: | |
| logger.exception("Error executing AutoPentest-DRL test") | |
| result.status = TestStatus.ERROR | |
| result.error_message = str(e) | |
| finally: | |
| result.end_time = datetime.now(timezone.utc) | |
| return result | |
| def _extract_host(self, url: str) -> Optional[str]: | |
| """Extract host from URL.""" | |
| if not url: | |
| return None | |
| # Remove protocol | |
| host = re.sub(r"^https?://", "", url) | |
| # Remove path | |
| host = host.split("/")[0] | |
| # Remove port | |
| host = host.split(":")[0] | |
| return host | |
| def _build_command(self, target: str) -> List[str]: | |
| """Build AutoPentest-DRL command.""" | |
| cmd = [ | |
| "python", | |
| "AutoPentest-DRL.py", | |
| "--target", | |
| target, | |
| "--format", | |
| self.config.output_format, | |
| ] | |
| if self.config.model_path: | |
| cmd.extend(["--model", self.config.model_path]) | |
| if self.config.generate_attack_graph: | |
| cmd.append("--attack-graph") | |
| if self.config.privilege_escalation: | |
| cmd.append("--privesc") | |
| if self.config.lateral_movement: | |
| cmd.append("--lateral-movement") | |
| if self.config.output_path: | |
| cmd.extend(["--output", self.config.output_path]) | |
| return cmd | |
| async def run_comparison_batch( | |
| self, test_cases: List[BenchmarkTestCase], max_concurrent: int = 1 | |
| ) -> List[CompetitorResult]: | |
| """Run multiple tests with concurrency control.""" | |
| # AutoPentest-DRL typically runs one network scan at a time | |
| semaphore = asyncio.Semaphore(max_concurrent) | |
| async def run_with_limit( | |
| test_case: BenchmarkTestCase, | |
| ) -> CompetitorResult: | |
| async with semaphore: | |
| return await self.execute_test(test_case) | |
| results = await asyncio.gather(*[run_with_limit(tc) for tc in test_cases]) | |
| return list(results) | |
| def get_attack_graph_summary(self, report_path: Path) -> Dict[str, Any]: | |
| """Get summary of attack graph analysis.""" | |
| graph_path = report_path.parent / "attack_graph.json" | |
| if not graph_path.exists(): | |
| return {"error": "Attack graph not found"} | |
| graph_data = self.parser.parse_attack_graph(graph_path) | |
| return { | |
| "total_nodes": len(graph_data.get("nodes", [])), | |
| "total_edges": len(graph_data.get("edges", [])), | |
| "attack_paths": len(graph_data.get("attack_paths", [])), | |
| "critical_nodes": len(graph_data.get("critical_nodes", [])), | |
| "graph_complexity": self._calculate_graph_complexity(graph_data), | |
| } | |
| def _calculate_graph_complexity(self, graph_data: Dict[str, Any]) -> str: | |
| """Calculate complexity level of attack graph.""" | |
| nodes = len(graph_data.get("nodes", [])) | |
| _ = len(graph_data.get("edges", [])) # TODO: Use edges | |
| if nodes < 10: | |
| return "simple" | |
| elif nodes < 30: | |
| return "moderate" | |
| elif nodes < 50: | |
| return "complex" | |
| else: | |
| return "highly_complex" | |
| def analyze_network_focus(self, results: List[CompetitorResult]) -> Dict[str, Any]: | |
| """Analyze AutoPentest-DRL's network-focused performance.""" | |
| analysis = { | |
| "network_exploitation_success": 0.0, | |
| "privilege_escalation_rate": 0.0, | |
| "lateral_movement_success": 0.0, | |
| "avg_time_to_compromise": 0.0, | |
| "strengths": [], | |
| "limitations": [], | |
| } | |
| successful_exploits = 0 | |
| priv_esc_count = 0 | |
| lateral_move_count = 0 | |
| total_duration = 0 | |
| for result in results: | |
| if result.status != TestStatus.PASSED: | |
| continue | |
| total_duration += result.scan_duration_seconds | |
| for finding in result.findings: | |
| if finding.exploited: | |
| successful_exploits += 1 | |
| if finding.vuln_type == "privilege_escalation": | |
| priv_esc_count += 1 | |
| elif finding.vuln_type == "lateral_movement": | |
| lateral_move_count += 1 | |
| total_findings = sum(len(r.findings) for r in results) | |
| if total_findings > 0: | |
| analysis["network_exploitation_success"] = successful_exploits / total_findings | |
| analysis["privilege_escalation_rate"] = priv_esc_count / total_findings | |
| analysis["lateral_movement_success"] = lateral_move_count / total_findings | |
| if results: | |
| analysis["avg_time_to_compromise"] = total_duration / len(results) | |
| # Identify strengths | |
| if analysis["network_exploitation_success"] > 0.5: | |
| analysis["strengths"].append("Strong network exploitation capabilities") | |
| if analysis["privilege_escalation_rate"] > 0.3: | |
| analysis["strengths"].append("Effective privilege escalation") | |
| # Identify limitations | |
| analysis["limitations"].append("Limited web application testing") | |
| analysis["limitations"].append("Requires Metasploit RPC") | |
| analysis["limitations"].append("Network-focused only") | |
| return analysis | |
Xet Storage Details
- Size:
- 20.6 kB
- Xet hash:
- a338d2de7ce17df2d6e73ba293c59f9a1ba9acd4d51f1186d05b0ff772c39372
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.