Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /zen_ai_pentest /plugin_manager.py
| """ | |
| Zen-AI-Pentest Plugin Manager | |
| ============================= | |
| Dynamic plugin system for security tool integration with AI-assisted selection. | |
| Supports 100+ security tools across multiple categories. | |
| """ | |
| import hashlib | |
| import importlib | |
| import importlib.util | |
| import inspect | |
| import json | |
| import logging | |
| import os | |
| import time | |
| from abc import ABC, abstractmethod | |
| from dataclasses import dataclass, field | |
| from enum import Enum | |
| from typing import Any, Callable, Dict, List, Optional, Type | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class ToolCategory(Enum): | |
| """Enumeration of security tool categories.""" | |
| NETWORK_SCANNING = "network_scanning" | |
| WEB_APPLICATION = "web_application" | |
| RECONNAISSANCE = "reconnaissance" | |
| EXPLOITATION = "exploitation" | |
| ACTIVE_DIRECTORY = "active_directory" | |
| CLOUD_SECURITY = "cloud_security" | |
| CONTAINER_SECURITY = "container_security" | |
| IOT_MOBILE = "iot_mobile" | |
| WIRELESS = "wireless" | |
| SOCIAL_ENGINEERING = "social_engineering" | |
| AI_LLM_SECURITY = "ai_llm_security" | |
| CRYPTOGRAPHY = "cryptography" | |
| FORENSICS = "forensics" | |
| VULNERABILITY_SCANNER = "vulnerability_scanner" | |
| UTILITY = "utility" | |
| class ToolRiskLevel(Enum): | |
| """Risk levels for tool execution.""" | |
| LOW = "low" | |
| MEDIUM = "medium" | |
| HIGH = "high" | |
| CRITICAL = "critical" | |
| class ToolMetadata: | |
| """Metadata for security tools.""" | |
| name: str | |
| version: str | |
| category: ToolCategory | |
| description: str | |
| author: str | |
| risk_level: ToolRiskLevel | |
| docker_image: Optional[str] = None | |
| binary_path: Optional[str] = None | |
| dependencies: List[str] = field(default_factory=list) | |
| tags: List[str] = field(default_factory=list) | |
| supported_platforms: List[str] = field(default_factory=lambda: ["linux"]) | |
| max_execution_time: int = 300 # seconds | |
| max_memory_mb: int = 1024 | |
| max_cpu_percent: float = 50.0 | |
| requires_root: bool = False | |
| requires_network: bool = True | |
| output_formats: List[str] = field(default_factory=lambda: ["json", "text"]) | |
| created_at: str = field(default_factory=lambda: time.strftime("%Y-%m-%d %H:%M:%S")) | |
| updated_at: str = field(default_factory=lambda: time.strftime("%Y-%m-%d %H:%M:%S")) | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "name": self.name, | |
| "version": self.version, | |
| "category": self.category.value, | |
| "description": self.description, | |
| "author": self.author, | |
| "risk_level": self.risk_level.value, | |
| "docker_image": self.docker_image, | |
| "binary_path": self.binary_path, | |
| "dependencies": self.dependencies, | |
| "tags": self.tags, | |
| "supported_platforms": self.supported_platforms, | |
| "max_execution_time": self.max_execution_time, | |
| "max_memory_mb": self.max_memory_mb, | |
| "max_cpu_percent": self.max_cpu_percent, | |
| "requires_root": self.requires_root, | |
| "requires_network": self.requires_network, | |
| "output_formats": self.output_formats, | |
| "created_at": self.created_at, | |
| "updated_at": self.updated_at, | |
| } | |
| def from_dict(cls, data: Dict[str, Any]) -> "ToolMetadata": | |
| return cls( | |
| name=data["name"], | |
| version=data["version"], | |
| category=ToolCategory(data["category"]), | |
| description=data["description"], | |
| author=data["author"], | |
| risk_level=ToolRiskLevel(data["risk_level"]), | |
| docker_image=data.get("docker_image"), | |
| binary_path=data.get("binary_path"), | |
| dependencies=data.get("dependencies", []), | |
| tags=data.get("tags", []), | |
| supported_platforms=data.get("supported_platforms", ["linux"]), | |
| max_execution_time=data.get("max_execution_time", 300), | |
| max_memory_mb=data.get("max_memory_mb", 1024), | |
| max_cpu_percent=data.get("max_cpu_percent", 50.0), | |
| requires_root=data.get("requires_root", False), | |
| requires_network=data.get("requires_network", True), | |
| output_formats=data.get("output_formats", ["json", "text"]), | |
| created_at=data.get("created_at", time.strftime("%Y-%m-%d %H:%M:%S")), | |
| updated_at=data.get("updated_at", time.strftime("%Y-%m-%d %H:%M:%S")), | |
| ) | |
| class ToolResult: | |
| """Result from tool execution.""" | |
| tool_name: str | |
| success: bool | |
| return_code: int | |
| stdout: str | |
| stderr: str | |
| execution_time: float | |
| output_files: List[str] = field(default_factory=list) | |
| parsed_output: Dict[str, Any] = field(default_factory=dict) | |
| findings: List[Dict[str, Any]] = field(default_factory=list) | |
| error_message: Optional[str] = None | |
| timestamp: str = field(default_factory=lambda: time.strftime("%Y-%m-%d %H:%M:%S")) | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| "tool_name": self.tool_name, | |
| "success": self.success, | |
| "return_code": self.return_code, | |
| "stdout": self.stdout, | |
| "stderr": self.stderr, | |
| "execution_time": self.execution_time, | |
| "output_files": self.output_files, | |
| "parsed_output": self.parsed_output, | |
| "findings": self.findings, | |
| "error_message": self.error_message, | |
| "timestamp": self.timestamp, | |
| } | |
| class BaseTool(ABC): | |
| """ | |
| Abstract base class for all security tools. | |
| All tools must inherit from this class and implement required methods. | |
| """ | |
| def __init__(self, metadata: ToolMetadata): | |
| self.metadata = metadata | |
| self.logger = logging.getLogger(f"tool.{metadata.name}") | |
| self._execution_history: List[Dict[str, Any]] = [] | |
| self._performance_metrics = { | |
| "total_executions": 0, | |
| "successful_executions": 0, | |
| "failed_executions": 0, | |
| "average_execution_time": 0.0, | |
| "total_findings": 0, | |
| } | |
| def validate_input(self, target: str, options: Dict[str, Any]) -> bool: | |
| """Validate input parameters before execution.""" | |
| pass | |
| def build_command(self, target: str, options: Dict[str, Any]) -> List[str]: | |
| """Build the command line arguments for the tool.""" | |
| pass | |
| def parse_output(self, stdout: str, stderr: str) -> Dict[str, Any]: | |
| """Parse tool output into structured data.""" | |
| pass | |
| def pre_execute(self, target: str, options: Dict[str, Any]) -> None: | |
| """Hook called before tool execution.""" | |
| self.logger.info(f"Pre-execution hook for {self.metadata.name}") | |
| def post_execute(self, result: ToolResult) -> ToolResult: | |
| """Hook called after tool execution. Can modify result.""" | |
| self.logger.info(f"Post-execution hook for {self.metadata.name}") | |
| return result | |
| def get_performance_score(self) -> float: | |
| """Calculate performance score based on execution history.""" | |
| if self._performance_metrics["total_executions"] == 0: | |
| return 0.5 # Default neutral score | |
| success_rate = self._performance_metrics["successful_executions"] / self._performance_metrics["total_executions"] | |
| return success_rate | |
| def update_metrics(self, result: ToolResult) -> None: | |
| """Update performance metrics after execution.""" | |
| self._performance_metrics["total_executions"] += 1 | |
| if result.success: | |
| self._performance_metrics["successful_executions"] += 1 | |
| else: | |
| self._performance_metrics["failed_executions"] += 1 | |
| # Update average execution time | |
| total = self._performance_metrics["total_executions"] | |
| current_avg = self._performance_metrics["average_execution_time"] | |
| self._performance_metrics["average_execution_time"] = (current_avg * (total - 1) + result.execution_time) / total | |
| self._performance_metrics["total_findings"] += len(result.findings) | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Serialize tool to dictionary.""" | |
| return { | |
| "metadata": self.metadata.to_dict(), | |
| "performance_metrics": self._performance_metrics, | |
| "execution_history_count": len(self._execution_history), | |
| } | |
| class PluginRegistry: | |
| """ | |
| Central registry for all security tool plugins. | |
| Handles plugin discovery, registration, and lifecycle management. | |
| """ | |
| def __init__(self, plugin_dirs: List[str] = None): | |
| self._plugins: Dict[str, BaseTool] = {} | |
| self._plugin_classes: Dict[str, Type[BaseTool]] = {} | |
| self._plugin_dirs = plugin_dirs or ["./plugins", "./tools"] | |
| self._hooks: Dict[str, List[Callable]] = { | |
| "pre_register": [], | |
| "post_register": [], | |
| "pre_execute": [], | |
| "post_execute": [], | |
| "on_error": [], | |
| } | |
| self._version_compatibility: Dict[str, List[str]] = {} | |
| self.logger = logging.getLogger("PluginRegistry") | |
| def register( | |
| self, | |
| name: str, | |
| tool_class: Type[BaseTool], | |
| metadata: ToolMetadata = None, | |
| ) -> bool: | |
| """Register a new tool plugin.""" | |
| try: | |
| # Run pre-register hooks | |
| for hook in self._hooks["pre_register"]: | |
| if not hook(name, tool_class, metadata): | |
| self.logger.warning(f"Pre-register hook blocked registration of {name}") | |
| return False | |
| if metadata is None: | |
| # Try to get metadata from class | |
| metadata = getattr(tool_class, "METADATA", None) | |
| if metadata is None: | |
| raise ValueError(f"No metadata provided for {name}") | |
| # Check version compatibility | |
| if not self._check_compatibility(metadata): | |
| self.logger.warning(f"Version incompatibility for {name}") | |
| return False | |
| # Create instance | |
| instance = tool_class(metadata) | |
| # Register plugin | |
| self._plugins[name] = instance | |
| self._plugin_classes[name] = tool_class | |
| self.logger.info(f"Successfully registered plugin: {name}") | |
| # Run post-register hooks | |
| for hook in self._hooks["post_register"]: | |
| hook(name, instance) | |
| return True | |
| except Exception as e: | |
| self.logger.error(f"Failed to register plugin {name}: {str(e)}") | |
| for hook in self._hooks["on_error"]: | |
| hook(name, e) | |
| return False | |
| def unregister(self, name: str) -> bool: | |
| """Unregister a plugin.""" | |
| if name in self._plugins: | |
| del self._plugins[name] | |
| del self._plugin_classes[name] | |
| self.logger.info(f"Unregistered plugin: {name}") | |
| return True | |
| return False | |
| def get(self, name: str) -> Optional[BaseTool]: | |
| """Get a registered plugin by name.""" | |
| return self._plugins.get(name) | |
| def get_all(self) -> Dict[str, BaseTool]: | |
| """Get all registered plugins.""" | |
| return self._plugins.copy() | |
| def get_by_category(self, category: ToolCategory) -> Dict[str, BaseTool]: | |
| """Get plugins filtered by category.""" | |
| return {name: tool for name, tool in self._plugins.items() if tool.metadata.category == category} | |
| def get_by_tag(self, tag: str) -> Dict[str, BaseTool]: | |
| """Get plugins filtered by tag.""" | |
| return {name: tool for name, tool in self._plugins.items() if tag in tool.metadata.tags} | |
| def get_by_risk_level(self, max_risk: ToolRiskLevel) -> Dict[str, BaseTool]: | |
| """Get plugins up to a maximum risk level.""" | |
| risk_order = [ | |
| ToolRiskLevel.LOW, | |
| ToolRiskLevel.MEDIUM, | |
| ToolRiskLevel.HIGH, | |
| ToolRiskLevel.CRITICAL, | |
| ] | |
| max_index = risk_order.index(max_risk) | |
| allowed_risks = risk_order[: max_index + 1] | |
| return {name: tool for name, tool in self._plugins.items() if tool.metadata.risk_level in allowed_risks} | |
| def discover_plugins(self, directory: str = None) -> List[str]: | |
| """Discover plugins in the plugin directories.""" | |
| discovered = [] | |
| directories = [directory] if directory else self._plugin_dirs | |
| for plugin_dir in directories: | |
| if not os.path.exists(plugin_dir): | |
| continue | |
| for root, dirs, files in os.walk(plugin_dir): | |
| for file in files: | |
| if file.endswith("_plugin.py"): | |
| plugin_path = os.path.join(root, file) | |
| try: | |
| self._load_plugin_file(plugin_path) | |
| discovered.append(plugin_path) | |
| except Exception as e: | |
| self.logger.error(f"Failed to load plugin {plugin_path}: {e}") | |
| return discovered | |
| def _load_plugin_file(self, plugin_path: str) -> None: | |
| """Load a single plugin file.""" | |
| spec = importlib.util.spec_from_file_location( | |
| f"plugin_{hashlib.md5(plugin_path.encode(), usedforsecurity=False).hexdigest()}", | |
| plugin_path, | |
| ) | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| # Find plugin classes in module | |
| for name, obj in inspect.getmembers(module): | |
| if inspect.isclass(obj) and issubclass(obj, BaseTool) and obj is not BaseTool and hasattr(obj, "METADATA"): | |
| metadata = obj.METADATA | |
| self.register(metadata.name, obj, metadata) | |
| def _check_compatibility(self, metadata: ToolMetadata) -> bool: | |
| """Check if plugin is compatible with current system.""" | |
| # Check platform compatibility | |
| import platform | |
| current_platform = platform.system().lower() | |
| if current_platform not in [p.lower() for p in metadata.supported_platforms]: | |
| return False | |
| # Check version compatibility | |
| if metadata.name in self._version_compatibility: | |
| supported_versions = self._version_compatibility[metadata.name] | |
| if metadata.version not in supported_versions: | |
| return False | |
| return True | |
| def add_hook(self, event: str, callback: Callable) -> None: | |
| """Add a lifecycle hook.""" | |
| if event in self._hooks: | |
| self._hooks[event].append(callback) | |
| def remove_hook(self, event: str, callback: Callable) -> None: | |
| """Remove a lifecycle hook.""" | |
| if event in self._hooks and callback in self._hooks[event]: | |
| self._hooks[event].remove(callback) | |
| def export_catalog(self, output_path: str) -> None: | |
| """Export tool catalog to JSON.""" | |
| catalog = { | |
| "tools": [tool.to_dict() for tool in self._plugins.values()], | |
| "total_count": len(self._plugins), | |
| "categories": list(set(t.metadata.category.value for t in self._plugins.values())), | |
| } | |
| with open(output_path, "w") as f: | |
| json.dump(catalog, f, indent=2) | |
| def import_catalog(self, catalog_path: str) -> int: | |
| """Import tool catalog from JSON.""" | |
| with open(catalog_path, "r") as f: | |
| catalog = json.load(f) | |
| count = 0 | |
| for tool_data in catalog.get("tools", []): | |
| try: | |
| metadata = ToolMetadata.from_dict(tool_data["metadata"]) | |
| # Create a basic tool class dynamically | |
| tool_class = self._create_tool_class(metadata) | |
| if self.register(metadata.name, tool_class, metadata): | |
| count += 1 | |
| except Exception as e: | |
| self.logger.error(f"Failed to import tool: {e}") | |
| return count | |
| def _create_tool_class(self, metadata: ToolMetadata) -> Type[BaseTool]: | |
| """Dynamically create a tool class from metadata.""" | |
| class DynamicTool(BaseTool): | |
| METADATA = metadata | |
| def validate_input(self, target: str, options: Dict[str, Any]) -> bool: | |
| return True # Basic validation | |
| def build_command(self, target: str, options: Dict[str, Any]) -> List[str]: | |
| cmd = [metadata.binary_path or metadata.name] | |
| cmd.append(target) | |
| for key, value in options.items(): | |
| cmd.extend([f"--{key}", str(value)]) | |
| return cmd | |
| def parse_output(self, stdout: str, stderr: str) -> Dict[str, Any]: | |
| return {"raw_output": stdout} | |
| return DynamicTool | |
| # Singleton registry instance | |
| _registry = None | |
| def get_registry() -> PluginRegistry: | |
| """Get the singleton plugin registry instance.""" | |
| global _registry | |
| if _registry is None: | |
| _registry = PluginRegistry() | |
| return _registry | |
| if __name__ == "__main__": | |
| # Example usage | |
| registry = get_registry() | |
| logger.info("Plugin Manager initialized") | |
| logger.info(f"Plugin directories: {registry._plugin_dirs}") | |
Xet Storage Details
- Size:
- 17.2 kB
- Xet hash:
- e9e8e8f78c367843aff41d09538ec13f31d3855d76ff376bc1adaf60a68a1cb1
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.