Buckets:

download
raw
28.9 kB
#!/usr/bin/env python3
"""
Sandboxed Execution Environment for Zen AI Pentest Framework
Bietet sichere, isolierte Ausführung von Exploits mittels:
- Docker-in-Docker Isolation
- gVisor als optionale zusätzliche Sicherheitsschicht
- Ressourcenlimits (CPU, Memory, Network)
- Read-only Filesystem
FOR AUTHORIZED SECURITY TESTING ONLY
Author: SHAdd0WTAka
Version: 2.0.0
"""
import asyncio
import json
import logging
import os
import shutil
import tempfile
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, List, Optional
# Docker SDK # noqa: I001
try:
import docker
from docker.errors import DockerException # noqa: F401
from docker.types import Mount # noqa: F401
DOCKER_AVAILABLE = True
except ImportError:
DOCKER_AVAILABLE = False
# Async subprocess for local fallback
logger = logging.getLogger("ZenAI.Sandbox")
class SandboxRuntime(Enum):
"""Available sandbox runtimes."""
DOCKER = "docker"
DOCKER_DIND = "docker_dind" # Docker-in-Docker
GVISOR = "gvisor" # gVisor runsc
GVISOR_DIND = "gvisor_dind" # gVisor + DinD
NATIVE = "native" # Fallback (unsicher)
class SandboxStatus(Enum):
"""Status der Sandbox-Ausführung."""
PENDING = "pending"
CREATING = "creating"
RUNNING = "running"
SUCCESS = "success"
FAILED = "failed"
TIMEOUT = "timeout"
BLOCKED = "blocked"
CLEANING = "cleaning"
CLEANED = "cleaned"
@dataclass
class ResourceLimits:
"""Resource limits for sandboxed execution."""
cpu_limit: float = 1.0 # CPU cores
memory_limit: str = "512m" # Memory (m/g)
memory_swap: str = "512m" # Swap limit
pids_limit: int = 50 # Max processes
tmpfs_size: str = "100m" # tmpfs Größe
storage_limit: str = "1g" # Storage limit
network_bandwidth: Optional[str] = None # z.B. "10mbit"
@dataclass
class SecurityProfile:
"""Security profile for sandbox configuration."""
read_only_root: bool = True
no_new_privileges: bool = True
drop_all_capabilities: bool = True
allowed_capabilities: List[str] = field(default_factory=list)
seccomp_profile: Optional[str] = None # Path to seccomp profile
apparmor_profile: Optional[str] = None # AppArmor profile name
disable_network: bool = False
dns_servers: List[str] = field(default_factory=lambda: ["8.8.8.8", "1.1.1.1"])
@dataclass
class SandboxResult:
"""Result of sandboxed execution."""
success: bool
status: SandboxStatus
exit_code: int
stdout: str
stderr: str
execution_time: float
container_id: Optional[str] = None
logs: List[str] = field(default_factory=list)
artifacts: Dict[str, str] = field(default_factory=dict)
resource_usage: Dict[str, Any] = field(default_factory=dict)
security_violations: List[str] = field(default_factory=list)
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
sandbox_id: str = field(default_factory=lambda: str(uuid.uuid4()))
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"success": self.success,
"status": self.status.value,
"exit_code": self.exit_code,
"stdout": self.stdout,
"stderr": self.stderr,
"execution_time": self.execution_time,
"container_id": self.container_id,
"logs": self.logs,
"artifacts": self.artifacts,
"resource_usage": self.resource_usage,
"security_violations": self.security_violations,
"timestamp": self.timestamp.isoformat(),
"sandbox_id": self.sandbox_id,
}
@dataclass
class SandboxConfig:
"""Configuration for sandboxed execution."""
runtime: SandboxRuntime = SandboxRuntime.DOCKER
image: str = "zenai/exploit-sandbox:latest"
dind_image: str = "docker:24-dind"
gvisor_runtime: str = "runsc" # gVisor runtime name
timeout: int = 60
auto_cleanup: bool = True
keep_artifacts: bool = False
resource_limits: ResourceLimits = field(default_factory=ResourceLimits)
security_profile: SecurityProfile = field(default_factory=SecurityProfile)
environment: Dict[str, str] = field(default_factory=dict)
volumes: Dict[str, str] = field(default_factory=dict)
class DockerSandbox:
"""
Docker-basierte Sandbox mit DinD und gVisor Unterstützung.
Features:
- Docker-in-Docker für maximale Isolation
- gVisor als optionale Sicherheitsschicht
- Ressourcenlimits und Read-only Filesystem
- Automatische Cleanup
"""
# Docker-in-Docker Compose für isolierte Umgebung
DIND_COMPOSE_TEMPLATE = """
version: '3.8'
services:
dind:
image: {dind_image}
privileged: true
environment:
- DOCKER_TLS_CERTDIR=/certs
volumes:
- {certs_dir}:/certs/client
- {work_dir}:/work
networks:
- sandbox_net
cpu_count: {cpu_limit}
mem_limit: {memory_limit}
pids_limit: {pids_limit}
read_only: {read_only}
security_opt:
- no-new-privileges:true
{cap_drop}
exploit:
image: {image}
depends_on:
- dind
environment:
- DOCKER_HOST=tcp://dind:2376
- DOCKER_CERT_PATH=/certs/client
- DOCKER_TLS_VERIFY=1
volumes:
- {certs_dir}:/certs/client:ro
- {work_dir}:/work
working_dir: /work
command: {command}
networks:
- sandbox_net
cpu_count: {cpu_limit}
mem_limit: {memory_limit}
pids_limit: {pids_limit}
read_only: {read_only}
tmpfs:
- /tmp:noexec,nosuid,size={tmpfs_size}
security_opt:
- no-new-privileges:true
{cap_drop}
{dns_config}
networks:
sandbox_net:
internal: {internal_network}
"""
def __init__(self, config: Optional[SandboxConfig] = None):
"""
Initialize Docker Sandbox.
Args:
config: Sandbox configuration
"""
self.config = config or SandboxConfig()
self.docker_client = None
self._gvisor_available = False
self._active_containers: List[str] = []
self._cleanup_queue: asyncio.Queue = asyncio.Queue()
# Initialize Docker client
if DOCKER_AVAILABLE:
try:
self.docker_client = docker.from_env()
self.docker_client.ping()
logger.info("Docker client initialized successfully")
# Check gVisor availability
self._check_gvisor()
except DockerException as e:
logger.warning(f"Docker not available: {e}")
# Start cleanup worker
self._cleanup_task = None
def _check_gvisor(self) -> bool:
"""Check if gVisor runtime is available."""
try:
runtimes = self.docker_client.info().get("Runtimes", {})
self._gvisor_available = "runsc" in runtimes
if self._gvisor_available:
logger.info("gVisor runtime available")
return self._gvisor_available
except Exception as e:
logger.debug(f"gVisor check failed: {e}")
return False
async def initialize(self) -> None:
"""Initialize sandbox environment."""
self._cleanup_task = asyncio.create_task(self._cleanup_worker())
# Pull required images
if self.docker_client:
try:
logger.info(f"Pulling sandbox image: {self.config.image}")
self.docker_client.images.pull(self.config.image)
if self.config.runtime in (SandboxRuntime.DOCKER_DIND, SandboxRuntime.GVISOR_DIND):
logger.info(f"Pulling DinD image: {self.config.dind_image}")
self.docker_client.images.pull(self.config.dind_image)
except Exception as e:
logger.warning(f"Failed to pull images: {e}")
async def execute(
self,
command: List[str],
work_dir: Optional[str] = None,
environment: Optional[Dict[str, str]] = None,
timeout: Optional[int] = None,
) -> SandboxResult:
"""
Execute command in sandbox.
Args:
command: Command and arguments
work_dir: Working directory to mount
environment: Additional environment variables
timeout: Execution timeout override
Returns:
SandboxResult with execution details
"""
if not self.docker_client:
return await self._fallback_local_execute(command, timeout)
runtime = self.config.runtime
if runtime == SandboxRuntime.DOCKER:
return await self._execute_docker(command, work_dir, environment, timeout)
elif runtime == SandboxRuntime.DOCKER_DIND:
return await self._execute_dind(command, work_dir, environment, timeout)
elif runtime == SandboxRuntime.GVISOR and self._gvisor_available:
return await self._execute_gvisor(command, work_dir, environment, timeout)
elif runtime == SandboxRuntime.GVISOR_DIND and self._gvisor_available:
return await self._execute_gvisor_dind(command, work_dir, environment, timeout)
else:
logger.warning(f"Runtime {runtime.value} not available, falling back to Docker")
return await self._execute_docker(command, work_dir, environment, timeout)
async def _execute_docker(
self,
command: List[str],
work_dir: Optional[str],
environment: Optional[Dict[str, str]],
timeout: Optional[int],
) -> SandboxResult:
"""Execute in standard Docker container."""
start_time = time.time()
sandbox_id = str(uuid.uuid4())[:8]
container_name = f"zenai-sandbox-{sandbox_id}"
# Prepare volumes
volumes = {}
if work_dir:
volumes[work_dir] = {"bind": "/work", "mode": "rw"}
# Add custom volumes
for host, container in self.config.volumes.items():
volumes[host] = {"bind": container, "mode": "ro"}
# Environment
env = {**self.config.environment, **(environment or {})}
# Resource limits
limits = self.config.resource_limits
security = self.config.security_profile
try:
# Create and run container
container = self.docker_client.containers.run(
image=self.config.image,
command=command,
name=container_name,
volumes=volumes,
environment=env,
working_dir="/work" if work_dir else None,
network_disabled=security.disable_network,
mem_limit=limits.memory_limit,
memswap_limit=limits.memory_swap,
cpu_period=100000,
cpu_quota=int(limits.cpu_limit * 100000),
pids_limit=limits.pids_limit,
read_only=security.read_only_root,
security_opt=["no-new-privileges:true"] if security.no_new_privileges else [],
cap_drop=["ALL"] if security.drop_all_capabilities else [],
cap_add=security.allowed_capabilities,
dns=security.dns_servers if security.dns_servers else None,
detach=True,
auto_remove=False, # We handle cleanup manually
stdin_open=False,
tty=False,
)
self._active_containers.append(container.id)
# Wait for completion with timeout
exec_timeout = timeout or self.config.timeout
try:
result = container.wait(timeout=exec_timeout)
logs = container.logs().decode("utf-8", errors="ignore")
# Get resource usage stats
stats = container.stats(stream=False)
resource_usage = self._parse_resource_stats(stats)
exit_code = result.get("StatusCode", -1)
success = exit_code == 0
return SandboxResult(
success=success,
status=SandboxStatus.SUCCESS if success else SandboxStatus.FAILED,
exit_code=exit_code,
stdout=logs,
stderr="",
execution_time=time.time() - start_time,
container_id=container.id,
resource_usage=resource_usage,
)
except Exception as e:
# Timeout or error - kill container
try:
container.kill()
except Exception:
pass
return SandboxResult(
success=False,
status=SandboxStatus.TIMEOUT,
exit_code=-1,
stdout="",
stderr=str(e),
execution_time=time.time() - start_time,
container_id=container.id,
)
except Exception as e:
logger.error(f"Docker execution failed: {e}")
return SandboxResult(
success=False,
status=SandboxStatus.FAILED,
exit_code=-1,
stdout="",
stderr=str(e),
execution_time=time.time() - start_time,
)
finally:
# Schedule cleanup
if self.config.auto_cleanup and "container" in locals():
await self._cleanup_queue.put(container.id)
async def _execute_dind(
self,
command: List[str],
work_dir: Optional[str],
environment: Optional[Dict[str, str]],
timeout: Optional[int],
) -> SandboxResult:
"""Execute in Docker-in-Docker environment."""
start_time = time.time()
sandbox_id = str(uuid.uuid4())[:8]
# Create temporary directories
certs_dir = tempfile.mkdtemp(prefix=f"zenai-certs-{sandbox_id}-")
work_dir = work_dir or tempfile.mkdtemp(prefix=f"zenai-work-{sandbox_id}-")
try:
# Generate compose file
compose_content = self._generate_dind_compose(
command=command,
certs_dir=certs_dir,
work_dir=work_dir,
)
compose_file = os.path.join(certs_dir, "docker-compose.yml")
with open(compose_file, "w") as f:
f.write(compose_content)
# Run docker-compose
compose_cmd = [
"docker-compose",
"-f",
compose_file,
"-p",
f"zenai-sandbox-{sandbox_id}",
"up",
"--abort-on-container-exit",
"--timeout",
"30",
]
proc = await asyncio.create_subprocess_exec(
*compose_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
exec_timeout = timeout or self.config.timeout
try:
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=exec_timeout + 30) # Extra for cleanup
# Get logs from exploit container
logs_cmd = ["docker-compose", "-f", compose_file, "-p", f"zenai-sandbox-{sandbox_id}", "logs", "exploit"]
logs_proc = await asyncio.create_subprocess_exec(
*logs_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
logs_stdout, _ = await logs_proc.communicate()
success = proc.returncode == 0
return SandboxResult(
success=success,
status=SandboxStatus.SUCCESS if success else SandboxStatus.FAILED,
exit_code=proc.returncode,
stdout=logs_stdout.decode("utf-8", errors="ignore"),
stderr=stderr.decode("utf-8", errors="ignore"),
execution_time=time.time() - start_time,
)
except asyncio.TimeoutError:
# Cleanup
await self._cleanup_dind(compose_file, sandbox_id)
return SandboxResult(
success=False,
status=SandboxStatus.TIMEOUT,
exit_code=-1,
stdout="",
stderr="Execution timeout in DinD sandbox",
execution_time=time.time() - start_time,
)
finally:
# Cleanup
if self.config.auto_cleanup:
await self._cleanup_dind(compose_file, sandbox_id)
shutil.rmtree(certs_dir, ignore_errors=True)
async def _execute_gvisor(
self,
command: List[str],
work_dir: Optional[str],
environment: Optional[Dict[str, str]],
timeout: Optional[int],
) -> SandboxResult:
"""Execute with gVisor runtime."""
start_time = time.time()
sandbox_id = str(uuid.uuid4())[:8]
container_name = f"zenai-sandbox-gvisor-{sandbox_id}"
volumes = {}
if work_dir:
volumes[work_dir] = {"bind": "/work", "mode": "rw"}
env = {**self.config.environment, **(environment or {})}
limits = self.config.resource_limits
security = self.config.security_profile
try:
container = self.docker_client.containers.run(
image=self.config.image,
command=command,
name=container_name,
volumes=volumes,
environment=env,
working_dir="/work" if work_dir else None,
runtime=self.config.gvisor_runtime,
network_disabled=security.disable_network,
mem_limit=limits.memory_limit,
cpu_quota=int(limits.cpu_limit * 100000),
pids_limit=limits.pids_limit,
read_only=security.read_only_root,
detach=True,
auto_remove=False,
)
self._active_containers.append(container.id)
exec_timeout = timeout or self.config.timeout
try:
result = container.wait(timeout=exec_timeout)
logs = container.logs().decode("utf-8", errors="ignore")
exit_code = result.get("StatusCode", -1)
success = exit_code == 0
return SandboxResult(
success=success,
status=SandboxStatus.SUCCESS if success else SandboxStatus.FAILED,
exit_code=exit_code,
stdout=logs,
stderr="",
execution_time=time.time() - start_time,
container_id=container.id,
)
except Exception as e:
try:
container.kill()
except Exception:
pass
return SandboxResult(
success=False,
status=SandboxStatus.TIMEOUT,
exit_code=-1,
stdout="",
stderr=str(e),
execution_time=time.time() - start_time,
container_id=container.id,
)
except Exception as e:
logger.error(f"gVisor execution failed: {e}")
return SandboxResult(
success=False,
status=SandboxStatus.FAILED,
exit_code=-1,
stdout="",
stderr=str(e),
execution_time=time.time() - start_time,
)
finally:
if self.config.auto_cleanup and "container" in locals():
await self._cleanup_queue.put(container.id)
async def _execute_gvisor_dind(
self,
command: List[str],
work_dir: Optional[str],
environment: Optional[Dict[str, str]],
timeout: Optional[int],
) -> SandboxResult:
"""Execute with gVisor + Docker-in-Docker (maximale Isolation)."""
# Kombiniere gVisor mit DinD für maximale Sicherheit
# Dies erfordert einen gVisor-fähigen DinD Container
logger.info("Using gVisor + DinD (maximal isolation)")
# Führe DinD mit gVisor Runtime aus
original_runtime = self.config.runtime
self.config.runtime = SandboxRuntime.DOCKER_DIND
# Setze gVisor als Runtime für die innere Docker-Instanz
env = {**self.config.environment, **(environment or {})}
env["DOCKER_RUNTIME"] = self.config.gvisor_runtime
result = await self._execute_dind(command, work_dir, env, timeout)
self.config.runtime = original_runtime
return result
async def _fallback_local_execute(self, command: List[str], timeout: Optional[int]) -> SandboxResult:
"""Fallback execution without Docker (unsicher!)."""
logger.warning("Executing without Docker sandbox - SECURITY RISK!")
start_time = time.time()
try:
proc = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
exec_timeout = timeout or self.config.timeout
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=exec_timeout)
success = proc.returncode == 0
return SandboxResult(
success=success,
status=SandboxStatus.SUCCESS if success else SandboxStatus.FAILED,
exit_code=proc.returncode,
stdout=stdout.decode("utf-8", errors="ignore"),
stderr=stderr.decode("utf-8", errors="ignore"),
execution_time=time.time() - start_time,
security_violations=["NO_SANDBOX_EXECUTION"],
)
except asyncio.TimeoutError:
proc.kill()
return SandboxResult(
success=False,
status=SandboxStatus.TIMEOUT,
exit_code=-1,
stdout="",
stderr="Execution timeout",
execution_time=time.time() - start_time,
security_violations=["NO_SANDBOX_EXECUTION"],
)
def _generate_dind_compose(self, command: List[str], certs_dir: str, work_dir: str) -> str:
"""Generate Docker Compose file for DinD execution."""
limits = self.config.resource_limits
security = self.config.security_profile
# Format command
cmd_str = json.dumps(command)
# Format capabilities
cap_drop = "cap_drop:\n - ALL" if security.drop_all_capabilities else ""
if security.allowed_capabilities:
cap_drop += "\n cap_add:\n - " + "\n - ".join(security.allowed_capabilities)
# Format DNS
dns_config = ""
if security.dns_servers:
dns_config = "dns:\n - " + "\n - ".join(security.dns_servers)
return self.DIND_COMPOSE_TEMPLATE.format(
dind_image=self.config.dind_image,
image=self.config.image,
certs_dir=certs_dir,
work_dir=work_dir,
cpu_limit=limits.cpu_limit,
memory_limit=limits.memory_limit,
pids_limit=limits.pids_limit,
tmpfs_size=limits.tmpfs_size,
read_only=str(security.read_only_root).lower(),
cap_drop=cap_drop,
dns_config=dns_config,
internal_network=str(not security.disable_network).lower(),
command=cmd_str,
)
async def _cleanup_dind(self, compose_file: str, sandbox_id: str) -> None:
"""Cleanup DinD environment."""
try:
cleanup_cmd = [
"docker-compose",
"-f",
compose_file,
"-p",
f"zenai-sandbox-{sandbox_id}",
"down",
"-v",
"--remove-orphans",
"--timeout",
"10",
]
proc = await asyncio.create_subprocess_exec(*cleanup_cmd)
await asyncio.wait_for(proc.communicate(), timeout=30)
except Exception as e:
logger.debug(f"DinD cleanup error: {e}")
async def _cleanup_worker(self) -> None:
"""Background worker for container cleanup."""
while True:
try:
container_id = await asyncio.wait_for(self._cleanup_queue.get(), timeout=60)
await self._cleanup_container(container_id)
except asyncio.TimeoutError:
# Periodic check for orphaned containers
await self._cleanup_orphaned()
except Exception as e:
logger.debug(f"Cleanup worker error: {e}")
async def _cleanup_container(self, container_id: str) -> None:
"""Remove a specific container."""
try:
if self.docker_client:
container = self.docker_client.containers.get(container_id)
container.remove(force=True, v=True)
logger.debug(f"Cleaned up container: {container_id[:12]}")
except Exception as e:
logger.debug(f"Container cleanup error: {e}")
async def _cleanup_orphaned(self) -> None:
"""Remove orphaned sandbox containers."""
try:
if not self.docker_client:
return
# Find old sandbox containers
containers = self.docker_client.containers.list(all=True, filters={"name": "zenai-sandbox-"})
for container in containers:
try:
# Check if container is old (> 1 hour)
created = datetime.fromisoformat(container.attrs["Created"].replace("Z", "+00:00"))
age = (datetime.now(timezone.utc) - created.replace(tzinfo=None)).total_seconds()
if age > 3600: # 1 hour
container.remove(force=True, v=True)
logger.info(f"Removed orphaned container: {container.name}")
except Exception as e:
logger.debug(f"Orphan cleanup error: {e}")
except Exception as e:
logger.debug(f"Orphaned cleanup error: {e}")
def _parse_resource_stats(self, stats: Dict) -> Dict[str, Any]:
"""Parse Docker stats for resource usage."""
try:
cpu_stats = stats.get("cpu_stats", {})
memory_stats = stats.get("memory_stats", {})
return {
"cpu_usage_percent": cpu_stats.get("cpu_usage", {}).get("total_usage", 0),
"memory_usage_bytes": memory_stats.get("usage", 0),
"memory_limit_bytes": memory_stats.get("limit", 0),
"memory_percent": (
(memory_stats.get("usage", 0) / memory_stats.get("limit", 1) * 100) if memory_stats.get("limit") else 0
),
}
except Exception:
return {}
async def cleanup_all(self) -> None:
"""Force cleanup of all active containers."""
if self._cleanup_task:
self._cleanup_task.cancel()
# Cleanup active containers
for container_id in self._active_containers:
await self._cleanup_container(container_id)
self._active_containers.clear()
# Cleanup by label
try:
if self.docker_client:
containers = self.docker_client.containers.list(all=True, filters={"name": "zenai-sandbox-"})
for container in containers:
container.remove(force=True, v=True)
except Exception as e:
logger.error(f"Cleanup all error: {e}")
# Convenience functions
async def execute_in_sandbox(
command: List[str], runtime: SandboxRuntime = SandboxRuntime.DOCKER, timeout: int = 60, **kwargs
) -> SandboxResult:
"""
Convenience function for sandboxed execution.
Args:
command: Command to execute
runtime: Sandbox runtime type
timeout: Execution timeout
**kwargs: Additional config options
Returns:
SandboxResult
"""
config = SandboxConfig(runtime=runtime, timeout=timeout, **kwargs)
sandbox = DockerSandbox(config)
await sandbox.initialize()
try:
return await sandbox.execute(command, timeout=timeout)
finally:
await sandbox.cleanup_all()
__all__ = [
"DockerSandbox",
"SandboxConfig",
"SandboxResult",
"SandboxRuntime",
"SandboxStatus",
"ResourceLimits",
"SecurityProfile",
"execute_in_sandbox",
]

Xet Storage Details

Size:
28.9 kB
·
Xet hash:
4ec9a61c3fa370f62158e00609e8b8c10c49ccc9e1e87f5676cd8caf0bf5d2e4

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