Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /agents /recovery_engine.py
| """ | |
| RecoveryEngine - Finale Version mit State-Transitions und Tool-Fallbacks | |
| Integriert mit ReActAgent und ToolExecutor | |
| """ | |
| import logging | |
| from enum import Enum | |
| from typing import Any, Dict | |
| logger = logging.getLogger("RecoveryEngine") | |
| class AgentState(Enum): | |
| PLANNING = "PLANNING" | |
| EXECUTING = "EXECUTING" | |
| ANALYZING = "ANALYZING" | |
| RECOVERY = "RECOVERY" | |
| SUCCESS = "SUCCESS" | |
| ERROR = "ERROR" | |
| class RecoveryEngine: | |
| """ | |
| Das Bindeglied zwischen strategischem Denken (Prompt) und robuster Ausführung (ToolExecutor) | |
| Features: | |
| - Wertet fallback_state und self_correction aus dem LLM-JSON aus | |
| - Führt State-Transitions durch | |
| - Bietet Tool-Fallbacks (Gobuster -> dirb, nmap -> masscan) | |
| - Gibt Fehler-Kontext zurück an LLM für Replannung | |
| """ | |
| # Tool-Fallback-Matrix | |
| TOOL_FALLBACKS = { | |
| "gobuster": "dirb", | |
| "nmap": "masscan", | |
| "masscan": "naabu", | |
| "ffuf": "gobuster", | |
| "sqlmap": "python_sqlmap_api", # Alternative API-basierte Version | |
| "amass": "subfinder", | |
| "subfinder": "assetfinder", | |
| "nikto": "nuclei", | |
| "burpsuite": "zap", | |
| } | |
| def __init__(self, agent=None): | |
| self.agent = agent | |
| self.failure_count: Dict[str, int] = {} | |
| self.recovery_history: list = [] | |
| def handle_failure(self, tool_name: str, error_msg: str, ai_instructions: Dict[str, Any]) -> Dict[str, Any]: | |
| """ | |
| Wird aufgerufen wenn ToolExecutor einen Fehler meldet | |
| Args: | |
| tool_name: Name des fehlgeschlagenen Tools | |
| error_msg: stderr oder Fehlermeldung | |
| ai_instructions: Das JSON vom LLM (mit fallback_state, self_correction) | |
| """ | |
| fallback = ai_instructions.get("fallback_state", "RECOVERY") | |
| correction = ai_instructions.get("self_correction", "No correction provided") | |
| logger.warning(f"🚨 TOOL FAILURE: {tool_name} - {error_msg}") | |
| logger.info(f"🔄 FALLBACK STATE: {fallback}") | |
| logger.info(f"💡 SELF-CORRECTION: {correction}") | |
| # Track failures | |
| self.failure_count[tool_name] = self.failure_count.get(tool_name, 0) + 1 | |
| # 1. State-Transition | |
| if self.agent: | |
| self.agent.update_state(AgentState(fallback)) | |
| # 2. Fehler-Typ erkennen und handhaben | |
| error_lower = error_msg.lower() | |
| if "command not found" in error_lower or "not found" in error_lower: | |
| return self._handle_missing_tool(tool_name, correction) | |
| if "timeout" in error_lower or "timed out" in error_lower: | |
| return self._handle_timeout(tool_name, correction) | |
| if "permission denied" in error_lower: | |
| return self._handle_permission_error(tool_name, correction) | |
| if "connection refused" in error_lower or "connection reset" in error_lower: | |
| return self._handle_connection_error(tool_name, correction) | |
| # 3. Kein spezifischer Handler -> Zurück an LLM | |
| return self._replan_with_context(tool_name, error_msg, correction) | |
| def _handle_missing_tool(self, tool_name: str, correction: str) -> Dict[str, Any]: | |
| """Tool ist nicht installiert -> Alternative vorschlagen""" | |
| fallback_tool = self.TOOL_FALLBACKS.get(tool_name) | |
| if fallback_tool: | |
| logger.info(f"🔄 SWITCHING TOOL: {tool_name} -> {fallback_tool}") | |
| self.recovery_history.append( | |
| { | |
| "type": "tool_switch", | |
| "from": tool_name, | |
| "to": fallback_tool, | |
| "reason": "tool_not_found", | |
| } | |
| ) | |
| return { | |
| "action": "SWITCH_TOOL", | |
| "original_tool": tool_name, | |
| "new_tool": fallback_tool, | |
| "message": f"Tool {tool_name} not found, switching to {fallback_tool}", | |
| "state": "PLANNING", | |
| } | |
| else: | |
| logger.error(f"❌ No fallback for {tool_name}") | |
| return { | |
| "action": "ABORT", | |
| "reason": f"Tool {tool_name} missing and no fallback available", | |
| "state": "ERROR", | |
| } | |
| def _handle_timeout(self, tool_name: str, correction: str) -> Dict[str, Any]: | |
| """Timeout -> Rate-Limiting oder Proxy vorschlagen""" | |
| logger.info(f"⏳ TIMEOUT in {tool_name}. Suggesting delay/proxy.") | |
| self.recovery_history.append( | |
| { | |
| "type": "timeout", | |
| "tool": tool_name, | |
| "action": "retry_with_delay", | |
| } | |
| ) | |
| return { | |
| "action": "RETRY_WITH_DELAY", | |
| "tool": tool_name, | |
| "delay": 5, | |
| "suggestion": "Add --delay or use proxy/tor", | |
| "message": f"{tool_name} timed out, retrying with delay", | |
| "state": "PLANNING", | |
| } | |
| def _handle_permission_error(self, tool_name: str, correction: str) -> Dict[str, Any]: | |
| """Permission Denied -> Root/Sudo vorschlagen""" | |
| logger.warning(f"🔒 PERMISSION DENIED for {tool_name}") | |
| return { | |
| "action": "ESCALATE_PERMISSIONS", | |
| "tool": tool_name, | |
| "suggestion": "Run with sudo or check capabilities", | |
| "message": f"Permission denied for {tool_name}, escalation needed", | |
| "state": "RECOVERY", | |
| } | |
| def _handle_connection_error(self, tool_name: str, correction: str) -> Dict[str, Any]: | |
| """Connection Error -> Proxy oder alternative Route""" | |
| logger.warning(f"🔌 CONNECTION ERROR for {tool_name}") | |
| return { | |
| "action": "USE_PROXY", | |
| "tool": tool_name, | |
| "suggestion": "Try proxychains or VPN", | |
| "message": f"Connection failed for {tool_name}, suggesting proxy", | |
| "state": "RECOVERY", | |
| } | |
| def _replan_with_context(self, tool_name: str, error_msg: str, correction: str) -> Dict[str, Any]: | |
| """Gibt Kontext an LLM zurück für Replannung""" | |
| context = f""" | |
| Error in {tool_name}: {error_msg} | |
| Your planned correction: {correction} | |
| Failure count: {self.failure_count.get(tool_name, 1)} | |
| Please replan with alternative approach. | |
| """.strip() | |
| logger.info(f"🔄 REPLANNING with context for {tool_name}") | |
| return { | |
| "action": "REPLAN", | |
| "tool": tool_name, | |
| "context": context, | |
| "message": f"Unrecognized error in {tool_name}, replanning required", | |
| "state": "PLANNING", | |
| } | |
| def should_abort(self, tool_name: str, max_failures: int = 3) -> bool: | |
| """Prüft ob wir ein Tool aufgeben sollten (zu viele Fehler)""" | |
| return self.failure_count.get(tool_name, 0) >= max_failures | |
| def get_recovery_stats(self) -> Dict[str, Any]: | |
| """Statistiken über Recovery-Aktionen""" | |
| return { | |
| "total_failures": sum(self.failure_count.values()), | |
| "failure_counts": self.failure_count.copy(), | |
| "recovery_history": self.recovery_history.copy(), | |
| "available_fallbacks": list(self.TOOL_FALLBACKS.keys()), | |
| } | |
| # Integration Helper für ReActAgent | |
| class ReActAgentWithRecovery: | |
| """ | |
| Beispiel-Integration in den Agent-Loop | |
| """ | |
| def __init__(self): | |
| self.state = AgentState.PLANNING | |
| self.history = [] | |
| self.recovery_engine = RecoveryEngine(agent=self) | |
| # self.tool_executor = ToolExecutor() # Würde hier initialisiert | |
| # self.llm = LLMClient() # Würde hier initialisiert | |
| def update_state(self, new_state: AgentState): | |
| """State-Transition durchführen""" | |
| old_state = self.state | |
| self.state = new_state | |
| logger.info(f"State: {old_state.value} -> {new_state.value}") | |
| def run_cycle(self, target: str, ai_decision: Dict[str, Any]) -> Dict[str, Any]: | |
| """ | |
| Ein Zyklus des Agent-Loops mit Recovery | |
| Args: | |
| target: Das Ziel-System | |
| ai_decision: JSON vom LLM (tool, params, expected_state, fallback_state, self_correction) | |
| """ | |
| tool_name = ai_decision.get("tool") | |
| params = ai_decision.get("params", {}) | |
| # 1. State: PLANNING -> EXECUTING | |
| self.update_state(AgentState.EXECUTING) | |
| # 2. Tool ausführen (simuliert) | |
| # result = self.tool_executor.execute(tool_name, params) | |
| # Für Demo: Simulieren wir verschiedene Ergebnisse | |
| result = self._simulate_tool_execution(tool_name, params) | |
| # 3. Prüfe auf Fehler | |
| if not result.get("success", False): | |
| # 🚨 Hier greift die RecoveryEngine! | |
| recovery_plan = self.recovery_engine.handle_failure( | |
| tool_name=tool_name, | |
| error_msg=result.get("stderr", "Unknown error"), | |
| ai_instructions=ai_decision, | |
| ) | |
| self.history.append( | |
| { | |
| "type": "recovery", | |
| "tool": tool_name, | |
| "action": recovery_plan, | |
| } | |
| ) | |
| return { | |
| "status": "recovered", | |
| "recovery_plan": recovery_plan, | |
| "state": self.state.value, | |
| } | |
| # 4. Erfolg: EXECUTING -> ANALYZING | |
| self.update_state(AgentState.ANALYZING) | |
| # 5. Ergebnisse parsen und verarbeiten | |
| findings = result.get("output", []) | |
| return { | |
| "status": "success", | |
| "findings": findings, | |
| "state": self.state.value, | |
| } | |
| def _simulate_tool_execution(self, tool_name: str, params: Dict) -> Dict: | |
| """Simuliert Tool-Ausführung für Demo-Zwecke""" | |
| # Dies würde in der echten Implementierung durch ToolExecutor ersetzt | |
| import random | |
| # 20% Fehler-Wahrscheinlichkeit für Demo | |
| if random.random() < 0.2: | |
| errors = [ | |
| {"success": False, "stderr": "command not found: gobuster"}, | |
| {"success": False, "stderr": "connection timeout after 30s"}, | |
| {"success": False, "stderr": "permission denied"}, | |
| ] | |
| return random.choice(errors) | |
| return {"success": True, "output": [f"Result from {tool_name}"]} | |
| if __name__ == "__main__": | |
| # Demo | |
| engine = RecoveryEngine() | |
| # Simuliere: Gobuster nicht gefunden | |
| result = engine.handle_failure( | |
| tool_name="gobuster", | |
| error_msg="command not found: gobuster", | |
| ai_instructions={ | |
| "fallback_state": "RECOVERY", | |
| "self_correction": "Try alternative directory scanner", | |
| }, | |
| ) | |
| print(f"Recovery Action: {result}") | |
| print(f"Stats: {engine.get_recovery_stats()}") | |
Xet Storage Details
- Size:
- 10.7 kB
- Xet hash:
- 878204b7e48d41d1f9f596c133d6110ec14478afa1e916863e3c1e84b00ac329
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.