Buckets:

download
raw
15.3 kB
#!/usr/bin/env python3
"""
Service Vulnerability Auto-Mapper for Zen-AI-Pentest
Automatically maps discovered services to known vulnerabilities
"""
import json
import logging
import re
from dataclasses import dataclass
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from modules.searchsploit_integration import (
Exploit,
ExploitRecommender,
SearchSploitIntegration,
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class DiscoveredService:
"""Represents a discovered service during scanning"""
name: str
port: int
protocol: str = "tcp"
version: Optional[str] = None
product: Optional[str] = None
banner: Optional[str] = None
cpe: Optional[str] = None
def get_identifier(self) -> str:
"""Get unique identifier for this service"""
return f"{self.name}_{self.port}"
@dataclass
class VulnerabilityMatch:
"""Links a service to potential exploits"""
service: DiscoveredService
exploits: List[Exploit]
confidence_score: float # 0.0 - 1.0
match_reason: str
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
return {
"service": {
"name": self.service.name,
"port": self.service.port,
"version": self.service.version,
"protocol": self.service.protocol,
},
"exploits": [
{
"edb_id": e.edb_id,
"title": e.title,
"type": e.type,
"platform": e.platform,
"verified": e.verified,
"cve": e.cve,
"url": e.url,
}
for e in self.exploits[:5] # Top 5 only
],
"confidence_score": self.confidence_score,
"match_reason": self.match_reason,
"timestamp": datetime.now().isoformat(),
}
class ServiceVulnerabilityMapper:
"""
Main class for mapping services to vulnerabilities
"""
def __init__(self):
self.searcher = SearchSploitIntegration()
self.recommender = ExploitRecommender()
self.mapped_services: Dict[str, VulnerabilityMatch] = {}
# Common service mappings for better search
self.service_aliases = {
"http": ["apache", "nginx", "iis"],
"https": ["apache", "nginx", "iis"],
"ssh": ["openssh", "libssh"],
"ftp": ["vsftpd", "proftpd", "pure-ftpd"],
"smtp": ["postfix", "exim", "sendmail"],
"mysql": ["mariadb", "percona"],
"postgresql": ["postgres"],
"redis": ["redis-server"],
"mongodb": ["mongo"],
"docker": ["dockerd", "containerd"],
}
def normalize_version(self, version: str) -> str:
"""Normalize version string for better matching"""
if not version:
return ""
# Remove common prefixes
version = re.sub(r"^(v|version|ver)\.?", "", version, flags=re.I)
# Extract version numbers (e.g., "Apache httpd 2.4.41" -> "2.4.41")
match = re.search(r"(\d+\.\d+(?:\.\d+)?)", version)
if match:
return match.group(1)
return version.strip()
def get_search_terms(self, service: DiscoveredService) -> List[str]:
"""Generate search terms for a service"""
terms = []
# Primary search term
if service.product:
terms.append(service.product)
else:
terms.append(service.name)
# Add version if available
if service.version:
version = self.normalize_version(service.version)
if version:
terms.append(version)
# Add aliases for common services
if service.name.lower() in self.service_aliases:
for alias in self.service_aliases[service.name.lower()]:
alias_term = alias
if service.version:
alias_term += f" {service.version}"
terms.append(alias_term)
return terms
def calculate_confidence(self, service: DiscoveredService, exploits: List[Exploit]) -> Tuple[float, str]:
"""
Calculate confidence score for vulnerability match
Returns (score, reason)
"""
if not exploits:
return 0.0, "No exploits found"
verified_count = sum(1 for e in exploits if e.verified)
total = len(exploits)
# Base score on verified ratio
score = verified_count / total if total > 0 else 0
reasons = []
if verified_count > 0:
reasons.append(f"{verified_count} verified exploits")
# Version match bonus
if service.version:
version = self.normalize_version(service.version)
for exp in exploits[:5]:
if version in exp.title:
score += 0.1
reasons.append(f"version '{version}' matched")
break
# Cap at 1.0
score = min(1.0, score)
return score, "; ".join(reasons) if reasons else "Generic match"
def map_service(self, service: DiscoveredService) -> VulnerabilityMatch:
"""
Map a single service to vulnerabilities
"""
logger.info(f"Mapping service: {service.name} on port {service.port}")
# Try multiple search strategies
all_exploits = []
search_terms = self.get_search_terms(service)
for term in search_terms:
try:
exploits = self.searcher.search(term, title_only=True)
all_exploits.extend(exploits)
except Exception as e:
logger.warning(f"Search failed for '{term}': {e}")
# Remove duplicates
seen_ids = set()
unique_exploits = []
for exp in all_exploits:
if exp.edb_id not in seen_ids:
seen_ids.add(exp.edb_id)
unique_exploits.append(exp)
# Score and filter
score, reason = self.calculate_confidence(service, unique_exploits)
# Sort by relevance
def relevance_sort(exp: Exploit) -> int:
points = 0
if exp.verified:
points += 10
if exp.type.lower() == "remote":
points += 5
if service.version and service.version in exp.title:
points += 3
return points
sorted_exploits = sorted(unique_exploits, key=relevance_sort, reverse=True)
match = VulnerabilityMatch(
service=service,
exploits=sorted_exploits[:10], # Top 10
confidence_score=score,
match_reason=reason,
)
self.mapped_services[service.get_identifier()] = match
return match
def map_services(self, services: List[DiscoveredService]) -> List[VulnerabilityMatch]:
"""
Map multiple services to vulnerabilities
"""
results = []
for service in services:
match = self.map_service(service)
results.append(match)
return results
def get_high_confidence_matches(self, threshold: float = 0.5) -> List[VulnerabilityMatch]:
"""Get matches above confidence threshold"""
return [match for match in self.mapped_services.values() if match.confidence_score >= threshold]
def get_verified_exploits_only(self) -> Dict[str, List[Exploit]]:
"""Get only verified exploits for all mapped services"""
result = {}
for identifier, match in self.mapped_services.items():
verified = [e for e in match.exploits if e.verified]
if verified:
result[identifier] = verified
return result
def export_to_json(self, filepath: str):
"""Export all mappings to JSON"""
data = {
"timestamp": datetime.now().isoformat(),
"total_services": len(self.mapped_services),
"mappings": [match.to_dict() for match in self.mapped_services.values()],
}
with open(filepath, "w") as f:
json.dump(data, f, indent=2)
logger.info(f"Exported mappings to {filepath}")
def generate_attack_plan(self) -> Dict:
"""
Generate a prioritized attack plan based on mappings
"""
# Sort by confidence and exploit count
sorted_matches = sorted(
self.mapped_services.values(),
key=lambda m: (m.confidence_score, len(m.exploits)),
reverse=True,
)
plan = {
"high_priority": [],
"medium_priority": [],
"low_priority": [],
"informational": [],
}
for match in sorted_matches:
entry = {
"service": match.service.name,
"port": match.service.port,
"version": match.service.version,
"exploit_count": len(match.exploits),
"verified_count": sum(1 for e in match.exploits if e.verified),
"confidence": match.confidence_score,
"top_exploit": (match.exploits[0].title if match.exploits else None),
}
if match.confidence_score >= 0.7 and entry["verified_count"] > 0:
plan["high_priority"].append(entry)
elif match.confidence_score >= 0.5:
plan["medium_priority"].append(entry)
elif match.exploits:
plan["low_priority"].append(entry)
else:
plan["informational"].append(entry)
return plan
def print_report(self):
"""Print a formatted report to console"""
print("\n" + "=" * 80)
print("SERVICE VULNERABILITY MAPPING REPORT")
print("=" * 80)
print(f"\nTotal Services Analyzed: {len(self.mapped_services)}\n")
# High confidence first
high_conf = self.get_high_confidence_matches(0.5)
if high_conf:
print("\n🔴 HIGH CONFIDENCE MATCHES:")
print("-" * 80)
for match in high_conf:
print(
f"\n [{match.service.port}/{match.service.protocol}] {match.service.name} {match.service.version or ''}"
)
print(f" Confidence: {match.confidence_score:.1%} - {match.match_reason}")
print(f" Exploits Found: {len(match.exploits)}")
for i, exp in enumerate(match.exploits[:3], 1):
status = "✓" if exp.verified else " "
print(f" {i}. [{status}] EDB-{exp.edb_id}: {exp.title[:60]}...")
# Low confidence
low_conf = [m for m in self.mapped_services.values() if m.confidence_score < 0.5 and m.exploits]
if low_conf:
print("\n\n🟡 LOW CONFIDENCE MATCHES:")
print("-" * 80)
for match in low_conf:
print(f" [{match.service.port}] {match.service.name}: {len(match.exploits)} exploits (unverified)")
# No exploits
no_exp = [m for m in self.mapped_services.values() if not m.exploits]
if no_exp:
print("\n\n🟢 NO KNOWN EXPLOITS:")
print("-" * 80)
for match in no_exp:
print(f" [{match.service.port}] {match.service.name}")
# Attack plan summary
plan = self.generate_attack_plan()
print("\n\n📋 ATTACK PLAN SUMMARY:")
print("-" * 80)
print(f" High Priority: {len(plan['high_priority'])} targets")
print(f" Medium Priority: {len(plan['medium_priority'])} targets")
print(f" Low Priority: {len(plan['low_priority'])} targets")
print("\n" + "=" * 80)
def quick_map_from_nmap(nmap_xml_path: str) -> ServiceVulnerabilityMapper:
"""
Quick function to map services from Nmap XML
"""
# Use defusedxml for safe XML parsing (prevents XXE attacks)
try:
from defusedxml import ElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET # nosec B314 - Fallback with caution
mapper = ServiceVulnerabilityMapper()
try:
tree = ET.parse(nmap_xml_path) # nosec B314 - defusedxml handles XXE
root = tree.getroot()
services = []
for host in root.findall("host"):
host.find("address").get("addr", "unknown")
ports_elem = host.find("ports")
if ports_elem is None:
continue
for port in ports_elem.findall("port"):
port_num = int(port.get("portid", 0))
protocol = port.get("protocol", "tcp")
service_elem = port.find("service")
if service_elem is not None:
svc = DiscoveredService(
name=service_elem.get("name", "unknown"),
port=port_num,
protocol=protocol,
version=service_elem.get("version"),
product=service_elem.get("product"),
banner=service_elem.get("extrainfo"),
cpe=service_elem.get("cpe"),
)
services.append(svc)
mapper.map_services(services)
return mapper
except Exception as e:
logger.error(f"Failed to parse Nmap XML: {e}")
return mapper
# Integration with Zen-AI-Pentest scanner
def analyze_scan_results(scan_results: Dict) -> ServiceVulnerabilityMapper:
"""
Analyze scan results and map to vulnerabilities
scan_results format:
{
'host': '192.168.1.1',
'services': [
{'name': 'http', 'port': 80, 'version': 'Apache 2.4.41'},
...
]
}
"""
mapper = ServiceVulnerabilityMapper()
services = []
for svc_data in scan_results.get("services", []):
svc = DiscoveredService(
name=svc_data.get("name", "unknown"),
port=svc_data.get("port", 0),
protocol=svc_data.get("protocol", "tcp"),
version=svc_data.get("version"),
product=svc_data.get("product"),
banner=svc_data.get("banner"),
)
services.append(svc)
mapper.map_services(services)
return mapper
if __name__ == "__main__":
# Demo usage
print("=" * 80)
print("Service Vulnerability Mapper Demo")
print("=" * 80)
# Example services (like from your docker-compose)
demo_services = [
DiscoveredService(name="http", port=8081, product="WordPress", version="6.4"),
DiscoveredService(name="redis", port=6379, product="Redis", version="7.0"),
DiscoveredService(name="mysql", port=3306, product="MySQL", version="8.0"),
DiscoveredService(name="http", port=8082, product="DVWA", version=None),
]
mapper = ServiceVulnerabilityMapper()
mapper.map_services(demo_services)
mapper.print_report()
# Export example - use tempfile for security
import tempfile
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
mapper.export_to_json(f.name)
print(f"\n✓ Exported to {f.name}")

Xet Storage Details

Size:
15.3 kB
·
Xet hash:
17865faf86254d5c3207be536840d3fcd614d60cb7be7bdfb4ae9b53c0f00a07

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