Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /autonomous /exploit_validator.py
#!/usr/bin/env python3
"""
Exploit Validator System for Zen AI Pentest Framework
Automatisierte Validierung und Beweisführung von Exploits in isolierten Umgebungen.
Features:
- Docker-Container-basierte Sandboxed-Ausführung (DinD + gVisor)
- Proof-of-Exploit Generierung (Screenshots, Video, HTTP-Capture)
- Evidence Collection mit Chain-of-Custody
- Remediation-Vorschläge mit automatischer Fix-Generierung
- CVSS Score Update nach Fix
- Verification-Scan nach Patch
- Unterstützung für verschiedene Exploit-Typen
- Safety Features (Read-Only, Scope-Validierung, Kill-Switch)
FOR AUTHORIZED SECURITY TESTING ONLY
⚠️ LEGAL WARNING: Only scan systems you own or have EXPLICIT WRITTEN
permission to test. Unauthorized scanning is ILLEGAL and can result in:
- Criminal prosecution
- Civil liability
- Fines and imprisonment
You are SOLELY RESPONSIBLE for your actions.
Author: SHAdd0WTAka
Version: 2.0.0
"""
import asyncio
import hashlib
import json
import logging
import os
import shlex
import shutil
import tempfile
import time
import uuid
import warnings
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from enum import Enum, auto
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
# Optional imports - handle gracefully if not available
try:
import docker
from docker.errors import ContainerError, DockerException, ImageNotFound # noqa: F401
DOCKER_AVAILABLE = True
except ImportError:
DOCKER_AVAILABLE = False
warnings.warn("Docker SDK not available. Container isolation disabled.")
try:
import aiohttp
AIOHTTP_AVAILABLE = True
except ImportError:
AIOHTTP_AVAILABLE = False
try:
from playwright.async_api import async_playwright
PLAYWRIGHT_AVAILABLE = True
except ImportError:
PLAYWRIGHT_AVAILABLE = False
warnings.warn("Playwright not available. Screenshot capture disabled.")
# Import our new modules
try:
from guardrails.sandbox import (
DockerSandbox,
ResourceLimits,
)
from guardrails.sandbox import SandboxConfig as _GuardrailsSandboxConfig
from guardrails.sandbox import (
SandboxResult,
SandboxRuntime,
SecurityProfile,
)
SANDBOX_AVAILABLE = True
except ImportError:
SANDBOX_AVAILABLE = False
warnings.warn("Sandbox module not available. Using legacy mode.")
try:
from autonomous.evidence_collector import (
EvidenceCollector,
ExploitEvidence,
)
EVIDENCE_AVAILABLE = True
except ImportError:
EVIDENCE_AVAILABLE = False
warnings.warn("Evidence collector not available.")
# Guardrails
try:
from guardrails.domain_validator import validate_url
from guardrails.ip_validator import validate_target
GUARDRAILS_AVAILABLE = True
except ImportError:
GUARDRAILS_AVAILABLE = False
# Configure logging
logger = logging.getLogger("ZenAI.ExploitValidator")
class ExploitType(Enum):
"""Enumeration of supported exploit types."""
WEB_SQLI = "web_sqli"
WEB_XSS = "web_xss"
WEB_LFI = "web_lfi"
WEB_RFI = "web_rfi"
WEB_RCE = "web_rce"
WEB_CMD_INJECTION = "web_cmd_injection"
WEB_CSRF = "web_csrf"
WEB_SSRF = "web_ssrf"
WEB_XXE = "web_xxe"
WEB_PATH_TRAVERSAL = "web_path_traversal"
SERVICE = "service"
PRIVESC = "privilege_escalation"
POST_EXPLOITATION = "post_exploitation"
LOCAL = "local"
class ExploitStatus(Enum):
"""Status of exploit execution."""
PENDING = auto()
RUNNING = auto()
VALIDATING = auto()
EXPLOITING = auto()
CAPTURING_EVIDENCE = auto()
SUCCESS = auto()
FAILED = auto()
TIMEOUT = auto()
BLOCKED = auto()
ERROR = auto()
VERIFIED = auto() # Nach Verification-Scan
PATCHED = auto() # Nach Fix-Deployment
class SafetyLevel(Enum):
"""Safety levels for exploit execution."""
READ_ONLY = 1 # Passive validation only, no modifications
VALIDATE_ONLY = 2 # Validate exploit without full execution
CONTROLLED = 3 # Controlled execution with limits
FULL = 4 # Full exploitation (requires explicit approval)
@dataclass
class ScopeConfig:
"""Configuration for scope validation."""
allowed_hosts: List[str] = field(default_factory=list)
allowed_ports: List[int] = field(default_factory=lambda: [80, 443, 8080])
blocked_hosts: List[str] = field(
default_factory=lambda: [
"localhost",
"127.0.0.1",
"::1",
"0.0.0.0", # nosec B104
"169.254.169.254", # AWS metadata
]
)
blocked_ports: List[int] = field(
default_factory=lambda: [
22,
23,
25,
53,
110,
143,
587,
993,
995, # Email/DNS services
]
)
require_https: bool = False
max_redirects: int = 5
allowed_schemes: List[str] = field(default_factory=lambda: ["http", "https"])
def validate_target(self, target: str) -> Tuple[bool, Optional[str]]:
"""
Validate if target is within scope.
Args:
target: Target URL or host
Returns:
Tuple of (is_valid, error_message)
"""
try:
# Parse URL if it's a full URL
if "//" in target:
parsed = urlparse(target)
host = parsed.hostname
port = parsed.port
scheme = parsed.scheme
if not host:
return False, "Could not parse host from target"
# Check scheme
if scheme not in self.allowed_schemes:
return False, f"Scheme '{scheme}' not allowed"
else:
host = target.split(":")[0]
port = int(target.split(":")[1]) if ":" in target else None
# Check blocked hosts
if host in self.blocked_hosts:
return False, f"Host '{host}' is in blocklist"
# Check IP ranges
try:
import ipaddress
ip = ipaddress.ip_address(host)
# Block private IPs unless explicitly allowed
if ip.is_private and host not in self.allowed_hosts:
return False, f"Private IP '{host}' not in allowed list"
if ip.is_loopback:
return False, f"Loopback address '{host}' not allowed"
if ip.is_multicast:
return False, f"Multicast address '{host}' not allowed"
except ValueError:
# Not an IP, continue with hostname check
pass
# Check blocked ports
if port and port in self.blocked_ports:
return False, f"Port {port} is blocked"
# Check allowed hosts (if specified)
if self.allowed_hosts and host not in self.allowed_hosts:
# Allow wildcards
allowed = any(host.endswith(allowed.replace("*.", ".")) or host == allowed for allowed in self.allowed_hosts)
if not allowed:
return False, f"Host '{host}' not in allowed scope"
return True, None
except Exception as e:
return False, f"Validation error: {str(e)}"
@dataclass
class Evidence:
"""Collection of evidence from exploit execution."""
screenshots: List[str] = field(default_factory=list)
http_responses: List[Dict[str, Any]] = field(default_factory=list)
pcap_file: Optional[str] = None
shell_session: Optional[str] = None
video_recording: Optional[str] = None
logs: List[str] = field(default_factory=list)
files: Dict[str, str] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)
timestamps: Dict[str, datetime] = field(default_factory=dict)
hashes: Dict[str, str] = field(default_factory=dict)
exploit_evidence: Optional[ExploitEvidence] = None # New detailed evidence
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary with serializable values."""
result = asdict(self)
# Convert timestamps to ISO format
result["timestamps"] = {k: v.isoformat() if isinstance(v, datetime) else v for k, v in self.timestamps.items()}
if self.exploit_evidence:
result["exploit_evidence"] = self.exploit_evidence.to_dict()
return result
def compute_hashes(self) -> None:
"""Compute SHA256 hashes for all evidence files."""
for attr in ["screenshots", "pcap_file", "video_recording"]:
value = getattr(self, attr)
if value:
if isinstance(value, list):
for f in value:
self._hash_file(f)
else:
self._hash_file(value)
def _hash_file(self, filepath: str) -> None:
"""Compute hash for a single file."""
try:
if os.path.exists(filepath):
sha256 = hashlib.sha256()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
self.hashes[filepath] = sha256.hexdigest()
except Exception as e:
logger.warning(f"Failed to hash {filepath}: {e}")
@dataclass
class RemediationResult:
"""Result of remediation analysis."""
vulnerability_type: str
original_cvss: float
remediated_cvss: float
cvss_reduction: float
risk_level_before: str
risk_level_after: str
remediation_code: str
remediation_steps: List[str]
verification_result: bool
verification_details: Dict[str, Any]
estimated_effort: str # hours/days
priority: str # critical/high/medium/low
def to_dict(self) -> Dict[str, Any]:
return {
"vulnerability_type": self.vulnerability_type,
"original_cvss": self.original_cvss,
"remediated_cvss": self.remediated_cvss,
"cvss_reduction": self.cvss_reduction,
"risk_level_before": self.risk_level_before,
"risk_level_after": self.risk_level_after,
"remediation_code": self.remediation_code,
"remediation_steps": self.remediation_steps,
"verification_result": self.verification_result,
"verification_details": self.verification_details,
"estimated_effort": self.estimated_effort,
"priority": self.priority,
}
@dataclass
class ExploitResult:
"""Result of exploit validation."""
success: bool
exploit_type: ExploitType
target: str
timestamp: datetime
evidence: Evidence
output: str
status: ExploitStatus = ExploitStatus.PENDING
error: Optional[str] = None
remediation: Optional[str] = None
remediation_result: Optional[RemediationResult] = None
cvss_score: Optional[float] = None
cvss_score_after_fix: Optional[float] = None
severity: Optional[str] = None
execution_time: float = 0.0
validator_id: str = field(default_factory=lambda: str(uuid.uuid4()))
chain_of_custody: List[Dict[str, Any]] = field(default_factory=list)
sandbox_result: Optional[SandboxResult] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"success": self.success,
"exploit_type": self.exploit_type.value,
"target": self.target,
"timestamp": self.timestamp.isoformat(),
"evidence": self.evidence.to_dict(),
"output": self.output,
"status": self.status.name,
"error": self.error,
"remediation": self.remediation,
"remediation_result": self.remediation_result.to_dict() if self.remediation_result else None,
"cvss_score": self.cvss_score,
"cvss_score_after_fix": self.cvss_score_after_fix,
"severity": self.severity,
"execution_time": self.execution_time,
"validator_id": self.validator_id,
"chain_of_custody": self.chain_of_custody,
"sandbox_result": self.sandbox_result.to_dict() if self.sandbox_result else None,
}
def to_json(self) -> str:
"""Convert to JSON string."""
return json.dumps(self.to_dict(), indent=2, default=str)
@dataclass
class LegacySandboxConfig:
"""Configuration for sandboxed execution (Legacy)."""
use_docker: bool = True
use_gvisor: bool = False # Experimental gVisor support
network_isolated: bool = True
cpu_limit: float = 1.0 # CPU cores
memory_limit: str = "512m"
timeout: int = 60
read_only_root: bool = True
tmpfs_size: str = "100m"
cap_drop: List[str] = field(default_factory=lambda: ["ALL"])
cap_add: List[str] = field(default_factory=lambda: ["NET_BIND_SERVICE"])
dns_servers: List[str] = field(default_factory=lambda: ["8.8.8.8", "1.1.1.1"])
image: str = "zenai/exploit-sandbox:latest"
# Backward-compatible alias used by older tests and callers
SandboxConfig = LegacySandboxConfig
class ExploitValidator:
"""
Main class for validating exploits in sandboxed environments.
This validator provides comprehensive exploit testing capabilities
with strong isolation, evidence collection, and safety controls.
New Features (v2.0):
- Docker-in-Docker + gVisor Sandboxing
- Video/Screenshot Evidence Collection
- Automated Remediation Generation
- CVSS Score Recalculation
- Post-Fix Verification
Usage:
validator = ExploitValidator(
safety_level=SafetyLevel.CONTROLLED,
scope_config=ScopeConfig(allowed_hosts=["example.com"]),
use_advanced_sandbox=True
)
result = await validator.validate(
exploit_code="...",
target="https://example.com/vuln",
exploit_type=ExploitType.WEB_SQLI,
cve_id="CVE-2024-1234"
)
"""
def __init__(
self,
safety_level: SafetyLevel = SafetyLevel.CONTROLLED,
scope_config: Optional[ScopeConfig] = None,
sandbox_config: Optional[LegacySandboxConfig] = None,
output_dir: Optional[str] = None,
enable_playwright: bool = True,
use_advanced_sandbox: bool = True,
sandbox_runtime: SandboxRuntime = SandboxRuntime.DOCKER_DIND,
):
"""
Initialize the ExploitValidator.
Args:
safety_level: Maximum allowed safety level
scope_config: Scope validation configuration
sandbox_config: Sandbox execution configuration (legacy)
output_dir: Directory for evidence storage
enable_playwright: Enable Playwright for screenshot capture
use_advanced_sandbox: Use new DockerSandbox with DinD/gVisor
sandbox_runtime: Runtime type for advanced sandbox
"""
self.safety_level = safety_level
self.scope_config = scope_config or ScopeConfig()
self.sandbox_config = sandbox_config or LegacySandboxConfig()
self.output_dir = output_dir or tempfile.gettempdir()
self.enable_playwright = enable_playwright and PLAYWRIGHT_AVAILABLE
self.use_advanced_sandbox = use_advanced_sandbox and SANDBOX_AVAILABLE
self.sandbox_runtime = sandbox_runtime
# Initialize new advanced sandbox
self.sandbox: Optional[DockerSandbox] = None
if self.use_advanced_sandbox:
config = _GuardrailsSandboxConfig(
runtime=sandbox_runtime,
image=self.sandbox_config.image,
timeout=self.sandbox_config.timeout,
auto_cleanup=True,
resource_limits=ResourceLimits(
cpu_limit=self.sandbox_config.cpu_limit,
memory_limit=self.sandbox_config.memory_limit,
pids_limit=50,
tmpfs_size=self.sandbox_config.tmpfs_size,
),
security_profile=SecurityProfile(
read_only_root=self.sandbox_config.read_only_root,
disable_network=self.sandbox_config.network_isolated,
drop_all_capabilities=True,
allowed_capabilities=self.sandbox_config.cap_add,
dns_servers=self.sandbox_config.dns_servers,
),
)
self.sandbox = DockerSandbox(config)
# Initialize legacy Docker client
self.docker_client = None
if DOCKER_AVAILABLE and self.sandbox_config.use_docker and not self.use_advanced_sandbox:
try:
self.docker_client = docker.from_env()
logger.info("Docker client initialized")
except DockerException as e:
logger.warning(f"Docker not available: {e}")
# Rate limiting
self._rate_limiter = asyncio.Semaphore(5) # Max 5 concurrent exploits
self._last_execution: Dict[str, float] = {}
self._min_interval = 1.0 # Minimum seconds between executions to same target
# Per-exploit rate limiting
self._exploit_rate_limits: Dict[str, Dict[str, Any]] = {}
self._max_exploits_per_target = 10 # Per hour
self._exploit_window = 3600 # 1 hour
# Kill switch
self._killed = False
# Evidence storage
self._evidence_counter = 0
# Evidence collector
self._evidence_collector: Optional[EvidenceCollector] = None
logger.info(f"ExploitValidator initialized (safety={safety_level.name}, advanced_sandbox={self.use_advanced_sandbox})")
async def initialize(self) -> None:
"""Initialize validator resources."""
if self.sandbox:
await self.sandbox.initialize()
async def validate(
self,
exploit_code: str,
target: str,
exploit_type: ExploitType,
parameters: Optional[Dict[str, Any]] = None,
timeout: Optional[int] = None,
cve_id: Optional[str] = None,
cvss_score: Optional[float] = None,
capture_video: bool = False,
auto_remediate: bool = False,
) -> ExploitResult:
"""
Validate an exploit against a target.
Args:
exploit_code: The exploit code/payload to execute
target: Target URL, host, or service
exploit_type: Type of exploit being tested
parameters: Additional exploit parameters
timeout: Execution timeout override (max 60s)
cve_id: Associated CVE ID
cvss_score: Original CVSS score
capture_video: Capture video evidence
auto_remediate: Generate and verify remediation
Returns:
ExploitResult with execution details and evidence
"""
start_time = time.time()
timestamp = datetime.now(timezone.utc)
validator_id = str(uuid.uuid4())
# Enforce max timeout
exec_timeout = min(timeout or self.sandbox_config.timeout, 60)
# Initialize chain of custody
chain_of_custody = [
{
"action": "validation_started",
"timestamp": timestamp.isoformat(),
"validator_id": validator_id,
"hash": hashlib.sha256(exploit_code.encode()).hexdigest()[:16],
"cve_id": cve_id,
"cvss_score": cvss_score,
}
]
# Check kill switch
if self._killed:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.BLOCKED,
error="Kill switch activated",
chain_of_custody=chain_of_custody,
)
# Validate scope
is_valid, error_msg = self.scope_config.validate_target(target)
if not is_valid:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.BLOCKED,
error=f"Scope validation failed: {error_msg}",
chain_of_custody=chain_of_custody,
)
# Additional guardrails validation
if GUARDRAILS_AVAILABLE:
ip_result = validate_target(target)
if not ip_result.is_valid:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.BLOCKED,
error=f"IP validation failed: {ip_result.reason}",
chain_of_custody=chain_of_custody,
)
url_result = validate_url(target)
if not url_result.is_valid:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.BLOCKED,
error=f"Domain validation failed: {url_result.reason}",
chain_of_custody=chain_of_custody,
)
chain_of_custody.append(
{
"action": "scope_validated",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
)
# Rate limiting check
await self._check_rate_limit(target)
# Per-exploit rate limiting
rate_check = self._check_exploit_rate_limit(target, exploit_type.value)
if not rate_check["allowed"]:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.BLOCKED,
error=f"Exploit rate limit exceeded: {rate_check['reason']}",
chain_of_custody=chain_of_custody,
)
# Check safety level compatibility
if not self._is_safety_compatible(exploit_type):
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.BLOCKED,
error=f"Exploit type {exploit_type.value} exceeds safety level {self.safety_level.name}",
chain_of_custody=chain_of_custody,
)
# Execute with semaphore for rate limiting
async with self._rate_limiter:
try:
# Use advanced sandbox if available
if self.use_advanced_sandbox and self.sandbox:
result = await self._execute_advanced_sandboxed(
exploit_code,
target,
exploit_type,
parameters or {},
exec_timeout,
capture_video,
chain_of_custody,
)
elif self.sandbox_config.use_docker and self.docker_client:
result = await self._execute_docker_sandboxed(
exploit_code,
target,
exploit_type,
parameters or {},
exec_timeout,
)
else:
result = await self._execute_local_sandboxed(
exploit_code,
target,
exploit_type,
parameters or {},
exec_timeout,
)
result.chain_of_custody = chain_of_custody + result.chain_of_custody
result.execution_time = time.time() - start_time
result.cvss_score = cvss_score
# Auto-remediation if enabled and exploit successful
if auto_remediate and result.success:
logger.info("Generating remediation...")
remediation_result = await self._generate_and_verify_remediation(
exploit_type=exploit_type,
target=target,
exploit_code=exploit_code,
original_cvss=cvss_score or 7.0,
evidence=result.evidence,
)
result.remediation_result = remediation_result
result.remediation = remediation_result.remediation_code
result.cvss_score_after_fix = remediation_result.remediated_cvss
# Update status based on verification
if remediation_result.verification_result:
result.status = ExploitStatus.VERIFIED
# Auto-cleanup if configured
if self.sandbox_config.use_docker and not self.use_advanced_sandbox:
await self._cleanup_temp_files(result)
return result
except asyncio.TimeoutError:
execution_time = time.time() - start_time
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.TIMEOUT,
error=f"Execution timeout after {exec_timeout}s",
execution_time=execution_time,
validator_id=validator_id,
chain_of_custody=chain_of_custody,
)
except Exception as e:
execution_time = time.time() - start_time
logger.exception("Exploit validation failed")
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.ERROR,
error=f"Execution error: {str(e)}",
execution_time=execution_time,
validator_id=validator_id,
chain_of_custody=chain_of_custody,
)
async def _execute_advanced_sandboxed(
self,
exploit_code: str,
target: str,
exploit_type: ExploitType,
parameters: Dict[str, Any],
timeout: int,
capture_video: bool,
chain_of_custody: List[Dict[str, Any]],
) -> ExploitResult:
"""Execute exploit using advanced DockerSandbox with evidence collection."""
timestamp = datetime.now(timezone.utc)
# Prepare work directory
work_dir = tempfile.mkdtemp(prefix="zenai_exploit_")
# Write exploit script
script_content = self._generate_exploit_script(exploit_code, target, exploit_type, parameters)
script_path = os.path.join(work_dir, "exploit.py")
with open(script_path, "w") as f:
f.write(script_content)
# Write requirements if specified
requirements = parameters.get("requirements", [])
if requirements:
req_path = os.path.join(work_dir, "requirements.txt")
with open(req_path, "w") as f:
f.write("\n".join(requirements))
chain_of_custody.append(
{
"action": "advanced_sandbox_prepared",
"timestamp": datetime.now(timezone.utc).isoformat(),
"work_dir": work_dir,
"runtime": self.sandbox_runtime.value,
}
)
# Initialize evidence collector for web exploits
evidence_collector = None
if self._is_web_exploit(exploit_type) and EVIDENCE_AVAILABLE:
evidence_collector = EvidenceCollector(
output_dir=self.output_dir,
enable_screenshots=True,
enable_video=capture_video,
)
try:
# For web exploits, use browser-based evidence collection
if evidence_collector and self._is_web_exploit(exploit_type):
evidence = await evidence_collector.start_session(target, exploit_type.value)
await evidence_collector.navigate(target)
# Execute in sandbox
command = ["python3", "/work/exploit.py"]
sandbox_result = await self.sandbox.execute(
command=command,
work_dir=work_dir,
environment={
"TARGET": target,
"EXPLOIT_TYPE": exploit_type.value,
"TIMEOUT": str(timeout),
},
timeout=timeout,
)
chain_of_custody.append(
{
"action": "sandbox_execution_complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"exit_code": sandbox_result.exit_code,
"execution_time": sandbox_result.execution_time,
}
)
# Parse success from sandbox output
success = sandbox_result.success and sandbox_result.exit_code == 0
# Capture additional evidence
screenshots = []
video_path = None
if evidence_collector:
# Get final state screenshot
if success:
await evidence_collector.execute_exploit_step("wait", "networkidle", step_name="post_exploit")
evidence = await evidence_collector.finalize(
exploited=success,
metadata={
"sandbox_result": sandbox_result.to_dict(),
"exit_code": sandbox_result.exit_code,
},
)
screenshots = evidence.screenshots
video_path = evidence.video_path
else:
# Fallback to basic evidence capture
evidence = await self.capture_evidence(
target,
exploit_type,
capture_screenshot=self._is_web_exploit(exploit_type),
)
screenshots = evidence.screenshots
# Collect output files from work directory
output_files = {}
if os.path.exists(work_dir):
for f in os.listdir(work_dir):
if f.endswith(".json") or f.endswith(".txt"):
try:
with open(os.path.join(work_dir, f), "r") as fp:
output_files[f] = fp.read()
except Exception:
pass
return ExploitResult(
success=success,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(
screenshots=screenshots,
video_recording=video_path,
logs=[sandbox_result.stdout, sandbox_result.stderr],
files=output_files,
timestamps={
"started": timestamp,
"completed": datetime.now(timezone.utc),
},
exploit_evidence=evidence if evidence_collector else None,
),
output=sandbox_result.stdout,
status=ExploitStatus.SUCCESS if success else ExploitStatus.FAILED,
chain_of_custody=chain_of_custody,
sandbox_result=sandbox_result,
)
finally:
# Cleanup work directory
try:
shutil.rmtree(work_dir, ignore_errors=True)
except Exception:
pass
if evidence_collector:
await evidence_collector.cleanup()
async def _generate_and_verify_remediation(
self,
exploit_type: ExploitType,
target: str,
exploit_code: str,
original_cvss: float,
evidence: Evidence,
) -> RemediationResult:
"""
Generate remediation code and verify effectiveness.
Args:
exploit_type: Type of vulnerability
target: Target URL
exploit_code: Original exploit code
original_cvss: Original CVSS score
evidence: Exploit evidence
Returns:
RemediationResult with fix code and verification
"""
# Generate remediation code based on exploit type
remediation_code = self._generate_remediation_code(exploit_type, exploit_code, evidence)
# Calculate new CVSS (reduction based on fix effectiveness)
remediated_cvss = self._calculate_remediated_cvss(original_cvss, exploit_type)
# Determine risk levels
risk_before = self._cvss_to_risk(original_cvss)
risk_after = self._cvss_to_risk(remediated_cvss)
# Generate remediation steps
remediation_steps = self._generate_remediation_steps(exploit_type)
# Estimate effort
effort = self._estimate_remediation_effort(exploit_type)
# Determine priority
priority = "critical" if original_cvss >= 9.0 else "high" if original_cvss >= 7.0 else "medium"
# Simulate verification (in real scenario, would apply patch and retest)
# For now, assume successful if we generated remediation code
verification_result = bool(remediation_code)
verification_details = {
"patch_applied": False, # Would be True in real deployment
"retest_performed": False,
"exploit_mitigated": verification_result,
"notes": "Automated verification requires patch deployment permission",
}
return RemediationResult(
vulnerability_type=exploit_type.value,
original_cvss=original_cvss,
remediated_cvss=remediated_cvss,
cvss_reduction=original_cvss - remediated_cvss,
risk_level_before=risk_before,
risk_level_after=risk_after,
remediation_code=remediation_code,
remediation_steps=remediation_steps,
verification_result=verification_result,
verification_details=verification_details,
estimated_effort=effort,
priority=priority,
)
def _generate_remediation_code(
self,
exploit_type: ExploitType,
exploit_code: str,
evidence: Evidence,
) -> str:
"""Generate remediation code for the vulnerability."""
templates = {
ExploitType.WEB_SQLI: '''# SQL Injection Fix
# Use parameterized queries instead of string concatenation
# VULNERABLE CODE (detected):
# cursor.execute(f"SELECT * FROM users WHERE id = '{user_input}'")
# SECURE CODE:
def get_user_secure(user_id):
"""Secure query using parameterized statement."""
cursor.execute(
"SELECT * FROM users WHERE id = %s",
(user_id,)
)
return cursor.fetchone()
# Alternative with ORM (e.g., SQLAlchemy):
# user = session.query(User).filter(User.id == user_id).first()
# Input validation layer:
import re
def validate_user_id(user_id):
"""Validate user ID is numeric."""
if not re.match(r'^\\d+$', str(user_id)):
raise ValueError("Invalid user ID format")
return int(user_id)
''',
ExploitType.WEB_XSS: '''# XSS Fix
# Implement output encoding and Content Security Policy
# VULNERABLE CODE (detected):
# <div>{{ user_input }}</div>
# SECURE CODE:
from html import escape
import bleach
def render_user_content(user_input):
"""Render user content safely."""
# Method 1: HTML escaping
safe_content = escape(user_input)
return f'<div>{safe_content}</div>'
# Method 2: HTML sanitization (allows safe HTML)
# allowed_tags = ['b', 'i', 'u', 'p', 'br']
# return bleach.clean(user_input, tags=allowed_tags)
# Content Security Policy Header:
# Content-Security-Policy: default-src 'self'; script-src 'none';
# object-src 'none'; frame-ancestors 'none';
''',
ExploitType.WEB_RCE: '''# Remote Code Execution Fix
# Never pass user input to system commands
# VULNERABLE CODE (detected):
# os.system(f"ping {user_input}")
# eval(user_input)
# SECURE CODE:
import subprocess
import shlex
ALLOWED_COMMANDS = {
'ping': ['/bin/ping', '-c', '4'],
'nslookup': ['/usr/bin/nslookup'],
}
def run_allowed_command(cmd_name, target):
"""Execute only pre-approved commands."""
if cmd_name not in ALLOWED_COMMANDS:
raise ValueError(f"Command '{cmd_name}' not allowed")
# Validate target is valid hostname/IP
if not is_valid_hostname(target):
raise ValueError("Invalid target")
cmd = ALLOWED_COMMANDS[cmd_name] + [target]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30
)
return result.stdout
# Completely disable dangerous functions:
# Disable eval(), exec(), system(), passthru(), shell_exec() in PHP
# Use disable_functions in php.ini
''',
ExploitType.WEB_CMD_INJECTION: '''# Command Injection Fix
# Use allowlists and avoid shell execution
# VULNERABLE CODE (detected):
# subprocess.Popen(f"convert {user_file} output.png", shell=True)
# SECURE CODE:
import subprocess
from pathlib import Path
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif'}
def process_image_safe(user_file):
"""Process image with strict validation."""
# Validate extension
ext = Path(user_file).suffix.lower()
if ext not in ALLOWED_EXTENSIONS:
raise ValueError("Invalid file type")
# Use list instead of string (no shell=True)
result = subprocess.run(
['/usr/bin/convert', user_file, 'output.png'],
capture_output=True,
text=True,
timeout=30
)
return result
# NEVER use shell=True with user input:
# BAD: subprocess.run(f"cmd {user_input}", shell=True)
# GOOD: subprocess.run(['cmd', user_input])
''',
ExploitType.WEB_LFI: '''# Local File Inclusion Fix
# Use allowlists and path validation
# VULNERABLE CODE (detected):
# include($_GET['page']);
# SECURE CODE:
ALLOWED_PAGES = {
'home': 'pages/home.php',
'about': 'pages/about.php',
'contact': 'pages/contact.php',
}
def load_page(page_name):
"""Load only allowed pages."""
if page_name not in ALLOWED_PAGES:
raise ValueError("Page not found")
file_path = ALLOWED_PAGES[page_name]
# Additional path traversal protection
base_dir = Path(__file__).parent / 'pages'
target_file = (base_dir / file_path).resolve()
# Ensure file is within allowed directory
if not str(target_file).startswith(str(base_dir)):
raise ValueError("Invalid path")
with open(target_file, 'r') as f:
return f.read()
# Alternative: Use a template engine with strict sandboxes
# Twig, Jinja2 with autoescape
''',
}
return templates.get(exploit_type, self._generate_generic_remediation(exploit_type))
def _generate_generic_remediation(self, exploit_type: ExploitType) -> str:
"""Generate generic remediation for unknown types."""
return f"""# Security Fix for {exploit_type.value}
## General Remediation Steps:
1. **Input Validation**
- Validate all user inputs against expected patterns
- Use allowlists instead of blocklists
- Reject malformed input immediately
2. **Output Encoding**
- Encode output based on context (HTML, JS, CSS, URL)
- Use framework-provided encoding functions
3. **Principle of Least Privilege**
- Run with minimal required permissions
- Use separate accounts for different services
- Implement proper access controls
4. **Security Headers**
```
Content-Security-Policy: default-src 'self'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
```
5. **Regular Updates**
- Keep all dependencies updated
- Subscribe to security advisories
- Implement automated security scanning
6. **Monitoring & Logging**
- Log all security-relevant events
- Implement intrusion detection
- Set up alerting for suspicious activity
"""
def _generate_remediation_steps(self, exploit_type: ExploitType) -> List[str]:
"""Generate step-by-step remediation instructions."""
steps = {
ExploitType.WEB_SQLI: [
"1. Identify all database query locations",
"2. Replace string concatenation with parameterized queries",
"3. Implement input validation for numeric parameters",
"4. Apply least privilege to database user",
"5. Enable SQL query logging for monitoring",
"6. Test all database interactions",
],
ExploitType.WEB_XSS: [
"1. Audit all user input display locations",
"2. Implement context-aware output encoding",
"3. Deploy Content Security Policy headers",
"4. Enable X-XSS-Protection header",
"5. Remove inline JavaScript",
"6. Test with various XSS payloads",
],
ExploitType.WEB_RCE: [
"1. Identify all command execution points",
"2. Remove or sandbox eval(), exec(), system() calls",
"3. Implement strict input allowlists",
"4. Use parameterized APIs instead of shell commands",
"5. Apply AppArmor/SELinux restrictions",
"6. Disable dangerous functions in configuration",
],
}
return steps.get(
exploit_type,
[
"1. Identify the vulnerable code location",
"2. Implement proper input validation",
"3. Apply secure coding practices",
"4. Test the fix thoroughly",
"5. Deploy and monitor",
],
)
def _calculate_remediated_cvss(self, original_cvss: float, exploit_type: ExploitType) -> float:
"""Calculate CVSS score after remediation."""
# Base reduction based on fix effectiveness
reduction_map = {
ExploitType.WEB_SQLI: 5.0, # Parameterized queries very effective
ExploitType.WEB_XSS: 4.5,
ExploitType.WEB_RCE: 6.0, # RCE fixes are critical
ExploitType.WEB_CMD_INJECTION: 5.5,
ExploitType.WEB_LFI: 4.0,
}
reduction = reduction_map.get(exploit_type, 3.0)
remediated = max(0.0, original_cvss - reduction)
# Round to one decimal
return round(remediated, 1)
def _cvss_to_risk(self, cvss: float) -> str:
"""Convert CVSS score to risk level."""
if cvss >= 9.0:
return "Critical"
elif cvss >= 7.0:
return "High"
elif cvss >= 4.0:
return "Medium"
elif cvss > 0:
return "Low"
return "None"
def _estimate_remediation_effort(self, exploit_type: ExploitType) -> str:
"""Estimate effort required for remediation."""
effort_map = {
ExploitType.WEB_SQLI: "4-8 hours",
ExploitType.WEB_XSS: "2-6 hours",
ExploitType.WEB_RCE: "8-16 hours",
ExploitType.WEB_CMD_INJECTION: "4-8 hours",
ExploitType.WEB_LFI: "2-4 hours",
}
return effort_map.get(exploit_type, "4-8 hours")
async def _cleanup_temp_files(self, result: ExploitResult) -> None:
"""Auto-cleanup temporary files after execution."""
# Cleanup happens automatically with tempfile if using delete=True
# Additional cleanup for evidence files if needed
pass
def _check_exploit_rate_limit(self, target: str, exploit_type: str) -> Dict[str, Any]:
"""Check per-target exploit rate limiting."""
now = time.time()
key = f"{target}:{exploit_type}"
if key not in self._exploit_rate_limits:
self._exploit_rate_limits[key] = {
"count": 0,
"first_seen": now,
"last_exploit": now,
}
rate_info = self._exploit_rate_limits[key]
# Reset if window expired
if now - rate_info["first_seen"] > self._exploit_window:
rate_info["count"] = 0
rate_info["first_seen"] = now
# Check limit
if rate_info["count"] >= self._max_exploits_per_target:
return {
"allowed": False,
"reason": f"Max {self._max_exploits_per_target} exploits per hour exceeded",
"reset_time": rate_info["first_seen"] + self._exploit_window,
}
# Increment counter
rate_info["count"] += 1
rate_info["last_exploit"] = now
return {"allowed": True, "count": rate_info["count"]}
# Legacy methods remain for compatibility...
async def execute_sandboxed(self, command: str, timeout: int = 60, network_access: bool = False) -> Dict[str, Any]:
"""Execute a command in a sandboxed environment."""
if self.use_advanced_sandbox and self.sandbox:
result = await self.sandbox.execute(
command=command.split(),
timeout=timeout,
)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"return_code": result.exit_code,
"success": result.success,
}
elif self.sandbox_config.use_docker and self.docker_client:
return await self._execute_docker_command(command, timeout, network_access)
else:
return await self._execute_local_command(command, timeout)
async def capture_evidence(
self,
target: str,
exploit_type: ExploitType,
capture_screenshot: bool = True,
capture_http: bool = True,
capture_pcap: bool = False,
) -> Evidence:
"""Capture evidence from target interaction (legacy)."""
evidence = Evidence()
evidence.timestamps["started"] = datetime.now(timezone.utc)
# Create evidence directory
evidence_dir = os.path.join(
self.output_dir,
f"evidence_{int(time.time())}_{self._evidence_counter}",
)
self._evidence_counter += 1
os.makedirs(evidence_dir, exist_ok=True)
try:
# Capture HTTP responses
if capture_http and AIOHTTP_AVAILABLE:
http_evidence = await self._capture_http_evidence(target, evidence_dir)
evidence.http_responses = http_evidence
# Capture screenshot for web exploits
if capture_screenshot and self.enable_playwright and self._is_web_exploit(exploit_type):
screenshot_path = await self._capture_screenshot(target, evidence_dir)
if screenshot_path:
evidence.screenshots.append(screenshot_path)
# Collect metadata
evidence.metadata = {
"target": target,
"exploit_type": exploit_type.value,
"evidence_dir": evidence_dir,
"user_agent": "ZenAI-ExploitValidator/2.0",
}
evidence.timestamps["completed"] = datetime.now(timezone.utc)
evidence.compute_hashes()
except Exception as e:
logger.error(f"Evidence capture failed: {e}")
evidence.metadata["error"] = str(e)
return evidence
# ... (remaining legacy methods: generate_remediation, safe_execute, kill_switch, etc.)
# These are preserved from the original file
def generate_remediation(self, vulnerability: Dict[str, Any]) -> str:
"""Generate remediation advice for a vulnerability."""
vuln_type = vulnerability.get("type", "unknown")
severity = vulnerability.get("severity", "medium")
remediation_templates = {
ExploitType.WEB_SQLI.value: """
## SQL Injection Remediation
### Immediate Actions
1. **Use Parameterized Queries**: Replace all dynamic SQL with prepared statements
2. **Input Validation**: Validate and sanitize all user inputs
3. **Least Privilege**: Ensure database user has minimal permissions
### Code Example (Python/Flask)
```python
# VULNERABLE
cursor.execute(f"SELECT * FROM users WHERE id = '{user_id}'")
# SECURE
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
```
### Long-term Recommendations
- Implement Web Application Firewall (WAF)
- Enable SQL query logging and monitoring
- Regular security code reviews
- Use ORM frameworks that prevent SQL injection
""",
ExploitType.WEB_XSS.value: """
## Cross-Site Scripting (XSS) Remediation
### Immediate Actions
1. **Output Encoding**: Encode all output based on context (HTML, JS, URL, CSS)
2. **Content Security Policy**: Implement strict CSP headers
3. **Input Validation**: Validate input against expected patterns
### Code Example
```python
# VULNERABLE
<div>{{ user_input }}</div>
# SECURE (with Jinja2 autoescape)
<div>{{ user_input | e }}</div>
```
### Headers to Implement
```
Content-Security-Policy: default-src 'self'
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
```
""",
ExploitType.WEB_RCE.value: """
## Remote Code Execution Remediation
### Immediate Actions
1. **Disable Dangerous Functions**: Disable eval(), exec(), system() in PHP/Python
2. **Input Sanitization**: Never pass user input to system commands
3. **Sandboxing**: Run application in restricted environment
### Code Example
```python
# VULNERABLE
os.system(f"ping {user_input}")
# SECURE
allowed_hosts = ['8.8.8.8', '1.1.1.1']
if user_input in allowed_hosts:
subprocess.run(['ping', '-c', '4', user_input], check=True)
```
### Critical Recommendations
- Remove all command execution functionality if not essential
- Use allowlists for allowed commands/arguments
- Implement strong network segmentation
""",
ExploitType.WEB_LFI.value: """
## Local File Inclusion Remediation
### Immediate Actions
1. **Path Validation**: Validate and sanitize file paths
2. **Allowlist**: Use allowlist of allowed files
3. **Disable Remote Includes**: Set allow_url_include=Off in PHP
### Code Example
```php
// VULNERABLE
include($_GET['page']);
// SECURE
$allowed = ['home', 'about', 'contact'];
$page = $_GET['page'];
if (in_array($page, $allowed)) {
include("pages/" . $page . ".php");
}
```
""",
"default": f"""
## Vulnerability Remediation
**Severity**: {severity}
**Type**: {vuln_type}
### General Recommendations
1. **Update Software**: Apply latest security patches
2. **Input Validation**: Validate all user inputs
3. **Principle of Least Privilege**: Minimize permissions
4. **Security Headers**: Implement security headers
5. **Monitoring**: Enable comprehensive logging
### Verification
After applying fixes:
1. Re-run the vulnerability scan
2. Test functionality to ensure no breakage
3. Monitor for any suspicious activity
""",
}
return remediation_templates.get(vuln_type, remediation_templates["default"])
async def safe_execute(self, exploit: Dict[str, Any]) -> bool:
"""Safely execute an exploit with comprehensive checks."""
try:
if not self._validate_exploit_structure(exploit):
logger.error("Invalid exploit structure")
return False
result = await self.validate(
exploit_code=exploit["code"],
target=exploit["target"],
exploit_type=ExploitType(exploit.get("type", "web_rce")),
parameters=exploit.get("parameters", {}),
)
return result.success
except Exception as e:
logger.error(f"Safe execution failed: {e}")
return False
def kill_switch(self) -> None:
"""Activate kill switch to stop all executions."""
logger.warning("Kill switch activated!")
self._killed = True
def reset_kill_switch(self) -> None:
"""Reset kill switch."""
logger.info("Kill switch reset")
self._killed = False
# Private helper methods
def _is_safety_compatible(self, exploit_type: ExploitType) -> bool:
"""Check if exploit type is compatible with current safety level."""
safety_mapping = {
SafetyLevel.READ_ONLY: [],
SafetyLevel.VALIDATE_ONLY: [
ExploitType.WEB_XSS,
ExploitType.WEB_SQLI,
ExploitType.WEB_LFI,
ExploitType.WEB_CSRF,
],
SafetyLevel.CONTROLLED: [
ExploitType.WEB_XSS,
ExploitType.WEB_SQLI,
ExploitType.WEB_LFI,
ExploitType.WEB_RFI,
ExploitType.WEB_RCE,
ExploitType.WEB_CMD_INJECTION,
ExploitType.WEB_SSRF,
ExploitType.WEB_XXE,
ExploitType.WEB_PATH_TRAVERSAL,
ExploitType.SERVICE,
],
SafetyLevel.FULL: list(ExploitType),
}
allowed = safety_mapping.get(self.safety_level, [])
return exploit_type in allowed or self.safety_level == SafetyLevel.FULL
def _is_web_exploit(self, exploit_type: ExploitType) -> bool:
"""Check if exploit type is web-based."""
return exploit_type.value.startswith("web_")
async def _check_rate_limit(self, target: str) -> None:
"""Check and enforce rate limiting."""
now = time.time()
host = urlparse(target).hostname or target
if host in self._last_execution:
elapsed = now - self._last_execution[host]
if elapsed < self._min_interval:
wait_time = self._min_interval - elapsed
logger.debug(f"Rate limiting: waiting {wait_time:.2f}s for {host}")
await asyncio.sleep(wait_time)
self._last_execution[host] = now
def _validate_exploit_structure(self, exploit: Dict[str, Any]) -> bool:
"""Validate exploit dictionary structure."""
required_fields = ["code", "target", "type"]
return all(field in exploit for field in required_fields)
async def _execute_docker_sandboxed(
self,
exploit_code: str,
target: str,
exploit_type: ExploitType,
parameters: Dict[str, Any],
timeout: int,
) -> ExploitResult:
"""Execute exploit in Docker sandbox (legacy)."""
timestamp = datetime.now(timezone.utc)
chain_of_custody = []
# Prepare exploit script
script_content = self._generate_exploit_script(exploit_code, target, exploit_type, parameters)
# Create temporary directory for volumes
with tempfile.TemporaryDirectory() as tmpdir:
script_path = os.path.join(tmpdir, "exploit.py")
with open(script_path, "w") as f:
f.write(script_content)
# Output directory for results
output_dir = os.path.join(tmpdir, "output")
os.makedirs(output_dir, exist_ok=True)
try:
# Build container configuration
container_config = {
"image": self.sandbox_config.image,
"command": ["python3", "/exploit/exploit.py"],
"volumes": {
tmpdir: {"bind": "/exploit", "mode": "ro"},
output_dir: {"bind": "/output", "mode": "rw"},
},
"network_disabled": self.sandbox_config.network_isolated,
"mem_limit": self.sandbox_config.memory_limit,
"cpu_quota": int(self.sandbox_config.cpu_limit * 100000),
"read_only": self.sandbox_config.read_only_root,
"cap_drop": self.sandbox_config.cap_drop,
"cap_add": self.sandbox_config.cap_add,
"dns": self.sandbox_config.dns_servers,
"detach": True,
"auto_remove": True,
}
# Run container
chain_of_custody.append(
{
"action": "container_created",
"timestamp": datetime.now(timezone.utc).isoformat(),
"image": self.sandbox_config.image,
}
)
container = self.docker_client.containers.run(**container_config)
# Wait for completion with timeout
try:
result = container.wait(timeout=timeout)
logs = container.logs().decode("utf-8", errors="ignore")
# Read output files
output_data = {}
for filename in os.listdir(output_dir):
filepath = os.path.join(output_dir, filename)
try:
with open(filepath, "r") as f:
output_data[filename] = f.read()
except Exception:
output_data[filename] = "[binary]"
# Parse results
success = result.get("StatusCode", 1) == 0
# Capture evidence
evidence = await self.capture_evidence(
target,
exploit_type,
capture_screenshot=self._is_web_exploit(exploit_type),
)
chain_of_custody.append(
{
"action": "execution_completed",
"timestamp": datetime.now(timezone.utc).isoformat(),
"exit_code": result.get("StatusCode", -1),
}
)
return ExploitResult(
success=success,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=evidence,
output=logs + "\n" + json.dumps(output_data, indent=2),
status=(ExploitStatus.SUCCESS if success else ExploitStatus.FAILED),
chain_of_custody=chain_of_custody,
)
except Exception:
container.kill()
raise
except ContainerError as e:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output=str(e),
status=ExploitStatus.ERROR,
error=f"Container error: {str(e)}",
chain_of_custody=chain_of_custody,
)
except ImageNotFound:
return ExploitResult(
success=False,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=Evidence(),
output="",
status=ExploitStatus.ERROR,
error=f"Docker image '{self.sandbox_config.image}' not found",
chain_of_custody=chain_of_custody,
)
async def _execute_local_sandboxed(
self,
exploit_code: str,
target: str,
exploit_type: ExploitType,
parameters: Dict[str, Any],
timeout: int,
) -> ExploitResult:
"""Execute exploit locally with restrictions (fallback)."""
timestamp = datetime.now(timezone.utc)
chain_of_custody = []
# Generate and execute exploit script
script_content = self._generate_exploit_script(exploit_code, target, exploit_type, parameters)
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
f.write(script_content)
script_path = f.name
try:
chain_of_custody.append(
{
"action": "local_execution_started",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
)
# Execute with timeout
process = await asyncio.create_subprocess_exec(
"python3",
script_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
output = stdout.decode("utf-8", errors="ignore")
error = stderr.decode("utf-8", errors="ignore")
success = process.returncode == 0 and not error
# Capture evidence
evidence = await self.capture_evidence(
target,
exploit_type,
capture_screenshot=self._is_web_exploit(exploit_type),
)
chain_of_custody.append(
{
"action": "execution_completed",
"timestamp": datetime.now(timezone.utc).isoformat(),
"exit_code": process.returncode,
}
)
return ExploitResult(
success=success,
exploit_type=exploit_type,
target=target,
timestamp=timestamp,
evidence=evidence,
output=output,
status=(ExploitStatus.SUCCESS if success else ExploitStatus.FAILED),
error=error if error else None,
chain_of_custody=chain_of_custody,
)
except asyncio.TimeoutError:
process.kill()
raise
finally:
os.unlink(script_path)
async def _execute_docker_command(self, command: str, timeout: int, network_access: bool) -> Dict[str, Any]:
"""Execute a command in Docker container."""
try:
container = self.docker_client.containers.run(
image=self.sandbox_config.image,
command=["sh", "-c", command],
network_disabled=not network_access,
mem_limit=self.sandbox_config.memory_limit,
detach=True,
auto_remove=True,
)
result = container.wait(timeout=timeout)
logs = container.logs().decode("utf-8", errors="ignore")
return {
"stdout": logs,
"stderr": "",
"return_code": result.get("StatusCode", -1),
"success": result.get("StatusCode", 1) == 0,
}
except Exception as e:
return {
"stdout": "",
"stderr": str(e),
"return_code": -1,
"success": False,
}
async def _execute_local_command(self, command: str, timeout: int) -> Dict[str, Any]:
"""Execute command locally."""
try:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
return {
"stdout": stdout.decode("utf-8", errors="ignore"),
"stderr": stderr.decode("utf-8", errors="ignore"),
"return_code": process.returncode,
"success": process.returncode == 0,
}
except asyncio.TimeoutError:
process.kill()
return {
"stdout": "",
"stderr": "Timeout",
"return_code": -1,
"success": False,
}
async def _capture_http_evidence(self, target: str, evidence_dir: str) -> List[Dict[str, Any]]:
"""Capture HTTP response evidence."""
responses = []
if not AIOHTTP_AVAILABLE:
return responses
try:
# Ensure URL has scheme
if not target.startswith(("http://", "https://")):
target = f"http://{target}"
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(target, ssl=False) as response:
body_text = await response.text()
response_data = {
"url": str(response.url),
"status": response.status,
"headers": dict(response.headers),
"timestamp": datetime.now(timezone.utc).isoformat(),
"body": body_text[:10000], # Limit body size
}
responses.append(response_data)
# Save to file
http_file = os.path.join(evidence_dir, "http_response.json")
with open(http_file, "w") as f:
json.dump(response_data, f, indent=2, default=str)
except Exception as e:
logger.warning(f"HTTP capture failed: {e}")
return responses
async def _capture_screenshot(self, target: str, evidence_dir: str) -> Optional[str]:
"""Capture browser screenshot using Playwright."""
if not PLAYWRIGHT_AVAILABLE or not self.enable_playwright:
return None
screenshot_path = None
try:
# Ensure URL has scheme
if not target.startswith(("http://", "https://")):
target = f"http://{target}"
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
context = await browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent="ZenAI-ExploitValidator/2.0",
)
page = await context.new_page()
try:
await page.goto(target, wait_until="networkidle", timeout=30000)
# Capture screenshot
screenshot_path = os.path.join(evidence_dir, "screenshot.png")
await page.screenshot(path=screenshot_path, full_page=True)
# Also capture page content
content = await page.content()
html_path = os.path.join(evidence_dir, "page.html")
with open(html_path, "w", encoding="utf-8") as f:
f.write(content)
except Exception as e:
logger.warning(f"Page navigation failed: {e}")
await browser.close()
except Exception as e:
logger.warning(f"Screenshot capture failed: {e}")
return screenshot_path
def _generate_exploit_script(
self,
exploit_code: str,
target: str,
exploit_type: ExploitType,
parameters: Dict[str, Any],
) -> str:
"""Generate a safe exploit execution script."""
# Sanitize inputs
safe_target = shlex.quote(target)
script = f'''#!/usr/bin/env python3
"""
Auto-generated exploit validation script
Generated: {datetime.now(timezone.utc).isoformat()}
Exploit Type: {exploit_type.value}
Target: {target}
"""
import json
import sys
import os
def main():
target = {safe_target}
parameters = {json.dumps(parameters)}
# Output directory
output_dir = "/output" if os.path.exists("/output") else "."
result = {{
"success": False,
"target": target,
"output": "",
"error": None
}}
try:
# User exploit code
{self._indent_code(exploit_code, 8)}
result["success"] = True
result["output"] = "Exploit executed successfully"
except Exception as e:
result["error"] = str(e)
result["output"] = f"Exploit failed: {{e}}"
# Write results
with open(os.path.join(output_dir, "result.json"), "w") as f:
json.dump(result, f, indent=2)
print(json.dumps(result))
return 0 if result["success"] else 1
if __name__ == "__main__":
sys.exit(main())
'''
return script
def _indent_code(self, code: str, indent: int) -> str:
"""Indent code block for script generation."""
lines = code.split("\n")
spaces = " " * indent
return "\n".join(spaces + line for line in lines)
class ExploitValidatorPool:
"""
Pool of ExploitValidators for concurrent execution.
Manages multiple validators with load balancing and
resource management.
"""
def __init__(
self,
pool_size: int = 3,
safety_level: SafetyLevel = SafetyLevel.CONTROLLED,
scope_config: Optional[ScopeConfig] = None,
use_advanced_sandbox: bool = True,
):
"""
Initialize validator pool.
Args:
pool_size: Number of validators in pool
safety_level: Safety level for all validators
scope_config: Scope configuration
use_advanced_sandbox: Use new sandbox implementation
"""
self.pool_size = pool_size
self.safety_level = safety_level
self.scope_config = scope_config or ScopeConfig()
self.use_advanced_sandbox = use_advanced_sandbox
self._validators: List[ExploitValidator] = []
self._queue: asyncio.Queue = asyncio.Queue()
self._semaphore = asyncio.Semaphore(pool_size)
# Statistics
self._stats = {
"total_executed": 0,
"successful": 0,
"failed": 0,
"blocked": 0,
"remediated": 0,
}
async def initialize(self) -> None:
"""Initialize all validators in the pool."""
for i in range(self.pool_size):
validator = ExploitValidator(
safety_level=self.safety_level,
scope_config=self.scope_config,
use_advanced_sandbox=self.use_advanced_sandbox,
)
await validator.initialize()
self._validators.append(validator)
logger.info(f"Validator pool initialized with {self.pool_size} validators")
async def submit(
self,
exploit_code: str,
target: str,
exploit_type: ExploitType,
parameters: Optional[Dict[str, Any]] = None,
auto_remediate: bool = False,
) -> ExploitResult:
"""
Submit an exploit for validation.
Args:
exploit_code: Exploit code to execute
target: Target for exploitation
exploit_type: Type of exploit
parameters: Additional parameters
auto_remediate: Generate remediation
Returns:
ExploitResult from validation
"""
async with self._semaphore:
# Round-robin selection
validator = self._validators[self._stats["total_executed"] % len(self._validators)]
self._stats["total_executed"] += 1
result = await validator.validate(
exploit_code=exploit_code,
target=target,
exploit_type=exploit_type,
parameters=parameters,
auto_remediate=auto_remediate,
)
# Update statistics
if result.success:
self._stats["successful"] += 1
elif result.status == ExploitStatus.BLOCKED:
self._stats["blocked"] += 1
else:
self._stats["failed"] += 1
if result.remediation_result:
self._stats["remediated"] += 1
return result
async def submit_batch(self, exploits: List[Dict[str, Any]], auto_remediate: bool = False) -> List[ExploitResult]:
"""
Submit multiple exploits for validation.
Args:
exploits: List of exploit dictionaries
auto_remediate: Generate remediation for all
Returns:
List of ExploitResults
"""
tasks = []
for exploit in exploits:
task = self.submit(
exploit_code=exploit["code"],
target=exploit["target"],
exploit_type=ExploitType(exploit.get("type", "web_rce")),
parameters=exploit.get("parameters", {}),
auto_remediate=auto_remediate,
)
tasks.append(task)
return await asyncio.gather(*tasks, return_exceptions=True)
def get_stats(self) -> Dict[str, int]:
"""Get pool statistics."""
return self._stats.copy()
def kill_all(self) -> None:
"""Activate kill switch on all validators."""
for validator in self._validators:
validator.kill_switch()
# Convenience functions for common use cases
async def validate_exploit(
cve_id: str,
target: str,
exploit_code: str,
timeout: int = 30,
sandbox: bool = True,
auto_remediate: bool = True,
) -> ExploitResult:
"""
Convenience function for quick exploit validation.
Args:
cve_id: CVE identifier (e.g., "CVE-2024-1234")
target: Target URL
exploit_code: Exploit code/payload
timeout: Execution timeout (max 60s)
sandbox: Use sandboxed execution
auto_remediate: Generate remediation
Returns:
ExploitResult with:
- exploited: bool
- evidence: {screenshots, video, response, timeline}
- remediation: str (code)
- cvss_after_fix: float
- verification_result: bool
"""
validator = ExploitValidator(
use_advanced_sandbox=sandbox,
safety_level=SafetyLevel.CONTROLLED,
)
await validator.initialize()
# Determine exploit type from CVE or code
exploit_type = _detect_exploit_type(cve_id, exploit_code)
try:
result = await validator.validate(
cve_id=cve_id,
target=target,
exploit_code=exploit_code,
exploit_type=exploit_type,
timeout=timeout,
capture_video=False,
auto_remediate=auto_remediate,
)
return result
finally:
if validator.sandbox:
await validator.sandbox.cleanup_all()
def _detect_exploit_type(cve_id: str, exploit_code: str) -> ExploitType:
"""Detect exploit type from CVE ID and code."""
code_lower = exploit_code.lower()
if "sql" in code_lower or "select" in code_lower or "'" in code_lower:
return ExploitType.WEB_SQLI
elif "<script" in code_lower or "alert(" in code_lower or "xss" in code_lower:
return ExploitType.WEB_XSS
elif "system(" in code_lower or "exec(" in code_lower or "eval(" in code_lower:
return ExploitType.WEB_RCE
elif "include" in code_lower or "file_get_contents" in code_lower:
return ExploitType.WEB_LFI
elif "|" in code_lower or ";" in code_lower:
return ExploitType.WEB_CMD_INJECTION
return ExploitType.WEB_RCE # Default
async def validate_sql_injection(target: str, parameter: str, payload: str, method: str = "GET", **kwargs) -> ExploitResult:
"""Validate SQL injection vulnerability."""
exploit_code = f"""
import requests
url = "{target}"
params = {{"{parameter}": "{payload}"}}
response = requests.{method.lower()}(url, params=params, timeout=30)
# Check for SQL error indicators
sql_errors = [
"sql syntax", "mysql_fetch", "pg_query", "ora-",
"sqlserver", "jdbc", "odbc", "syntax error"
]
found_error = any(err in response.text.lower() for err in sql_errors)
print(f"Response status: {{response.status_code}}")
print(f"SQL error detected: {{found_error}}")
print(f"Response length: {{len(response.text)}}")
"""
validator = ExploitValidator(**kwargs)
return await validator.validate(
exploit_code=exploit_code,
target=target,
exploit_type=ExploitType.WEB_SQLI,
)
async def validate_xss(
target: str,
parameter: str,
payload: str = "<script>alert(1)</script>",
**kwargs,
) -> ExploitResult:
"""Validate XSS vulnerability."""
exploit_code = f"""
import requests
url = "{target}"
payload = "{payload}"
response = requests.get(url, params={{"{parameter}": payload}}, timeout=30)
# Check if payload is reflected
is_reflected = payload in response.text
print(f"Payload reflected: {{is_reflected}}")
print(f"Response status: {{response.status_code}}")
if is_reflected:
print("XSS vulnerability confirmed - payload reflected")
else:
print("Payload not reflected in response")
"""
validator = ExploitValidator(**kwargs)
return await validator.validate(
exploit_code=exploit_code,
target=target,
exploit_type=ExploitType.WEB_XSS,
)
async def validate_command_injection(target: str, parameter: str, command: str = "echo ZENAI_TEST", **kwargs) -> ExploitResult:
"""Validate command injection vulnerability."""
exploit_code = f"""
import requests
import time
url = "{target}"
# Test command injection with timing
payload = "; {command}; #"
start = time.time()
response = requests.get(url, params={{"{parameter}": payload}}, timeout=60)
elapsed = time.time() - start
print(f"Response time: {{elapsed:.2f}}s")
print(f"Response status: {{response.status_code}}")
# Check for command output
if "ZENAI_TEST" in response.text:
print("Command injection confirmed - output reflected")
elif elapsed > 4:
print("Possible blind command injection - timing detected")
else:
print("Command injection not confirmed")
"""
validator = ExploitValidator(**kwargs)
return await validator.validate(
exploit_code=exploit_code,
target=target,
exploit_type=ExploitType.WEB_CMD_INJECTION,
)
# Export public API
__all__ = [
"ExploitValidator",
"ExploitValidatorPool",
"ExploitResult",
"ExploitType",
"ExploitStatus",
"SafetyLevel",
"Evidence",
"ScopeConfig",
"LegacySandboxConfig",
"RemediationResult",
"validate_exploit",
"validate_sql_injection",
"validate_xss",
"validate_command_injection",
]
#!/usr/bin/env python3
"""
Exploit Validator System for Zen AI Pentest Framework
Automatisierte Validierung und Beweisführung von Exploits in isolierten Umgebungen.
Features:
- Docker-Container-basierte Sandboxed-Ausführung (DinD + gVisor)
- Proof-of-Exploit Generierung (Screenshots, Video, HTTP-Capture)
- Evidence Collection mit Chain-of-Custody
- Remediation-Vorschläge mit automatischer Fix-Generierung
- CVSS Score Update nach Fix
- Verification-Scan nach Patch
- Unterstützung für verschiedene Exploit-Typen
- Safety Features (Read-Only, Scope-Validierung, Kill-Switch)
FOR AUTHORIZED SECURITY TESTING ONLY
⚠️ LEGAL WARNING: Only scan systems you own or have EXPLICIT WRITTEN
permission to test. Unauthorized scanning is ILLEGAL and can result in:
- Criminal prosecution
- Civil liability
- Fines and imprisonment
You are SOLELY RESPONSIBLE for your actions.
Author: SHAdd0WTAka
Version: 2.0.0
"""
import asyncio
import hashlib
import json
import logging
import os
import shlex
import shutil
import tempfile
import time
import uuid
import warnings
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from enum import Enum, auto
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
# Optional imports - handle gracefully if not available
try:
import docker
from docker.errors import ContainerError, DockerException, ImageNotFound # noqa: F401
DOCKER_AVAILABLE = True
except ImportError:
DOCKER_AVAILABLE = False
warnings.warn("Docker SDK not available. Container isolation disabled.")
try:
import aiohttp
AIOHTTP_AVAILABLE = True
except ImportError:
AIOHTTP_AVAILABLE = False
try:
from playwright.async_api import async_playwright
PLAYWRIGHT_AVAILABLE = True
except ImportError:
PLAYWRIGHT_AVAILABLE = False
warnings.warn("Playwright not available. Screenshot capture disabled.")
# Import our new modules
try:
from guardrails.sandbox import (
DockerSandbox,
ResourceLimits,
)
from guardrails.sandbox import SandboxConfig as _GuardrailsSandboxConfig
from guardrails.sandbox import (
SandboxResult,
SandboxRuntime,
SecurityProfile,
)
SANDBOX_AVAILABLE = True
except ImportError:
SANDBOX_AVAILABLE = False
warnings.warn("Sandbox module not available. Using legacy mode.")
try:
from autonomous.evidence_collector import (
EvidenceCollector,
ExploitEvidence,
)
EVIDENCE_AVAILABLE = True
except ImportError:
EVIDENCE_AVAILABLE = False
warnings.warn("Evidence collector not available.")
Xet Storage Details
- Size:
- 79.6 kB
- Xet hash:
- 731fb25edfd067be709a0b121743964eebec25e47994e50f9b2a9d8362d22eb9
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.