File size: 10,366 Bytes
f70e563
c9aae52
 
 
 
 
 
 
 
 
f70e563
c9aae52
a0d47e6
c9aae52
 
 
 
 
a0d47e6
f70e563
c9aae52
f70e563
c9aae52
 
 
 
 
 
 
 
 
 
 
 
 
 
a0d47e6
c9aae52
f70e563
c9aae52
 
 
f70e563
c9aae52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70e563
c9aae52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0d47e6
 
 
c9aae52
 
 
a0d47e6
 
 
c9aae52
a0d47e6
c9aae52
a0d47e6
c9aae52
a0d47e6
c9aae52
a0d47e6
c9aae52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0d47e6
c9aae52
a0d47e6
c9aae52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70e563
c9aae52
 
 
 
a0d47e6
c9aae52
 
 
 
 
 
 
f70e563
c9aae52
 
f70e563
c9aae52
 
 
 
 
 
 
f70e563
c9aae52
 
f70e563
c9aae52
 
 
 
 
 
 
f70e563
c9aae52
 
f70e563
c9aae52
 
 
 
 
 
 
f70e563
c9aae52
 
 
f70e563
c9aae52
 
 
 
 
 
 
f70e563
c9aae52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""
UniversalInstaller – OS-aware tool installation with retry and dependency check.

This module is called by the Orchestrator, not directly by the LLM.

Responsibilities:
- Detect remote OS via TerminalAdapter.
- Select appropriate package manager (apt, yum, choco, brew, adb) or fallback.
- Run real installation commands on the target.
- Return normalized, structured results for logging and for the LLM to react to.
"""

import logging
import re
from typing import Dict, Any

from core.terminal import TerminalAdapter

logger = logging.getLogger(__name__)


class UniversalInstaller:
    def __init__(
        self,
        retries: int = 2,
        strict_tool_names: bool = True,
    ) -> None:
        """
        :param retries: number of installation retries per request.
        :param strict_tool_names:
            If True, tool_name/package_name will be validated with a simple regex
            to avoid obviously dangerous strings. Set to False if you trust the
            caller and want full freedom.
        """
        self.target: Dict[str, Any] = {}
        self.terminal: TerminalAdapter = None  # type: ignore
        self.retries = retries
        self.strict_tool_names = strict_tool_names

    # -------------------------------------------------------------------------
    # Setup
    # -------------------------------------------------------------------------

    def set_target(self, target: Dict[str, Any]) -> None:
        """
        Set the target information (ip, os, creds, port, etc.) and create a
        corresponding TerminalAdapter.
        """
        self.target = target or {}
        self.terminal = TerminalAdapter(self.target)

    # -------------------------------------------------------------------------
    # Public API
    # -------------------------------------------------------------------------

    def install(self, tool_name: str, method: str = "auto") -> Dict[str, Any]:
        """
        Install a tool on the configured target.

        :param tool_name: logical package or tool name, e.g. "nmap", "python3".
        :param method: "auto" (detect OS) or explicit ("apt", "yum", "choco",
                       "brew", "adb").
        :return: structured result dict, e.g.:
                 {
                    "status": "success" | "error",
                    "method": "apt",
                    "tool": "nmap",
                    "stdout": "...",
                    "stderr": "..."
                 }
        """
        if self.strict_tool_names and not self._is_safe_tool_name(tool_name):
            msg = f"Rejected tool_name '{tool_name}' due to strict_tool_names policy"
            logger.warning(f"UniversalInstaller: {msg}")
            return {
                "status": "error",
                "tool": tool_name,
                "method": method,
                "stdout": "",
                "stderr": msg,
            }

        last_error: Dict[str, Any] = {}
        for attempt in range(self.retries):
            try:
                os_type = self._detect_os()
                logger.debug(
                    f"UniversalInstaller: detected OS '{os_type}', attempt {attempt + 1}"
                )
                if method == "auto":
                    if os_type == "linux_debian":
                        return self._apt_install(tool_name)
                    if os_type == "linux_rhel":
                        return self._yum_install(tool_name)
                    if os_type == "windows":
                        return self._choco_install(tool_name)
                    if os_type == "macos":
                        return self._brew_install(tool_name)
                    if os_type == "android":
                        return self._adb_install(tool_name)

                    # Unknown OS: generic GitHub download fallback
                    return self._github_download(tool_name)

                # Explicit method requested
                if method == "apt":
                    return self._apt_install(tool_name)
                if method == "yum":
                    return self._yum_install(tool_name)
                if method == "choco":
                    return self._choco_install(tool_name)
                if method == "brew":
                    return self._brew_install(tool_name)
                if method == "adb":
                    return self._adb_install(tool_name)

                # Fallback if method is unrecognized
                return self._github_download(tool_name)

            except Exception as e:
                logger.warning(f"UniversalInstaller: install attempt {attempt + 1} failed: {e}")
                last_error = {
                    "status": "error",
                    "tool": tool_name,
                    "method": method,
                    "stdout": "",
                    "stderr": str(e),
                }

        if not last_error:
            # Shouldn't happen, but just in case
            last_error = {
                "status": "error",
                "tool": tool_name,
                "method": method,
                "stdout": "",
                "stderr": f"Installation failed after {self.retries} attempts",
            }

        return last_error

    # -------------------------------------------------------------------------
    # Internal helpers
    # -------------------------------------------------------------------------

    def _is_safe_tool_name(self, tool: str) -> bool:
        """
        Very simple tool/package name validation:
        - letters, digits, underscores, dashes, dots
        - no spaces or shell metacharacters.

        This is not about "security" in a strong sense; it's about avoiding
        accidental shell injection when building commands like "apt install X".
        """
        return bool(re.fullmatch(r"[A-Za-z0-9._-]+", tool))

    def _detect_os(self) -> str:
        """
        Detect remote OS by trying common commands. Returns a normalized OS type:
        - "linux_debian"
        - "linux_rhel"
        - "windows"
        - "macos"
        - "android"
        - "unknown"
        """
        cmd = (
            "cat /etc/os-release 2>/dev/null || "
            "systeminfo 2>/dev/null || "
            "sw_vers 2>/dev/null || "
            "getprop ro.build.version.release 2>/dev/null"
        )
        result = self.terminal.execute(cmd)
        stdout = (result.get("stdout") or "").lower()

        if "ubuntu" in stdout or "debian" in stdout:
            return "linux_debian"
        if "rhel" in stdout or "centos" in stdout or "red hat" in stdout:
            return "linux_rhel"
        if "windows" in stdout:
            return "windows"
        if "macos" in stdout or "darwin" in stdout or "os x" in stdout:
            return "macos"
        if "android" in stdout:
            return "android"

        logger.debug(f"UniversalInstaller: unknown OS from detect_os output: {stdout[:200]}")
        return "unknown"

    # -------------------------------------------------------------------------
    # Per-method installers
    # -------------------------------------------------------------------------

    def _apt_install(self, tool: str) -> Dict[str, Any]:
        logger.info(f"UniversalInstaller: installing '{tool}' via apt")
        # Update package lists (ignore errors)
        self.terminal.execute("sudo apt update -y || apt update -y")
        result = self.terminal.execute(f"sudo apt install -y {tool}")
        return {
            "status": "success" if result.get("exit_code", 1) == 0 else "error",
            "method": "apt",
            "tool": tool,
            "stdout": result.get("stdout", ""),
            "stderr": result.get("stderr", ""),
        }

    def _yum_install(self, tool: str) -> Dict[str, Any]:
        logger.info(f"UniversalInstaller: installing '{tool}' via yum")
        result = self.terminal.execute(f"sudo yum install -y {tool}")
        return {
            "status": "success" if result.get("exit_code", 1) == 0 else "error",
            "method": "yum",
            "tool": tool,
            "stdout": result.get("stdout", ""),
            "stderr": result.get("stderr", ""),
        }

    def _choco_install(self, tool: str) -> Dict[str, Any]:
        logger.info(f"UniversalInstaller: installing '{tool}' via choco")
        result = self.terminal.execute(f"choco install {tool} -y")
        return {
            "status": "success" if result.get("exit_code", 1) == 0 else "error",
            "method": "choco",
            "tool": tool,
            "stdout": result.get("stdout", ""),
            "stderr": result.get("stderr", ""),
        }

    def _brew_install(self, tool: str) -> Dict[str, Any]:
        logger.info(f"UniversalInstaller: installing '{tool}' via brew")
        result = self.terminal.execute(f"brew install {tool}")
        return {
            "status": "success" if result.get("exit_code", 1) == 0 else "error",
            "method": "brew",
            "tool": tool,
            "stdout": result.get("stdout", ""),
            "stderr": result.get("stderr", ""),
        }

    def _adb_install(self, tool: str) -> Dict[str, Any]:
        logger.info(f"UniversalInstaller: installing '{tool}' via adb")
        # Assuming "tool" refers to an APK base name
        result = self.terminal.execute(f"adb install {tool}.apk")
        return {
            "status": "success" if result.get("exit_code", 1) == 0 else "error",
            "method": "adb",
            "tool": tool,
            "stdout": result.get("stdout", ""),
            "stderr": result.get("stderr", ""),
        }

    def _github_download(self, tool: str) -> Dict[str, Any]:
        """
        Generic fallback: placeholder for "download binary from GitHub" logic.
        In a full implementation, you would:
        - Use Omnisearch or a known URL to fetch a release.
        - Save it to disk, mark it executable, and maybe add to PATH.
        """
        logger.info(f"UniversalInstaller: using generic GitHub download for '{tool}'")
        # You can expand this with real download logic.
        detail = f"Downloaded {tool} from GitHub (generic fallback)"
        return {
            "status": "success",
            "method": "github_fallback",
            "tool": tool,
            "stdout": detail,
            "stderr": "",
        }