Buckets:

download
raw
12.8 kB
#!/usr/bin/env python3
"""
SearchSploit Integration Module for Zen-AI-Pentest
Automated Exploit-DB querying and vulnerability mapping
"""
import json
import logging
import subprocess
from dataclasses import dataclass
from typing import Dict, List, Optional, Union
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class Exploit:
"""Represents an exploit from Exploit-DB"""
title: str
edb_id: str
date_published: str
type: str
platform: str
cve: Optional[str]
verified: bool
path: str
author: Optional[str] = None
def __post_init__(self):
self.url = f"https://www.exploit-db.com/exploits/{self.edb_id}"
def get_local_path(self) -> Optional[str]:
"""Get the local filesystem path to the exploit"""
result = subprocess.run(["searchsploit", "-p", self.edb_id], capture_output=True, text=True)
for line in result.stdout.split("\n"):
if line.startswith(" Path:"):
return line.split(":", 1)[1].strip()
return None
def copy_to_workspace(self, dest_dir: str = ".") -> Optional[str]:
"""Copy exploit to workspace directory"""
result = subprocess.run(
["searchsploit", "-m", self.edb_id],
capture_output=True,
text=True,
cwd=dest_dir,
)
for line in result.stdout.split("\n"):
if "Copied to:" in line:
return line.split("Copied to:")[1].strip()
return None
class SearchSploitIntegration:
"""
Main class for SearchSploit integration
"""
def __init__(self):
self._check_searchsploit()
def _check_searchsploit(self):
"""Verify searchsploit is installed"""
try:
result = subprocess.run(["searchsploit", "-h"], capture_output=True, check=False)
# Check if help output contains expected text (stdout or stderr)
output = result.stdout + result.stderr
if b"Usage: searchsploit" not in output:
raise RuntimeError("searchsploit not found")
except (subprocess.CalledProcessError, FileNotFoundError):
raise RuntimeError("searchsploit not found. Install with: sudo apt install exploitdb")
def search(
self,
query: Union[str, List[str]],
exact: bool = False,
title_only: bool = True,
exclude_dos: bool = True,
case_sensitive: bool = False,
) -> List[Exploit]:
"""
Search for exploits
Args:
query: Search terms (string or list)
exact: Exact match on exploit title
title_only: Search only in titles (faster, less false positives)
exclude_dos: Exclude Denial of Service exploits
case_sensitive: Case-sensitive search
Returns:
List of Exploit objects
"""
if isinstance(query, list):
query = " ".join(query)
cmd = ["searchsploit", "-j"]
if title_only:
cmd.append("-t")
if exact:
cmd.append("-e")
if case_sensitive:
cmd.append("-c")
if exclude_dos:
cmd.append("--exclude=/dos/")
cmd.extend(query.split())
logger.info(f"Searching: {' '.join(cmd)}")
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
data = json.loads(result.stdout)
return self._parse_results(data)
except json.JSONDecodeError as e:
logger.error(f"Failed to parse searchsploit output: {e}")
return []
except subprocess.TimeoutExpired:
logger.error("Search timed out")
return []
def search_by_cve(self, cve: str) -> List[Exploit]:
"""Search exploits by CVE number"""
# Normalize CVE format
cve = cve.upper().replace("CVE-", "").strip()
if not cve.startswith("CVE-"):
cve = f"CVE-{cve}"
cmd = ["searchsploit", "-j", "--cve", cve]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
data = json.loads(result.stdout)
return self._parse_results(data)
except Exception as e:
logger.error(f"CVE search failed: {e}")
return []
def search_by_edb_id(self, edb_id: str) -> Optional[Exploit]:
"""Get specific exploit by EDB-ID"""
exploits = self.search(edb_id, title_only=False)
for exp in exploits:
if exp.edb_id == edb_id:
return exp
return None
def _parse_results(self, data: dict) -> List[Exploit]:
"""Parse searchsploit JSON output"""
exploits = []
if "RESULTS_EXPLOIT" not in data:
return exploits
for item in data["RESULTS_EXPLOIT"]:
try:
exploit = Exploit(
title=item.get("Title", "Unknown"),
edb_id=item.get("EDB-ID", "0"),
date_published=item.get("Date_Published", "Unknown"),
type=item.get("Type", "unknown"),
platform=item.get("Platform", "unknown"),
cve=item.get("Codes") if item.get("Codes") else None,
verified=item.get("Verified", "0") == "1",
path=item.get("Path", ""),
author=item.get("Author"),
)
exploits.append(exploit)
except Exception as e:
logger.warning(f"Failed to parse exploit entry: {e}")
continue
return exploits
def get_verified_exploits(self, exploits: List[Exploit]) -> List[Exploit]:
"""Filter only verified exploits"""
return [e for e in exploits if e.verified]
def get_remote_exploits(self, exploits: List[Exploit]) -> List[Exploit]:
"""Filter only remote exploits (not local)"""
return [e for e in exploits if e.type.lower() == "remote"]
def get_webapps_exploits(self, exploits: List[Exploit]) -> List[Exploit]:
"""Filter web application exploits"""
return [e for e in exploits if "webapps" in e.type.lower()]
def search_by_nmap_xml(self, nmap_xml_path: str) -> Dict[str, List[Exploit]]:
"""
Search exploits based on Nmap XML output
Returns dict mapping service names to exploits
"""
# Use defusedxml for safe XML parsing
try:
from defusedxml import ElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET # nosec B314 - Fallback
results = {}
try:
tree = ET.parse(nmap_xml_path) # nosec B314 - defusedxml handles XXE
root = tree.getroot()
for host in root.findall("host"):
for port in host.find("ports").findall("port"):
service = port.find("service")
if service is not None:
name = service.get("name", "")
version = service.get("version", "")
product = service.get("product", "")
# Search for this service
query = f"{product} {version}".strip() if product else name
if query and query not in results:
exploits = self.search(query, title_only=True)
if exploits:
results[query] = exploits
except Exception as e:
logger.error(f"Failed to parse Nmap XML: {e}")
return results
class ExploitRecommender:
"""
Recommends exploits based on discovered services
"""
def __init__(self):
self.searcher = SearchSploitIntegration()
def analyze_service(
self,
service_name: str,
version: Optional[str] = None,
port: Optional[int] = None,
) -> Dict:
"""
Analyze a service and recommend exploits
Returns dict with:
- service: service name
- version: detected version
- exploits: list of relevant exploits
- prioritized: exploits sorted by relevance
"""
query_parts = [service_name]
if version:
query_parts.append(version)
exploits = self.searcher.search(" ".join(query_parts))
# Prioritize
verified = self.searcher.get_verified_exploits(exploits)
remote = self.searcher.get_remote_exploits(exploits)
self.searcher.get_webapps_exploits(exploits)
# Scoring
scored = []
for exp in exploits:
score = 0
if exp.verified:
score += 10
if exp.type.lower() == "remote":
score += 5
if "webapps" in exp.type.lower():
score += 3
if version and version in exp.title:
score += 2
scored.append((score, exp))
scored.sort(reverse=True, key=lambda x: x[0])
prioritized = [exp for _, exp in scored]
return {
"service": service_name,
"version": version,
"port": port,
"total_exploits": len(exploits),
"verified_count": len(verified),
"remote_count": len(remote),
"exploits": exploits,
"prioritized": prioritized[:10], # Top 10
}
def generate_report(self, services: List[Dict]) -> str:
"""Generate a text report for multiple services"""
report = []
report.append("=" * 80)
report.append("EXPLOIT RECOMMENDATION REPORT")
report.append("=" * 80)
report.append("")
for svc in services:
name = svc.get("name", "Unknown")
version = svc.get("version", "")
port = svc.get("port", "")
report.append(f"\n{'─' * 80}")
report.append(f"Service: {name} {version} (Port: {port})")
report.append(f"{'─' * 80}")
analysis = self.analyze_service(name, version, port)
if analysis["prioritized"]:
report.append(f"\nFound {analysis['total_exploits']} exploits ({analysis['verified_count']} verified)")
report.append("\nTop Recommendations:")
for i, exp in enumerate(analysis["prioritized"][:5], 1):
status = "✓ VERIFIED" if exp.verified else "✗ Unverified"
report.append(f"\n {i}. [{status}] EDB-{exp.edb_id}")
report.append(f" Title: {exp.title}")
report.append(f" Type: {exp.type} | Platform: {exp.platform}")
if exp.cve:
report.append(f" CVE: {exp.cve}")
report.append(f" URL: {exp.url}")
else:
report.append("\n No exploits found in database.")
report.append("\n" + "=" * 80)
return "\n".join(report)
# Convenience functions for quick use
def quick_search(query: str) -> List[Exploit]:
"""Quick search function"""
searcher = SearchSploitIntegration()
return searcher.search(query)
def find_cve_exploits(cve: str) -> List[Exploit]:
"""Find exploits by CVE"""
searcher = SearchSploitIntegration()
return searcher.search_by_cve(cve)
if __name__ == "__main__":
# Demo usage
print("=" * 80)
print("SearchSploit Integration Demo")
print("=" * 80)
# Example 1: Search for WordPress SQL injection
print("\n[1] Searching for WordPress SQL Injection...")
searcher = SearchSploitIntegration()
results = searcher.search("wordpress sql injection", title_only=True)
verified = searcher.get_verified_exploits(results)
print(f" Found {len(results)} exploits ({len(verified)} verified)")
if results:
print(f" Top result: {results[0].title}")
print(f" EDB-ID: {results[0].edb_id}")
print(f" URL: {results[0].url}")
# Example 2: Service Analysis
print("\n[2] Analyzing Redis service...")
recommender = ExploitRecommender()
analysis = recommender.analyze_service("redis", "8.0.2")
print(f" Service: {analysis['service']} {analysis['version']}")
print(f" Total Exploits: {analysis['total_exploits']}")
print(f" Top Exploit: {analysis['prioritized'][0].title if analysis['prioritized'] else 'None'}")
# Example 3: CVE Search
print("\n[3] Searching by CVE...")
cve_exploits = searcher.search_by_cve("2025-32023")
if cve_exploits:
print(f" Found: {cve_exploits[0].title}")
print("\n" + "=" * 80)
print("Demo complete!")
print("=" * 80)

Xet Storage Details

Size:
12.8 kB
·
Xet hash:
a1f2d166109bd7df585072a74f9af573a41028e1cfecf479d548180bcb0179ae

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