| """ |
| Orchestrator – Main controller for RRA v2.0. |
| |
| Responsibilities: |
| - Interpret structured RRA JSON ("phase", "action_type", etc.). |
| - Route to Omnisearch, TerminalAdapter, UniversalInstaller, HermesMemory. |
| - Implement retries, timeouts, and error handling. |
| - Build all real commands from templates or stored metadata – the LLM never |
| directly controls shell strings unless explicitly allowed via config. |
| |
| This file assumes: |
| - The model outputs <RRA>{...}</RRA> with a strict JSON schema. |
| - Tool messages in the dataset mirror the real outputs from these methods. |
| """ |
|
|
| import asyncio |
| import json |
| import logging |
| from typing import Any, Dict, Optional |
|
|
| from core.omnisearch import Omnisearch |
| from core.vision import VisionProcessor |
| from core.terminal import TerminalAdapter |
| from core.universal_installer import UniversalInstaller |
| from core.hermes_memory import HermesMemory |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| class Orchestrator: |
| def __init__( |
| self, |
| allow_llm_raw_terminal: bool = False, |
| ) -> None: |
| """ |
| :param allow_llm_raw_terminal: |
| If True, the orchestrator may expose a "terminal_raw" action_type |
| that forwards commands directly from RRA JSON to TerminalAdapter. |
| This is unsafe by default and should only be used when the operator |
| explicitly wants that behavior. |
| """ |
| self.omnisearch = Omnisearch() |
| self.vision = VisionProcessor() |
| self.terminal_cache: Dict[str, TerminalAdapter] = {} |
| self.installer = UniversalInstaller() |
| self.memory = HermesMemory() |
| self.allow_llm_raw_terminal = allow_llm_raw_terminal |
|
|
| |
| |
| |
|
|
| async def execute_tool( |
| self, |
| tool_name: str, |
| args: Dict[str, Any], |
| retries: int = 3, |
| timeout: int = 120, |
| ) -> Any: |
| """ |
| Generic tool execution wrapper with retries and timeouts. |
| """ |
| for attempt in range(retries): |
| try: |
| result = await asyncio.wait_for( |
| self._execute_tool_internal(tool_name, args), |
| timeout=timeout, |
| ) |
| return result |
| except asyncio.TimeoutError: |
| logger.warning(f"Tool {tool_name} attempt {attempt + 1} timed out") |
| error = {"status": "error", "reason": "timeout"} |
| except Exception as e: |
| logger.warning(f"Tool {tool_name} attempt {attempt + 1} failed: {e}") |
| error = {"status": "error", "reason": str(e)} |
| await asyncio.sleep(2 * (attempt + 1)) |
| return error |
|
|
| async def _execute_tool_internal(self, tool_name: str, args: Dict[str, Any]) -> Any: |
| """ |
| All actual tool calls are implemented here. |
| """ |
| if tool_name == "Omnisearch": |
| |
| results = await self.omnisearch.query(**args) |
| return {"status": "success", "results": results} |
|
|
| elif tool_name == "Vision": |
| |
| mode = args.pop("mode") |
| method = getattr(self.vision, mode) |
| if asyncio.iscoroutinefunction(method): |
| out = await method(**args) |
| else: |
| out = method(**args) |
| return {"status": "success", "result": out} |
|
|
| elif tool_name == "Terminal": |
| |
| target = args["target"] |
| command = args["command"] |
| adapter = self._get_or_create_terminal(target) |
| result = adapter.execute(command) |
| result.setdefault("status", "success" if result.get("exit_code", 1) == 0 else "error") |
| return result |
|
|
| elif tool_name == "UniversalInstaller": |
| |
| self.installer.set_target(args["target"]) |
| out = self.installer.install(args["tool"], args.get("method", "auto")) |
| |
| if isinstance(out, str): |
| return {"status": "success", "detail": out} |
| return out |
|
|
| elif tool_name == "HermesMemory": |
| |
| method_name = args.pop("method") |
| meth = getattr(self.memory, method_name) |
| if asyncio.iscoroutinefunction(meth): |
| return await meth(**args) |
| else: |
| return meth(**args) |
|
|
| else: |
| logger.error(f"Unknown tool: {tool_name}") |
| return {"status": "error", "reason": f"Unknown tool: {tool_name}"} |
|
|
| def _get_or_create_terminal(self, target: Dict[str, Any]) -> TerminalAdapter: |
| """ |
| Cache TerminalAdapter per target key (e.g., IP + OS) to avoid reconnecting |
| every time. |
| """ |
| key = f"{target.get('ip')}|{target.get('os','linux')}" |
| if key not in self.terminal_cache: |
| self.terminal_cache[key] = TerminalAdapter(target) |
| return self.terminal_cache[key] |
|
|
| |
| |
| |
|
|
| async def handle_rra(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| """ |
| Main entry for interpreting a single RRA JSON object (already parsed |
| from <RRA>...</RRA>). |
| |
| Returns a dict that should be serialized into a tool message and fed |
| back to the LLM. |
| """ |
| phase = rra_obj.get("phase") |
| if phase == "plan": |
| |
| |
| return await self._handle_plan(rra_obj) |
| elif phase == "action": |
| return await self._handle_action(rra_obj) |
| elif phase == "cache": |
| return await self._handle_cache(rra_obj) |
| else: |
| return {"status": "error", "reason": f"Unknown phase: {phase}"} |
|
|
| async def _handle_plan(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| """ |
| Optionally consult HermesMemory on the plan (e.g., see if we've |
| exploited similar targets before). This is a hook – you can expand it. |
| """ |
| |
| |
| return {"status": "ok", "message": "plan_received"} |
|
|
| async def _handle_action(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| action_type = rra_obj.get("action_type") |
|
|
| if action_type == "search_exploit": |
| query = rra_obj.get("query", "") |
| engines = rra_obj.get("engines") |
| max_results = rra_obj.get("max_results", 10) |
| return await self.execute_tool( |
| "Omnisearch", |
| {"query": query, "engines": engines, "max_results": max_results}, |
| ) |
|
|
| if action_type == "install_dependency": |
| target = rra_obj.get("target_info") or rra_obj.get("target") |
| tool_name = rra_obj.get("tool_name") or rra_obj.get("package_name") |
| method = rra_obj.get("method", "auto") |
| return await self.execute_tool( |
| "UniversalInstaller", |
| {"target": target, "tool": tool_name, "method": method}, |
| ) |
|
|
| if action_type == "run_tool": |
| return await self._handle_run_tool(rra_obj) |
|
|
| if action_type == "terminal": |
| return await self._handle_terminal(rra_obj) |
|
|
| if action_type == "terminal_raw": |
| |
| if not self.allow_llm_raw_terminal: |
| return { |
| "status": "error", |
| "reason": "terminal_raw not allowed in this configuration", |
| } |
| return await self._handle_terminal_raw(rra_obj) |
|
|
| return {"status": "error", "reason": f"Unknown action_type: {action_type}"} |
|
|
| async def _handle_run_tool(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| """ |
| Run a known exploit/tool stored in HermesMemory's arsenal. |
| |
| rra_obj should contain: |
| - tool_key: logical key for the exploit/tool |
| - run_context: "target" or "local" |
| - target: target info dict if run_context == "target" |
| - arguments: dict of arguments to fill into templates |
| """ |
| tool_key = rra_obj.get("tool_key") |
| run_context = rra_obj.get("run_context", "target") |
| target = rra_obj.get("target") |
| arguments = rra_obj.get("arguments", {}) |
|
|
| raw = self.memory.get_arsenal_tool_raw(tool_key) |
| if not raw: |
| return { |
| "status": "error", |
| "reason": f"Tool {tool_key} not found in arsenal", |
| } |
|
|
| |
| |
| import ast |
|
|
| try: |
| meta = ast.literal_eval(raw) |
| except Exception as e: |
| return {"status": "error", "reason": f"Invalid arsenal metadata: {e}"} |
|
|
| path = meta.get("path") |
| if not path: |
| return { |
| "status": "error", |
| "reason": f"Arsenal entry {tool_key} missing 'path'", |
| } |
|
|
| |
| |
| cmd = self._build_exploit_command(path, arguments) |
|
|
| if run_context == "target": |
| return await self.execute_tool( |
| "Terminal", |
| {"target": target, "command": cmd}, |
| ) |
| else: |
| |
| local_target = {"os": "local"} |
| return await self.execute_tool( |
| "Terminal", |
| {"target": local_target, "command": cmd}, |
| ) |
|
|
| def _build_exploit_command(self, path: str, arguments: Dict[str, Any]) -> str: |
| """ |
| Minimal example: assume most exploits are python scripts with args |
| like --url and --cmd. In your real system, you should derive this |
| from stored metadata per tool_key, not hardcode here. |
| """ |
| parts = ["python3", path] |
| for k, v in arguments.items(): |
| |
| parts.append(f"--{k}") |
| parts.append(str(v)) |
| return " ".join(parts) |
|
|
| async def _handle_terminal(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| """ |
| Safe terminal action: use operation/command_name/templates, not raw shell. |
| """ |
| target = rra_obj.get("target") |
| os_hint = rra_obj.get("os_hint", "linux") |
| operation = rra_obj.get("operation") |
| command_name = rra_obj.get("command_name") |
| params = rra_obj.get("parameters", {}) |
|
|
| cmd = self._build_terminal_command( |
| os_hint=os_hint, |
| operation=operation, |
| command_name=command_name, |
| params=params, |
| ) |
| return await self.execute_tool("Terminal", {"target": target, "command": cmd}) |
|
|
| def _build_terminal_command( |
| self, |
| os_hint: str, |
| operation: str, |
| command_name: Optional[str], |
| params: Dict[str, Any], |
| ) -> str: |
| """ |
| Map (operation, command_name, params) to actual shell command. |
| |
| This is where you define your "terminal templates". For now, examples: |
| - basic_enum + whoami/id => simple commands |
| - file_read => cat/path |
| """ |
| |
| if operation == "basic_enum": |
| if os_hint.lower().startswith("win"): |
| |
| if command_name == "whoami": |
| return "whoami" |
| if command_name == "hostname": |
| return "hostname" |
| if command_name == "id": |
| return "whoami /all" |
| return "whoami" |
| else: |
| |
| if command_name == "whoami": |
| return "whoami" |
| if command_name == "id": |
| return "id" |
| if command_name == "hostname": |
| return "hostname" |
| return "whoami" |
|
|
| if operation == "file_read": |
| path = params.get("path", "/etc/passwd") |
| if os_hint.lower().startswith("win"): |
| return f"type {path}" |
| else: |
| return f"cat {path}" |
|
|
| |
| |
|
|
| |
| return command_name or "whoami" |
|
|
| async def _handle_terminal_raw(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| """ |
| Unsafe raw terminal: directly execute the 'command' field. |
| Only enabled if allow_llm_raw_terminal=True. |
| """ |
| target = rra_obj.get("target") |
| cmd = rra_obj.get("command", "") |
| return await self.execute_tool("Terminal", {"target": target, "command": cmd}) |
|
|
| async def _handle_cache(self, rra_obj: Dict[str, Any]) -> Dict[str, Any]: |
| """ |
| Cache phase: store arsenal tools / exploit relations via HermesMemory. |
| """ |
| cache_type = rra_obj.get("cache_type") |
|
|
| if cache_type == "arsenal_tool": |
| tool_key = rra_obj.get("tool_key") |
| path = rra_obj.get("path") |
| sha256 = rra_obj.get("sha256", "") |
| tags = rra_obj.get("tags", []) |
| target_os = rra_obj.get("target_os", "unknown") |
| service = rra_obj.get("service", "unknown") |
| metadata = { |
| "tags": tags, |
| "target_os": target_os, |
| "service": service, |
| } |
| self.memory.store_arsenal_tool( |
| tool_key=tool_key, |
| path=path, |
| sha256=sha256, |
| metadata=metadata, |
| ) |
| return {"status": "success", "message": "arsenal_tool_stored"} |
|
|
| if cache_type == "exploit_success": |
| cve = rra_obj.get("cve") |
| service = rra_obj.get("service", "unknown") |
| target_os = rra_obj.get("target_os", "unknown") |
| tool_key = rra_obj.get("tool_key") |
| self.memory.record_exploit_success( |
| cve=cve, |
| service=service, |
| target_os=target_os, |
| tool_key=tool_key, |
| ) |
| return {"status": "success", "message": "exploit_success_recorded"} |
|
|
| return {"status": "error", "reason": f"Unknown cache_type: {cache_type}"} |
|
|