Buckets:

download
raw
16.4 kB
"""
PentestGPT Comparison Module
Provides comprehensive comparison capabilities against PentestGPT,
an AI-powered penetration testing tool by Gelei Deng et al.
Reference: https://github.com/GeleiDeng/PentestGPT
"""
import asyncio
import logging
import re
import subprocess
import time
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional
from .common_benchmarks import (
BenchmarkTestCase,
CompetitorAdapter,
CompetitorResult,
FindingResult,
TestStatus,
)
logger = logging.getLogger(__name__)
@dataclass
class PentestGPTCapabilities:
"""PentestGPT tool capabilities."""
# Core capabilities
web_scanning: bool = True
api_scanning: bool = True
network_scanning: bool = True
mobile_scanning: bool = False
cloud_scanning: bool = False
container_scanning: bool = False
# AI features
uses_llm: bool = True
autonomous_mode: bool = True
interactive_mode: bool = True
context_awareness: bool = True
attack_chain_building: bool = True
# Exploitation
supports_exploitation: bool = True
post_exploitation: bool = False
lateral_movement: bool = False
# Output formats
supports_json: bool = True
supports_markdown: bool = True
supports_html: bool = False
supports_pdf: bool = False
# Integration
has_api: bool = False
ci_cd_support: bool = False
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class PentestGPTConfig:
"""Configuration for PentestGPT execution."""
# LLM configuration
llm_model: str = "gpt-4" # or "gpt-3.5-turbo"
api_key: Optional[str] = None
base_url: Optional[str] = None
# Execution mode
mode: str = "auto" # "auto", "interactive", "api"
# Scanning options
depth: str = "standard" # "quick", "standard", "deep"
scope: str = "targeted" # "targeted", "broad"
# Logging
log_level: str = "INFO"
save_conversation: bool = True
# Timeouts
max_session_duration: int = 3600 # 1 hour
command_timeout: int = 300 # 5 minutes per command
class PentestGPTResultParser:
"""Parser for PentestGPT output."""
# Vulnerability patterns in PentestGPT output
VULN_PATTERNS = {
"sql_injection": [
r"SQL\s+injection",
r"SQLi",
r"sql\s*injection",
],
"xss": [
r"cross.site\s+scripting",
r"XSS",
r"reflected\s+xss",
r"stored\s+xss",
],
"command_injection": [
r"command\s+injection",
r"OS\s+command\s+injection",
r"RCE",
r"remote\s+code\s+execution",
],
"path_traversal": [
r"path\s+traversal",
r"directory\s+traversal",
r"LFI",
r"local\s+file\s+inclusion",
],
"authentication_bypass": [
r"authentication\s+bypass",
r"auth\s+bypass",
r"broken\s+authentication",
],
"authorization_issue": [
r"authorization",
r"IDOR",
r"insecure\s+direct\s+object",
],
"information_disclosure": [
r"information\s+disclosure",
r"sensitive\s+data\s+exposure",
],
"csrf": [
r"CSRF",
r"cross.site\s+request\s+forgery",
],
"ssrf": [
r"SSRF",
r"server.side\s+request\s+forgery",
],
"xxe": [
r"XXE",
r"XML\s+external\s+entity",
],
"insecure_deserialization": [
r"insecure\s+deserialization",
r"deserialization",
],
}
SEVERITY_PATTERNS = {
"critical": [r"critical", r"severe", r"high\s+risk"],
"high": [r"high", r"major"],
"medium": [r"medium", r"moderate"],
"low": [r"low", r"minor", r"informational"],
"info": [r"info", r"information", r"note"],
}
def parse_console_output(self, output: str) -> List[FindingResult]:
"""Parse PentestGPT console output for findings."""
findings = []
# Split output into sections (usually separated by headers)
sections = re.split(r"\n[=\-]{3,}\n", output)
for section in sections:
finding = self._parse_section(section)
if finding:
findings.append(finding)
return findings
def _parse_section(self, section: str) -> Optional[FindingResult]:
"""Parse a single section for vulnerability information."""
section_lower = section.lower()
# Detect vulnerability type
vuln_type = None
for vtype, patterns in self.VULN_PATTERNS.items():
for pattern in patterns:
if re.search(pattern, section_lower, re.IGNORECASE):
vuln_type = vtype
break
if vuln_type:
break
if not vuln_type:
return None
# Detect severity
severity = "medium" # default
for sev, patterns in self.SEVERITY_PATTERNS.items():
for pattern in patterns:
if re.search(pattern, section_lower, re.IGNORECASE):
severity = sev
break
if severity != "medium":
break
# Extract location/URL
location = self._extract_location(section)
# Extract description
description = self._extract_description(section)
# Extract confidence
confidence = self._extract_confidence(section)
return FindingResult(
vuln_type=vuln_type,
severity=severity,
location=location,
confidence=confidence,
description=description,
)
def _extract_location(self, text: str) -> str:
"""Extract URL/location from text."""
# URL pattern
url_match = re.search(r'https?://[^\s<>"\']+|/[a-zA-Z0-9_/-]+', text)
if url_match:
return url_match.group(0)
# Endpoint pattern
endpoint_match = re.search(
r'(?:endpoint|path|URL)["\']?\s*:?\s*["\']?([^\n"\']+)',
text,
re.IGNORECASE,
)
if endpoint_match:
return endpoint_match.group(1).strip()
return "unknown"
def _extract_description(self, text: str) -> str:
"""Extract vulnerability description."""
# Look for description patterns
desc_match = re.search(
r'(?:description|summary|details?)["\']?\s*:?\s*["\']?([^\n]{10,500})',
text,
re.IGNORECASE,
)
if desc_match:
return desc_match.group(1).strip()
# Return first substantial sentence
sentences = re.split(r"[.!?]+", text)
for sent in sentences:
sent = sent.strip()
if len(sent) > 20 and len(sent) < 500:
return sent
return "No description available"
def _extract_confidence(self, text: str) -> float:
"""Extract confidence level from text."""
text_lower = text.lower()
if re.search(r"\b(confirmed|verified|exploited)\b", text_lower):
return 0.95
elif re.search(r"\b(high confidence|very likely)\b", text_lower):
return 0.85
elif re.search(r"\b(likely|probable|suspected)\b", text_lower):
return 0.70
elif re.search(r"\b(possible|potential|may be)\b", text_lower):
return 0.50
else:
return 0.60 # default
def parse_json_output(self, json_data: Dict[str, Any]) -> List[FindingResult]:
"""Parse structured JSON output from PentestGPT."""
findings = []
vuln_list = json_data.get("vulnerabilities", [])
if not vuln_list and "findings" in json_data:
vuln_list = json_data.get("findings", [])
for vuln in vuln_list:
finding = FindingResult(
vuln_type=vuln.get("type", "unknown"),
severity=vuln.get("severity", "medium").lower(),
location=vuln.get("location", vuln.get("url", "unknown")),
confidence=vuln.get("confidence", 0.7),
description=vuln.get("description", ""),
cwe_id=vuln.get("cwe_id"),
verified=vuln.get("verified", False),
exploited=vuln.get("exploited", False),
)
findings.append(finding)
return findings
def parse_conversation_log(self, log_path: Path) -> List[FindingResult]:
"""Parse conversation log file for findings."""
findings = []
try:
with open(log_path, "r") as f:
content = f.read()
# Parse the entire conversation
findings = self.parse_console_output(content)
except Exception as e:
logger.error(f"Error parsing conversation log: {e}")
return findings
class PentestGPTComparator(CompetitorAdapter):
"""Adapter for comparing against PentestGPT."""
def __init__(self, config: Optional[PentestGPTConfig] = None):
self.config = config or PentestGPTConfig()
self.parser = PentestGPTResultParser()
self.capabilities = PentestGPTCapabilities()
# Metadata
self.metadata = {
"name": "PentestGPT",
"version": "2.0",
"vendor": "Gelei Deng et al.",
"license": "MIT",
"github": "https://github.com/GeleiDeng/PentestGPT",
"paper": "https://arxiv.org/abs/2308.06782",
"category": "AI-Powered Penetration Testing",
}
def is_available(self) -> bool:
"""Check if PentestGPT is installed and available."""
try:
result = subprocess.run(["pentestgpt", "--version"], capture_output=True, timeout=10)
return result.returncode == 0
except (subprocess.SubprocessError, FileNotFoundError):
# Check if installed via pip
try:
result = subprocess.run(
["python", "-m", "pentestgpt", "--version"],
capture_output=True,
timeout=10,
)
return result.returncode == 0
except (subprocess.SubprocessError, FileNotFoundError):
return False
def get_capabilities(self) -> Dict[str, Any]:
"""Get PentestGPT capabilities."""
return self.capabilities.to_dict()
def get_metadata(self) -> Dict[str, Any]:
"""Get PentestGPT metadata."""
return self.metadata
async def execute_test(self, test_case: BenchmarkTestCase, timeout_seconds: int = 600) -> CompetitorResult:
"""Execute a benchmark test using PentestGPT."""
result = CompetitorResult(
tool_name="PentestGPT",
tool_version=self.metadata["version"],
test_case_id=test_case.id,
status=TestStatus.PENDING,
start_time=datetime.now(timezone.utc),
)
if not self.is_available():
result.status = TestStatus.ERROR
result.error_message = "PentestGPT is not installed or not available"
return result
try:
# Build target URL
target = test_case.target_url or f"http://{test_case.target_host}"
if test_case.target_port:
target = f"{target}:{test_case.target_port}"
# Build command
cmd = self._build_command(target, test_case)
logger.info(f"Running PentestGPT: {' '.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,
)
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
if process.returncode == 0:
findings = self.parser.parse_console_output(output)
result.findings = findings
result.raw_output = {
"stdout": output,
"stderr": error_output,
"returncode": process.returncode,
}
result.status = TestStatus.PASSED
# Calculate metrics
result.calculate_metrics(test_case.expected_findings)
else:
result.status = TestStatus.FAILED
result.error_message = f"PentestGPT exited with code {process.returncode}"
result.raw_output = {"stderr": error_output}
except Exception as e:
logger.exception("Error executing PentestGPT test")
result.status = TestStatus.ERROR
result.error_message = str(e)
finally:
result.end_time = datetime.now(timezone.utc)
return result
def _build_command(self, target: str, test_case: BenchmarkTestCase) -> List[str]:
"""Build PentestGPT command for the test case."""
cmd = ["pentestgpt"]
# Mode
if self.config.mode == "auto":
cmd.extend(["--autonomous"])
# Target
cmd.extend(["--target", target])
# LLM model
cmd.extend(["--model", self.config.llm_model])
# Logging
if self.config.save_conversation:
cmd.extend(["--log", f"pentestgpt_{test_case.id}.log"])
# Depth
if self.config.depth == "quick":
cmd.extend(["--quick"])
elif self.config.depth == "deep":
cmd.extend(["--deep"])
return cmd
async def run_comparison_batch(
self, test_cases: List[BenchmarkTestCase], max_concurrent: int = 1
) -> List[CompetitorResult]:
"""Run multiple tests and return results."""
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 analyze_strengths_weaknesses(self, results: List[CompetitorResult]) -> Dict[str, Any]:
"""Analyze PentestGPT strengths and weaknesses based on results."""
analysis = {
"strengths": [],
"weaknesses": [],
"avg_detection_rate": 0.0,
"avg_precision": 0.0,
"category_performance": {},
}
if not results:
return analysis
# Calculate averages
detection_rates = [r.detection_rate for r in results if r.status == TestStatus.PASSED]
precisions = [r.precision for r in results if r.status == TestStatus.PASSED]
if detection_rates:
analysis["avg_detection_rate"] = sum(detection_rates) / len(detection_rates)
if precisions:
analysis["avg_precision"] = sum(precisions) / len(precisions)
# Identify strengths
if analysis["avg_detection_rate"] > 0.7:
analysis["strengths"].append("Good overall vulnerability detection rate")
if analysis["avg_precision"] > 0.8:
analysis["strengths"].append("Low false positive rate")
# Identify weaknesses
timeout_rate = sum(1 for r in results if r.status == TestStatus.TIMEOUT) / len(results)
if timeout_rate > 0.2:
analysis["weaknesses"].append(f"High timeout rate ({timeout_rate:.1%})")
return analysis

Xet Storage Details

Size:
16.4 kB
·
Xet hash:
e660c865410971b552a115693d4adca75ee5a418f11fe80a075559daf0051623

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