Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /zen_ai_pentest /tool_wrapper.py
| """ | |
| Tool Wrapper with Safety Mechanisms for Zen-AI-Pentest | |
| ====================================================== | |
| Implements secure tool execution with: | |
| - Resource quotas and limits | |
| - Timeout handling | |
| - Network isolation | |
| - Read-only mounts | |
| - Secure credential injection | |
| """ | |
| import hashlib | |
| import json | |
| import logging | |
| import os | |
| import resource | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import threading | |
| import time | |
| from dataclasses import dataclass, field | |
| from typing import Any, Dict, List, Optional | |
| import docker # noqa: I001 | |
| from docker.errors import APIError, ContainerError, DockerException | |
| from docker.types import Mount | |
| from .plugin_manager import BaseTool, ToolResult | |
| logger = logging.getLogger(__name__) | |
| class SandboxConfig: | |
| """Configuration for sandboxed execution.""" | |
| # Resource limits | |
| max_cpu_percent: float = 50.0 | |
| max_memory_mb: int = 1024 | |
| max_execution_time: int = 300 | |
| max_disk_mb: int = 512 | |
| # Network settings | |
| network_mode: str = "none" # none, bridge, host | |
| allowed_ports: List[int] = field(default_factory=list) | |
| blocked_hosts: List[str] = field(default_factory=lambda: ["169.254.169.254"]) # AWS metadata | |
| # Filesystem settings | |
| read_only_mounts: List[str] = field(default_factory=list) | |
| writable_mounts: Dict[str, str] = field(default_factory=dict) | |
| tmpfs_size_mb: int = 100 | |
| # Security settings | |
| drop_capabilities: List[str] = field(default_factory=lambda: ["ALL"]) | |
| add_capabilities: List[str] = field(default_factory=list) | |
| seccomp_profile: Optional[str] = None | |
| apparmor_profile: Optional[str] = None | |
| no_new_privileges: bool = True | |
| # User settings | |
| run_as_user: str = "nobody" | |
| run_as_group: str = "nogroup" | |
| # Credential settings | |
| credential_env_vars: Dict[str, str] = field(default_factory=dict) | |
| credential_files: Dict[str, str] = field(default_factory=dict) | |
| def to_docker_resources(self) -> Dict[str, Any]: | |
| """Convert to Docker resources format.""" | |
| return { | |
| "cpu_quota": int(self.max_cpu_percent * 1000), # Docker uses microseconds | |
| "cpu_period": 100000, | |
| "mem_limit": f"{self.max_memory_mb}m", | |
| "memswap_limit": f"{self.max_memory_mb}m", | |
| } | |
| class ExecutionOptions: | |
| """Options for tool execution.""" | |
| target: str | |
| timeout: int = 300 | |
| output_format: str = "json" | |
| verbose: bool = False | |
| save_output: bool = True | |
| custom_args: Dict[str, Any] = field(default_factory=dict) | |
| environment_vars: Dict[str, str] = field(default_factory=dict) | |
| class ResourceMonitor: | |
| """Monitors resource usage during tool execution.""" | |
| def __init__(self, max_memory_mb: int = 1024, max_cpu_percent: float = 50.0): | |
| self.max_memory_mb = max_memory_mb | |
| self.max_cpu_percent = max_cpu_percent | |
| self.peak_memory_mb = 0 | |
| self.peak_cpu_percent = 0.0 | |
| self.start_time = None | |
| self._monitoring = False | |
| self._monitor_thread = None | |
| def start(self) -> None: | |
| """Start resource monitoring.""" | |
| self.start_time = time.time() | |
| self._monitoring = True | |
| self._monitor_thread = threading.Thread(target=self._monitor_loop) | |
| self._monitor_thread.daemon = True | |
| self._monitor_thread.start() | |
| def stop(self) -> Dict[str, Any]: | |
| """Stop monitoring and return statistics.""" | |
| self._monitoring = False | |
| if self._monitor_thread: | |
| self._monitor_thread.join(timeout=1.0) | |
| return { | |
| "peak_memory_mb": self.peak_memory_mb, | |
| "peak_cpu_percent": self.peak_cpu_percent, | |
| "execution_time": (time.time() - self.start_time if self.start_time else 0), | |
| } | |
| def _monitor_loop(self) -> None: | |
| """Monitor loop running in separate thread.""" | |
| import psutil | |
| process = psutil.Process() | |
| while self._monitoring: | |
| try: | |
| # Memory usage | |
| mem_info = process.memory_info() | |
| mem_mb = mem_info.rss / 1024 / 1024 | |
| self.peak_memory_mb = max(self.peak_memory_mb, mem_mb) | |
| # CPU usage | |
| cpu_percent = process.cpu_percent(interval=0.1) | |
| self.peak_cpu_percent = max(self.peak_cpu_percent, cpu_percent) | |
| # Check limits | |
| if mem_mb > self.max_memory_mb: | |
| logger.warning(f"Memory limit exceeded: {mem_mb:.2f}MB > {self.max_memory_mb}MB") | |
| time.sleep(0.5) | |
| except Exception as e: | |
| logger.error(f"Monitor error: {e}") | |
| break | |
| class SecureToolWrapper: | |
| """ | |
| Wrapper for secure tool execution with sandboxing. | |
| """ | |
| def __init__( | |
| self, | |
| use_docker: bool = True, | |
| docker_socket: str = "unix://var/run/docker.sock", | |
| ): | |
| self.use_docker = use_docker | |
| self.docker_socket = docker_socket | |
| self._docker_client = None | |
| self._temp_dirs: List[str] = [] | |
| self.logger = logging.getLogger("SecureToolWrapper") | |
| def docker_client(self): | |
| """Lazy initialization of Docker client.""" | |
| if self._docker_client is None and self.use_docker: | |
| try: | |
| self._docker_client = docker.DockerClient(base_url=self.docker_socket) | |
| except DockerException as e: | |
| self.logger.error(f"Failed to connect to Docker: {e}") | |
| self.use_docker = False | |
| return self._docker_client | |
| def execute( | |
| self, | |
| tool: BaseTool, | |
| options: ExecutionOptions, | |
| sandbox_config: SandboxConfig = None, | |
| ) -> ToolResult: | |
| """ | |
| Execute a tool with safety mechanisms. | |
| Args: | |
| tool: The tool to execute | |
| options: Execution options | |
| sandbox_config: Sandbox configuration | |
| Returns: | |
| ToolResult with execution results | |
| """ | |
| if sandbox_config is None: | |
| sandbox_config = self._create_default_sandbox_config(tool) | |
| start_time = time.time() | |
| try: | |
| # Pre-execution validation | |
| if not tool.validate_input(options.target, options.custom_args): | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=False, | |
| return_code=-1, | |
| stdout="", | |
| stderr="Input validation failed", | |
| execution_time=0, | |
| error_message="Input validation failed", | |
| ) | |
| # Run pre-execute hook | |
| tool.pre_execute(options.target, options.custom_args) | |
| # Execute based on mode | |
| if self.use_docker and tool.metadata.docker_image: | |
| result = self._execute_docker(tool, options, sandbox_config) | |
| else: | |
| result = self._execute_subprocess(tool, options, sandbox_config) | |
| # Run post-execute hook | |
| result = tool.post_execute(result) | |
| # Update tool metrics | |
| tool.update_metrics(result) | |
| return result | |
| except Exception as e: | |
| self.logger.error(f"Execution failed: {e}") | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=False, | |
| return_code=-1, | |
| stdout="", | |
| stderr=str(e), | |
| execution_time=time.time() - start_time, | |
| error_message=str(e), | |
| ) | |
| finally: | |
| # Cleanup temporary directories | |
| self._cleanup_temp_dirs() | |
| def _execute_docker(self, tool: BaseTool, options: ExecutionOptions, config: SandboxConfig) -> ToolResult: | |
| """Execute tool in Docker container.""" | |
| start_time = time.time() | |
| # Create temporary directories | |
| work_dir = self._create_temp_dir("work") | |
| output_dir = self._create_temp_dir("output") | |
| # Build command | |
| command = tool.build_command(options.target, options.custom_args) | |
| # Prepare mounts | |
| mounts = [] | |
| # Read-only mounts for tool binaries | |
| for ro_path in config.read_only_mounts: | |
| mounts.append(Mount(target=ro_path, source=ro_path, type="bind", read_only=True)) | |
| # Writable output directory | |
| mounts.append( | |
| Mount( | |
| target="/output", | |
| source=output_dir, | |
| type="bind", | |
| read_only=False, | |
| ) | |
| ) | |
| # Writable work directory | |
| mounts.append(Mount(target="/work", source=work_dir, type="bind", read_only=False)) | |
| # Prepare environment variables | |
| env_vars = { | |
| "TARGET": options.target, | |
| "OUTPUT_FORMAT": options.output_format, | |
| "VERBOSE": "1" if options.verbose else "0", | |
| } | |
| env_vars.update(options.environment_vars) | |
| # Add credentials securely | |
| for key, value in config.credential_env_vars.items(): | |
| env_vars[key] = value | |
| # Prepare security options | |
| security_opt = [] | |
| if config.seccomp_profile: | |
| security_opt.append(f"seccomp={config.seccomp_profile}") | |
| if config.apparmor_profile: | |
| security_opt.append(f"apparmor={config.apparmor_profile}") | |
| if config.no_new_privileges: | |
| security_opt.append("no-new-privileges:true") | |
| try: | |
| # Run container | |
| container = self.docker_client.containers.run( | |
| image=tool.metadata.docker_image, | |
| command=command, | |
| detach=True, | |
| environment=env_vars, | |
| mounts=mounts, | |
| network_mode=config.network_mode, | |
| cap_drop=config.drop_capabilities, | |
| cap_add=config.add_capabilities, | |
| security_opt=security_opt, | |
| user=f"{config.run_as_user}:{config.run_as_group}", | |
| **config.to_docker_resources(), | |
| stdout=True, | |
| stderr=True, | |
| ) | |
| # Wait for completion with timeout | |
| try: | |
| result = container.wait(timeout=options.timeout) | |
| exit_code = result.get("StatusCode", -1) | |
| except Exception: | |
| # Timeout - kill container | |
| container.kill() | |
| exit_code = -1 | |
| # Get logs | |
| stdout = container.logs(stdout=True, stderr=False).decode("utf-8", errors="ignore") | |
| stderr = container.logs(stdout=False, stderr=True).decode("utf-8", errors="ignore") | |
| # Cleanup container | |
| container.remove(force=True) | |
| # Parse output | |
| parsed_output = tool.parse_output(stdout, stderr) | |
| # Get output files | |
| output_files = [] | |
| for root, dirs, files in os.walk(output_dir): | |
| for f in files: | |
| output_files.append(os.path.join(root, f)) | |
| execution_time = time.time() - start_time | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=exit_code == 0, | |
| return_code=exit_code, | |
| stdout=stdout, | |
| stderr=stderr, | |
| execution_time=execution_time, | |
| output_files=output_files, | |
| parsed_output=parsed_output, | |
| findings=parsed_output.get("findings", []), | |
| ) | |
| except ContainerError as e: | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=False, | |
| return_code=-1, | |
| stdout="", | |
| stderr=str(e), | |
| execution_time=time.time() - start_time, | |
| error_message=f"Container error: {e}", | |
| ) | |
| except APIError as e: | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=False, | |
| return_code=-1, | |
| stdout="", | |
| stderr=str(e), | |
| execution_time=time.time() - start_time, | |
| error_message=f"Docker API error: {e}", | |
| ) | |
| def _execute_subprocess(self, tool: BaseTool, options: ExecutionOptions, config: SandboxConfig) -> ToolResult: | |
| """Execute tool using subprocess with resource limits.""" | |
| start_time = time.time() | |
| # Build command | |
| command = tool.build_command(options.target, options.custom_args) | |
| # Create output directory | |
| output_dir = self._create_temp_dir("output") | |
| # Prepare environment | |
| env = os.environ.copy() | |
| env.update(options.environment_vars) | |
| env["TARGET"] = options.target | |
| env["OUTPUT_DIR"] = output_dir | |
| # Add credentials | |
| for key, value in config.credential_env_vars.items(): | |
| env[key] = value | |
| # Start resource monitor | |
| monitor = ResourceMonitor( | |
| max_memory_mb=config.max_memory_mb, | |
| max_cpu_percent=config.max_cpu_percent, | |
| ) | |
| def preexec_fn(): | |
| """Set resource limits before execution.""" | |
| # Memory limit | |
| resource.setrlimit( | |
| resource.RLIMIT_AS, | |
| ( | |
| config.max_memory_mb * 1024 * 1024, | |
| config.max_memory_mb * 1024 * 1024, | |
| ), | |
| ) | |
| # CPU time limit | |
| resource.setrlimit(resource.RLIMIT_CPU, (options.timeout, options.timeout)) | |
| # File size limit | |
| resource.setrlimit( | |
| resource.RLIMIT_FSIZE, | |
| ( | |
| config.max_disk_mb * 1024 * 1024, | |
| config.max_disk_mb * 1024 * 1024, | |
| ), | |
| ) | |
| # Process limit | |
| resource.setrlimit(resource.RLIMIT_NPROC, (100, 100)) | |
| try: | |
| monitor.start() | |
| # Run subprocess | |
| process = subprocess.Popen( | |
| command, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| env=env, | |
| cwd=output_dir, | |
| preexec_fn=preexec_fn, | |
| ) | |
| # Wait with timeout | |
| try: | |
| stdout, stderr = process.communicate(timeout=options.timeout) | |
| exit_code = process.returncode | |
| except subprocess.TimeoutExpired: | |
| process.kill() | |
| stdout, stderr = process.communicate() | |
| exit_code = -1 | |
| monitor.stop() | |
| # Decode output | |
| stdout_str = stdout.decode("utf-8", errors="ignore") | |
| stderr_str = stderr.decode("utf-8", errors="ignore") | |
| # Parse output | |
| parsed_output = tool.parse_output(stdout_str, stderr_str) | |
| # Get output files | |
| output_files = [] | |
| for root, dirs, files in os.walk(output_dir): | |
| for f in files: | |
| output_files.append(os.path.join(root, f)) | |
| execution_time = time.time() - start_time | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=exit_code == 0, | |
| return_code=exit_code, | |
| stdout=stdout_str, | |
| stderr=stderr_str, | |
| execution_time=execution_time, | |
| output_files=output_files, | |
| parsed_output=parsed_output, | |
| findings=parsed_output.get("findings", []), | |
| ) | |
| except Exception as e: | |
| monitor.stop() | |
| return ToolResult( | |
| tool_name=tool.metadata.name, | |
| success=False, | |
| return_code=-1, | |
| stdout="", | |
| stderr=str(e), | |
| execution_time=time.time() - start_time, | |
| error_message=str(e), | |
| ) | |
| def _create_default_sandbox_config(self, tool: BaseTool) -> SandboxConfig: | |
| """Create default sandbox config based on tool metadata.""" | |
| return SandboxConfig( | |
| max_cpu_percent=tool.metadata.max_cpu_percent, | |
| max_memory_mb=tool.metadata.max_memory_mb, | |
| max_execution_time=tool.metadata.max_execution_time, | |
| network_mode=("bridge" if tool.metadata.requires_network else "none"), | |
| ) | |
| def _create_temp_dir(self, prefix: str = "zen") -> str: | |
| """Create a temporary directory.""" | |
| temp_dir = tempfile.mkdtemp(prefix=f"{prefix}_") | |
| self._temp_dirs.append(temp_dir) | |
| return temp_dir | |
| def _cleanup_temp_dirs(self) -> None: | |
| """Clean up all temporary directories.""" | |
| for temp_dir in self._temp_dirs: | |
| try: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| except Exception as e: | |
| self.logger.warning(f"Failed to cleanup {temp_dir}: {e}") | |
| self._temp_dirs.clear() | |
| def inject_credentials( | |
| self, | |
| config: SandboxConfig, | |
| credentials: Dict[str, str], | |
| method: str = "env", | |
| ) -> SandboxConfig: | |
| """ | |
| Securely inject credentials into sandbox config. | |
| Args: | |
| config: Sandbox configuration to modify | |
| credentials: Credentials to inject | |
| method: Injection method (env, file, or tmpfs) | |
| Returns: | |
| Modified sandbox configuration | |
| """ | |
| if method == "env": | |
| # Environment variables (least secure, but simple) | |
| for key, value in credentials.items(): | |
| hashed_key = hashlib.sha256(f"ZEN_{key}".encode()).hexdigest()[:16] | |
| config.credential_env_vars[hashed_key] = value | |
| elif method == "file": | |
| # Temporary file (more secure) | |
| cred_file = self._create_temp_dir("creds") | |
| cred_path = os.path.join(cred_file, "credentials.json") | |
| with open(cred_path, "w") as f: | |
| json.dump(credentials, f) | |
| os.chmod(cred_path, 0o600) | |
| config.credential_files[cred_path] = "/run/secrets/credentials" | |
| elif method == "tmpfs": | |
| # tmpfs mount (most secure) | |
| config.tmpfs_size_mb = max(config.tmpfs_size_mb, 10) | |
| # Credentials will be written to tmpfs at runtime | |
| return config | |
| class NetworkIsolator: | |
| """ | |
| Manages network isolation for tool execution. | |
| """ | |
| def __init__(self): | |
| self._iptables_rules = [] | |
| self.logger = logging.getLogger("NetworkIsolator") | |
| def create_isolated_network(self, name: str, blocked_hosts: List[str] = None) -> str: | |
| """ | |
| Create an isolated Docker network. | |
| Returns: | |
| Network name | |
| """ | |
| try: | |
| client = docker.from_env() | |
| # Create network with internal flag | |
| network = client.networks.create( | |
| name=name, | |
| driver="bridge", | |
| internal=True, # No external access | |
| options={ | |
| "com.docker.network.bridge.enable_icc": "false", | |
| "com.docker.network.bridge.enable_ip_masquerade": "false", | |
| }, | |
| ) | |
| self.logger.info(f"Created isolated network: {name}") | |
| return network.name | |
| except DockerException as e: | |
| self.logger.error(f"Failed to create network: {e}") | |
| return None | |
| def apply_egress_filtering( | |
| self, | |
| container_id: str, | |
| allowed_hosts: List[str] = None, | |
| blocked_hosts: List[str] = None, | |
| ) -> bool: | |
| """ | |
| Apply egress filtering to a container. | |
| Args: | |
| container_id: Docker container ID | |
| allowed_hosts: List of allowed hosts (whitelist) | |
| blocked_hosts: List of blocked hosts (blacklist) | |
| Returns: | |
| True if successful | |
| """ | |
| try: | |
| client = docker.from_env() | |
| container = client.containers.get(container_id) | |
| # Get container PID for network namespace | |
| container.attrs["State"]["Pid"] | |
| # Apply iptables rules in container's network namespace | |
| # This is a simplified version - real implementation would use nsenter | |
| if blocked_hosts: | |
| for host in blocked_hosts: | |
| rule = f"OUTPUT -d {host} -j DROP" | |
| self._iptables_rules.append((container_id, rule)) | |
| self.logger.info(f"Applied egress filtering to {container_id}") | |
| return True | |
| except Exception as e: | |
| self.logger.error(f"Failed to apply egress filtering: {e}") | |
| return False | |
| # Example usage | |
| if __name__ == "__main__": | |
| wrapper = SecureToolWrapper() | |
| logger.info("Secure Tool Wrapper initialized") | |
| logger.info(f"Docker available: {wrapper.docker_client is not None}") | |
Xet Storage Details
- Size:
- 20.9 kB
- Xet hash:
- 7b3309df44ba83f59a33b62cfe7f137372d9ca007a3fe8c1d98a2733649332bd
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.