Repository navigation
Expand file tree
/
Copy pathgui_hacker.py
More file actions
700 lines (614 loc) · 32.6 KB
/
Copy pathgui_hacker.py
File metadata and controls
700 lines (614 loc) · 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
"""
AI Pentest Agent - Hacker Terminal GUI
A full-screen terminal-style interface with animations, matrix effects,
real-time output, and full system access.
"""
import tkinter as tk
from tkinter import font as tkfont
import threading
import queue
import time
import os
import sys
import subprocess
import shutil
import json
import random
from pathlib import Path
from datetime import datetime
sys.path.insert(0, str(Path(__file__).parent.parent))
from agents.red_team import RedTeamAgent, CampaignResult
from modules.scanner import PortScanner
from modules.web_recon import WebRecon
from modules.vuln_scanner import VulnScanner
from core.tools import ToolManager, TOOLS
from core.memory import Memory
from core.llm import LLMClient, LLMConfig
# ── Color scheme ──────────────────────────────────────────────────────────────
C = {
"bg": "#0a0a0a",
"bg2": "#0d1117",
"fg": "#00ff41", # matrix green
"fg_dim": "#008f11",
"fg_bright": "#39ff14",
"red": "#ff0040",
"yellow": "#ffff00",
"cyan": "#00ffff",
"blue": "#0080ff",
"purple": "#ff00ff",
"orange": "#ff8000",
"white": "#e0e0e0",
"gray": "#404040",
"border": "#1a1a2e",
"header": "#0f3460",
}
class MatrixRain(tk.Canvas):
"""Matrix-style falling characters background."""
def __init__(self, parent, width=800, height=600, **kwargs):
super().__init__(parent, width=width, height=height,
bg=C["bg"], highlightthickness=0, **kwargs)
self.width = width
self.height = height
self.drops = []
self.chars = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン0123456789ABCDEF"
self.font = ("Consolas", 10)
self._init_drops()
self._animate()
def _init_drops(self):
num_drops = self.width // 12
for i in range(num_drops):
x = i * 12
y = random.randint(-self.height, 0)
speed = random.randint(2, 8)
length = random.randint(5, 20)
self.drops.append({"x": x, "y": y, "speed": speed, "length": length})
def _animate(self):
self.delete("all")
for drop in self.drops:
for j in range(drop["length"]):
char_y = drop["y"] - j * 12
if 0 <= char_y <= self.height:
alpha = max(0, 1 - j / drop["length"])
if alpha > 0.7:
color = C["fg_bright"]
elif alpha > 0.4:
color = C["fg"]
else:
color = C["fg_dim"]
char = random.choice(self.chars)
self.create_text(drop["x"], char_y, text=char,
fill=color, font=self.font)
drop["y"] += drop["speed"]
if drop["y"] - drop["length"] * 12 > self.height:
drop["y"] = random.randint(-200, 0)
drop["speed"] = random.randint(2, 8)
self.after(50, self._animate)
class TerminalText(tk.Text):
"""Terminal-style text widget with auto-scroll and colored output."""
def __init__(self, parent, **kwargs):
super().__init__(parent, bg=C["bg"], fg=C["fg"],
insertbackground=C["fg"], font=("Consolas", 10),
relief=tk.FLAT, wrap=tk.WORD, state=tk.DISABLED,
cursor="xterm", **kwargs)
self._setup_tags()
def _setup_tags(self):
self.tag_config("timestamp", foreground=C["gray"])
self.tag_config("info", foreground=C["cyan"])
self.tag_config("success", foreground=C["fg_bright"])
self.tag_config("warning", foreground=C["yellow"])
self.tag_config("error", foreground=C["red"])
self.tag_config("critical", foreground=C["red"])
self.tag_config("prompt", foreground=C["fg_bright"])
self.tag_config("command", foreground=C["white"])
self.tag_config("output", foreground=C["fg"])
self.tag_config("phase", foreground=C["purple"])
self.tag_config("finding", foreground=C["orange"])
self.tag_config("tool", foreground=C["blue"])
self.tag_config("header", foreground=C["cyan"])
self.tag_config("banner", foreground=C["fg_bright"])
def write(self, text, tag="output"):
self.configure(state=tk.NORMAL)
self.insert(tk.END, text + "\n", tag)
self.see(tk.END)
self.configure(state=tk.DISABLED)
def write_raw(self, text, tag="output"):
self.configure(state=tk.NORMAL)
self.insert(tk.END, text, tag)
self.see(tk.END)
self.configure(state=tk.DISABLED)
def clear(self):
self.configure(state=tk.NORMAL)
self.delete("1.0", tk.END)
self.configure(state=tk.DISABLED)
class HackerGUI:
"""Main hacker terminal GUI."""
def __init__(self, root):
self.root = root
self.root.title("AI Pentest Agent v2.0 — [KERNEL ACCESS]")
self.root.geometry("1400x900")
self.root.configure(bg=C["bg"])
self.root.minsize(1000, 700)
self.campaign_running = False
self.ui_queue = queue.Queue()
self.command_history = []
self.history_idx = -1
self.memory = Memory()
self.tool_mgr = ToolManager()
self._build_ui()
self._poll_ui_queue()
self._show_banner()
self._check_llm()
def _build_ui(self):
# Main container
main = tk.Frame(self.root, bg=C["bg"])
main.pack(fill=tk.BOTH, expand=True)
# ── Header bar ──
header = tk.Frame(main, bg=C["header"], height=30)
header.pack(fill=tk.X)
header.pack_propagate(False)
tk.Label(header, text="◈ AI PENTEST AGENT v2.0", bg=C["header"],
fg=C["fg_bright"], font=("Consolas", 11, "bold")).pack(side=tk.LEFT, padx=10)
self.status_label = tk.Label(header, text="● READY", bg=C["header"],
fg=C["fg"], font=("Consolas", 9))
self.status_label.pack(side=tk.RIGHT, padx=10)
self.llm_label = tk.Label(header, text="LLM: checking...", bg=C["header"],
fg=C["gray"], font=("Consolas", 9))
self.llm_label.pack(side=tk.RIGHT, padx=10)
# ── Paned layout ──
paned = tk.PanedWindow(main, orient=tk.HORIZONTAL, bg=C["border"],
sashwidth=3)
paned.pack(fill=tk.BOTH, expand=True, padx=2, pady=2)
# ── Left panel ──
left = tk.Frame(paned, bg=C["bg2"], width=350)
paned.add(left, minsize=250)
# Target input
target_frame = tk.Frame(left, bg=C["bg2"])
target_frame.pack(fill=tk.X, padx=5, pady=5)
tk.Label(target_frame, text="TARGET:", bg=C["bg2"], fg=C["cyan"],
font=("Consolas", 9, "bold")).pack(side=tk.LEFT)
self.target_var = tk.StringVar(value="127.0.0.1")
target_entry = tk.Entry(target_frame, textvariable=self.target_var,
bg=C["bg"], fg=C["fg_bright"],
insertbackground=C["fg"],
font=("Consolas", 10), relief=tk.FLAT,
highlightbackground=C["border"],
highlightthickness=1)
target_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Mode selector
mode_frame = tk.Frame(left, bg=C["bg2"])
mode_frame.pack(fill=tk.X, padx=5, pady=2)
tk.Label(mode_frame, text="MODE:", bg=C["bg2"], fg=C["cyan"],
font=("Consolas", 9, "bold")).pack(side=tk.LEFT)
self.mode_var = tk.StringVar(value="full")
for mode in ["full", "scan", "webscan", "vulnscan", "shell"]:
tk.Radiobutton(mode_frame, text=mode, variable=self.mode_var,
value=mode, bg=C["bg2"], fg=C["fg"],
selectcolor=C["bg"], font=("Consolas", 8),
activebackground=C["bg2"], activeforeground=C["fg_bright"],
indicatoron=0, padx=5, pady=1,
relief=tk.FLAT, cursor="hand2").pack(side=tk.LEFT, padx=1)
# Action buttons
btn_frame = tk.Frame(left, bg=C["bg2"])
btn_frame.pack(fill=tk.X, padx=5, pady=5)
self.launch_btn = tk.Button(btn_frame, text="▶ LAUNCH", bg=C["fg"],
fg=C["bg"], font=("Consolas", 10, "bold"),
relief=tk.FLAT, cursor="hand2",
activebackground=C["fg_bright"],
command=self._launch)
self.launch_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
self.stop_btn = tk.Button(btn_frame, text="■ STOP", bg=C["red"],
fg=C["white"], font=("Consolas", 10, "bold"),
relief=tk.FLAT, cursor="hand2",
state=tk.DISABLED, command=self._stop)
self.stop_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
# Phase indicators
phase_frame = tk.LabelFrame(left, text=" PHASES ", bg=C["bg2"],
fg=C["cyan"], font=("Consolas", 9, "bold"),
relief=tk.FLAT, labelanchor="n")
phase_frame.pack(fill=tk.X, padx=5, pady=5)
self.phase_labels = {}
phases = [("recon", "RECON"), ("scan", "SCAN"), ("vuln", "VULN"),
("exploit", "EXPLOIT"), ("web", "WEB"), ("report", "REPORT")]
for key, label in phases:
row = tk.Frame(phase_frame, bg=C["bg2"])
row.pack(fill=tk.X, padx=5, pady=1)
dot = tk.Label(row, text="○", bg=C["bg2"], fg=C["gray"],
font=("Consolas", 10))
dot.pack(side=tk.LEFT)
lbl = tk.Label(row, text=label, bg=C["bg2"], fg=C["fg_dim"],
font=("Consolas", 9))
lbl.pack(side=tk.LEFT, padx=5)
status = tk.Label(row, text="idle", bg=C["bg2"], fg=C["gray"],
font=("Consolas", 8))
status.pack(side=tk.RIGHT)
self.phase_labels[key] = (dot, lbl, status)
# Stats
stats_frame = tk.LabelFrame(left, text=" STATS ", bg=C["bg2"],
fg=C["cyan"], font=("Consolas", 9, "bold"),
relief=tk.FLAT, labelanchor="n")
stats_frame.pack(fill=tk.X, padx=5, pady=5)
self.stats_labels = {}
for stat in ["Ports", "Findings", "Duration", "Risk"]:
row = tk.Frame(stats_frame, bg=C["bg2"])
row.pack(fill=tk.X, padx=5, pady=1)
tk.Label(row, text=f"{stat}:", bg=C["bg2"], fg=C["fg_dim"],
font=("Consolas", 9)).pack(side=tk.LEFT)
lbl = tk.Label(row, text="-", bg=C["bg2"], fg=C["fg"],
font=("Consolas", 9, "bold"))
lbl.pack(side=tk.RIGHT)
self.stats_labels[stat] = lbl
# Tools status button
tk.Button(left, text="⚙ TOOLS STATUS", bg=C["bg"], fg=C["cyan"],
font=("Consolas", 9), relief=tk.FLAT, cursor="hand2",
command=self._show_tools).pack(fill=tk.X, padx=5, pady=2)
# Memory button
tk.Button(left, text="◈ MEMORY", bg=C["bg"], fg=C["purple"],
font=("Consolas", 9), relief=tk.FLAT, cursor="hand2",
command=self._show_memory).pack(fill=tk.X, padx=5, pady=2)
# ── Right panel (terminal) ──
right = tk.Frame(paned, bg=C["bg"])
paned.add(right, minsize=500)
# Terminal output
self.terminal = TerminalText(right)
self.terminal.pack(fill=tk.BOTH, expand=True, padx=2, pady=2)
# Command input
input_frame = tk.Frame(right, bg=C["header"], height=30)
input_frame.pack(fill=tk.X, side=tk.BOTTOM)
input_frame.pack_propagate(False)
tk.Label(input_frame, text="❯", bg=C["header"], fg=C["fg_bright"],
font=("Consolas", 12, "bold")).pack(side=tk.LEFT, padx=5)
self.cmd_input = tk.Entry(input_frame, bg=C["header"], fg=C["fg_bright"],
insertbackground=C["fg_bright"],
font=("Consolas", 11), relief=tk.FLAT,
highlightthickness=0)
self.cmd_input.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
self.cmd_input.bind("<Return>", self._on_command)
self.cmd_input.bind("<Up>", self._history_up)
self.cmd_input.bind("<Down>", self._history_down)
def _show_banner(self):
banner = r"""
╔══════════════════════════════════════════════════════════════╗
║ █████╗ ██╗ ██████╗ ███████╗███╗ ██╗████████╗ ║
║ ██╔══██╗██║ ██╔══██╗██╔════╝████╗ ██║╚══██╔══╝ ║
║ ███████║██║ ██████╔╝█████╗ ██╔██╗ ██║ ██║ ║
║ ██╔══██║██║ ██╔══██╗██╔══╝ ██║╚██╗██║ ██║ ║
║ ██║ ██║██║ ██║ ██║███████╗██║ ╚████║ ██║ ║
║ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ║
║ ║
║ ██████╗ ███████╗███╗ ██╗████████╗███████╗██████╗ ║
║ ██╔════╝ ██╔════╝████╗ ██║╚══██╔══╝██╔════╝██╔══██╗ ║
║ ██║ █████╗ ██╔██╗ ██║ ██║ █████╗ ██████╔╝ ║
║ ██║ ██╔══╝ ██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗ ║
║ ╚██████╗ ███████╗██║ ╚████║ ██║ ███████╗██║ ██║ ║
║ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ║
║ ║
║ [ AI-POWERED PENETRATION TESTING ] ║
║ [ FULL SYSTEM ACCESS ENABLED ] ║
║ [ MULTI-PROVIDER LLM ENGINE ] ║
╚══════════════════════════════════════════════════════════════╝
"""
self.terminal.configure(state=tk.NORMAL)
for line in banner.split("\n"):
self.terminal.insert(tk.END, line + "\n", "banner")
self.terminal.configure(state=tk.DISABLED)
self.terminal.write("", "output")
self.terminal.write(" [*] System initialized. Type 'help' for commands.", "info")
self.terminal.write(" [*] Enter a target and click LAUNCH to begin assessment.", "info")
self.terminal.write("", "output")
def _check_llm(self):
config = LLMConfig.from_env()
client = LLMClient(config)
if client.is_available:
self.llm_label.configure(text=f"LLM: {config.provider}/{config.model}", fg=C["fg"])
else:
self.llm_label.configure(text="LLM: offline (heuristic mode)", fg=C["yellow"])
def _poll_ui_queue(self):
try:
while True:
task = self.ui_queue.get_nowait()
action = task.get("action")
if action == "log":
tag = task.get("tag", "output")
self.terminal.write(f"[{datetime.now().strftime('%H:%M:%S')}] {task['msg']}", tag)
elif action == "phase":
self._update_phase(task["phase"], task["status"])
elif action == "stat":
if task["key"] in self.stats_labels:
self.stats_labels[task["key"]].configure(text=task["value"])
elif action == "finished":
self._campaign_finished()
elif action == "error":
self.terminal.write(f" [ERROR] {task['msg']}", "error")
self._campaign_finished()
except queue.Empty:
pass
self.root.after(100, self._poll_ui_queue)
def _update_phase(self, phase, status):
key_map = {
"reconnaissance": "recon", "scanning": "scan",
"vulnerability_analysis": "vuln", "exploitation": "exploit",
"web_analysis": "web", "reporting": "report",
}
key = key_map.get(phase, phase)
if key in self.phase_labels:
dot, lbl, st = self.phase_labels[key]
colors = {"running": C["yellow"], "done": C["fg_bright"], "fail": C["red"], "idle": C["gray"]}
symbols = {"running": "◉", "done": "●", "fail": "✗", "idle": "○"}
dot.configure(text=symbols.get(status, "○"), fg=colors.get(status, C["gray"]))
st.configure(text=status, fg=colors.get(status, C["gray"]))
def _launch(self):
if self.campaign_running:
return
target = self.target_var.get().strip()
if not target:
self.terminal.write(" [!] No target specified", "warning")
return
self.campaign_running = True
self.launch_btn.configure(state=tk.DISABLED)
self.stop_btn.configure(state=tk.NORMAL)
self.status_label.configure(text="● RUNNING", fg=C["yellow"])
for key in self.phase_labels:
self._update_phase(key, "idle")
for stat in self.stats_labels:
self.stats_labels[stat].configure(text="-")
mode = self.mode_var.get()
config = {
"scan_workers": 50, "scan_timeout": 2.0,
"web_timeout": 5.0, "report_dir": "reports",
}
if mode == "shell":
self._open_shell()
return
self.terminal.write("", "output")
self.terminal.write(f" [>] Launching {mode} campaign against {target}...", "info")
thread = threading.Thread(target=self._run_campaign,
args=(target, mode, config), daemon=True)
thread.start()
def _run_campaign(self, target, mode, config):
try:
if mode == "scan":
self._run_scan(target, config)
elif mode == "webscan":
self._run_webscan(target, config)
elif mode == "vulnscan":
self._run_vulnscan(target, config)
else:
self._run_full(target, config)
except Exception as e:
self.ui_queue.put({"action": "error", "msg": str(e)})
finally:
self.ui_queue.put({"action": "finished"})
def _run_full(self, target, config):
def on_log(msg):
tag = "output"
if "error" in msg.lower() or "fail" in msg.lower():
tag = "error"
elif "found" in msg.lower() or "complete" in msg.lower():
tag = "success"
self.ui_queue.put({"action": "log", "msg": msg, "tag": tag})
def on_phase(phase, status, duration, data, errors):
self.ui_queue.put({"action": "phase", "phase": phase, "status": status})
if phase == "scanning" and data.get("ports"):
ports = [p for p in data["ports"] if p.get("state") == "open"]
self.ui_queue.put({"action": "stat", "key": "Ports", "value": str(len(ports))})
if phase == "vulnerability_analysis":
findings = data.get("cve_matches", []) + data.get("default_port_risks", [])
if findings:
self.ui_queue.put({"action": "stat", "key": "Findings", "value": str(len(findings))})
if phase == "reporting" and data.get("report_paths"):
for p in data["report_paths"].values():
self.ui_queue.put({"action": "log", "msg": f"Report: {p}", "tag": "success"})
agent = RedTeamAgent(target, config, on_phase_done=on_phase, on_log=on_log)
result = agent.run_campaign()
self.ui_queue.put({"action": "stat", "key": "Duration", "value": f"{result.total_duration:.1f}s"})
max_sev = "INFO"
for f in result.findings:
sev = f.split("]")[0].strip("[").upper() if "[" in f else "INFO"
if sev in ("CRITICAL", "HIGH"):
max_sev = sev
break
if sev == "MEDIUM":
max_sev = "MEDIUM"
self.ui_queue.put({"action": "stat", "key": "Risk", "value": max_sev})
def _run_scan(self, target, config):
self.ui_queue.put({"action": "phase", "phase": "scanning", "status": "running"})
self.ui_queue.put({"action": "log", "msg": f"Scanning {target}...", "tag": "info"})
scanner = PortScanner(max_workers=config["scan_workers"], timeout=config["scan_timeout"])
result = scanner.scan(target)
open_ports = [p for p in result.ports if p.state == "open"]
self.ui_queue.put({"action": "stat", "key": "Ports", "value": str(len(open_ports))})
for p in open_ports:
self.ui_queue.put({"action": "log", "msg": f" {p.port}/{p.protocol} {p.service} {p.banner or ''}", "tag": "success"})
self.ui_queue.put({"action": "phase", "phase": "scanning", "status": "done"})
def _run_webscan(self, target, config):
self.ui_queue.put({"action": "phase", "phase": "web_analysis", "status": "running"})
import asyncio
wr = WebRecon(timeout=config.get("web_timeout", 5.0))
loop = asyncio.new_event_loop()
result = loop.run_until_complete(wr.scan(target, deep=True))
loop.close()
data = result.to_dict()
for f in data.get("findings", []):
self.ui_queue.put({"action": "log", "msg": f" [{f['severity']}] {f['title']}", "tag": "finding"})
self.ui_queue.put({"action": "stat", "key": "Findings", "value": str(len(data.get("findings", [])))})
self.ui_queue.put({"action": "phase", "phase": "web_analysis", "status": "done"})
def _run_vulnscan(self, target, config):
self.ui_queue.put({"action": "phase", "phase": "vulnerability_analysis", "status": "running"})
scanner = PortScanner(max_workers=config["scan_workers"], timeout=config["scan_timeout"])
scan_result = scanner.scan(target)
open_ports = [p for p in scan_result.ports if p.state == "open"]
vs = VulnScanner()
findings = vs.match_cves(open_ports) + vs.check_default_ports(open_ports)
for f in findings:
d = f.to_dict()
self.ui_queue.put({"action": "log", "msg": f" [{d['severity']}] {d['description']}", "tag": "finding"})
self.ui_queue.put({"action": "stat", "key": "Findings", "value": str(len(findings))})
self.ui_queue.put({"action": "phase", "phase": "vulnerability_analysis", "status": "done"})
def _open_shell(self):
self.campaign_running = False
self.status_label.configure(text="● SHELL", fg=C["cyan"])
self.terminal.write("", "output")
self.terminal.write(" [>] Interactive shell mode. Type commands below.", "info")
self.terminal.write(" [>] Type 'exit' to return to campaign mode.", "info")
self.cmd_input.focus_set()
def _campaign_finished(self):
self.campaign_running = False
self.launch_btn.configure(state=tk.NORMAL)
self.stop_btn.configure(state=tk.DISABLED)
self.status_label.configure(text="● READY", fg=C["fg"])
def _stop(self):
self.campaign_running = False
self.ui_queue.put({"action": "log", "msg": "Campaign stopped by user", "tag": "warning"})
self._campaign_finished()
def _on_command(self, event):
cmd = self.cmd_input.get().strip()
self.cmd_input.delete(0, tk.END)
if not cmd:
return
self.command_history.append(cmd)
self.history_idx = len(self.command_history)
self.terminal.write(f" ❯ {cmd}", "command")
if cmd == "exit":
self._campaign_finished()
return
if cmd == "help":
self._show_help()
return
if cmd == "clear":
self.terminal.clear()
return
if cmd == "tools":
self._show_tools()
return
if cmd == "memory":
self._show_memory()
return
if cmd == "status":
self._show_status()
return
if cmd.startswith("install "):
tool = cmd.split(" ", 1)[1]
self._install_tool(tool)
return
if cmd.startswith("scan "):
target = cmd.split(" ", 1)[1]
self.target_var.set(target)
self.mode_var.set("scan")
self._launch()
return
if cmd.startswith("attack "):
target = cmd.split(" ", 1)[1]
self.target_var.set(target)
self.mode_var.set("full")
self._launch()
return
# Execute as system command
self._execute_shell(cmd)
def _execute_shell(self, cmd):
def run():
try:
result = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=60,
creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0
)
if result.stdout:
for line in result.stdout.splitlines()[:50]:
self.ui_queue.put({"action": "log", "msg": f" {line}", "tag": "output"})
if result.stderr:
for line in result.stderr.splitlines()[:20]:
self.ui_queue.put({"action": "log", "msg": f" {line}", "tag": "error"})
if result.returncode != 0:
self.ui_queue.put({"action": "log", "msg": f" [exit code: {result.returncode}]", "tag": "warning"})
except subprocess.TimeoutExpired:
self.ui_queue.put({"action": "log", "msg": " Command timed out", "tag": "error"})
except Exception as e:
self.ui_queue.put({"action": "log", "msg": f" Error: {e}", "tag": "error"})
threading.Thread(target=run, daemon=True).start()
def _show_help(self):
help_text = [
" ┌─────────────────────────────────────────────────────────┐",
" │ COMMAND REFERENCE │",
" ├─────────────────────────────────────────────────────────┤",
" │ scan <target> Quick port scan │",
" │ attack <target> Full campaign │",
" │ install <tool> Install a pentesting tool │",
" │ tools Show tool status │",
" │ memory Show memory stats │",
" │ status Show agent status │",
" │ clear Clear terminal │",
" │ help Show this help │",
" │ exit Exit shell mode │",
" │ <any shell cmd> Execute system command │",
" └─────────────────────────────────────────────────────────┘",
]
for line in help_text:
self.terminal.write(line, "info")
def _show_tools(self):
status = self.tool_mgr.check_all_tools()
self.terminal.write("", "output")
self.terminal.write(" ┌──────────────── TOOLS STATUS ─────────────────┐", "header")
for name, s in status.items():
icon = "●" if s.installed else "○"
color = "success" if s.installed else "error"
detail = s.version[:40] if s.version else s.path or "not installed"
self.terminal.write(f" │ {icon} {s.display:12s} {detail}", color)
self.terminal.write(" └───────────────────────────────────────────────┘", "header")
self.terminal.write(" Use 'install <name>' to install a tool", "info")
def _show_memory(self):
stats = self.memory.get_stats()
self.terminal.write("", "output")
self.terminal.write(" ┌──────────────── MEMORY ──────────────────────┐", "header")
self.terminal.write(f" │ Entries: {stats['memory_entries']}", "output")
self.terminal.write(f" │ Sessions: {stats['sessions']}", "output")
self.terminal.write(f" │ Patterns: {stats['patterns']}", "output")
for cat, cnt in stats.get("categories", {}).items():
self.terminal.write(f" │ {cat}: {cnt}", "output")
self.terminal.write(" └─────────────────────────────────────────────┘", "header")
def _show_status(self):
config = LLMConfig.from_env()
self.terminal.write("", "output")
self.terminal.write(" ┌──────────────── AGENT STATUS ────────────────┐", "header")
self.terminal.write(f" │ LLM Provider: {config.provider}", "output")
self.terminal.write(f" │ LLM Model: {config.model}", "output")
self.terminal.write(f" │ LLM Enabled: {config.enabled}", "output")
self.terminal.write(f" │ Campaign: {'running' if self.campaign_running else 'idle'}", "output")
self.terminal.write(" └─────────────────────────────────────────────┘", "header")
def _install_tool(self, tool_name):
def run():
self.ui_queue.put({"action": "log", "msg": f"Installing {tool_name}...", "tag": "info"})
success = self.tool_mgr.install_tool(tool_name)
if success:
self.ui_queue.put({"action": "log", "msg": f"{tool_name} installed successfully", "tag": "success"})
else:
self.ui_queue.put({"action": "log", "msg": f"Failed to install {tool_name}", "tag": "error"})
threading.Thread(target=run, daemon=True).start()
def _history_up(self, event):
if self.command_history and self.history_idx > 0:
self.history_idx -= 1
self.cmd_input.delete(0, tk.END)
self.cmd_input.insert(0, self.command_history[self.history_idx])
def _history_down(self, event):
if self.history_idx < len(self.command_history) - 1:
self.history_idx += 1
self.cmd_input.delete(0, tk.END)
self.cmd_input.insert(0, self.command_history[self.history_idx])
else:
self.history_idx = len(self.command_history)
self.cmd_input.delete(0, tk.END)
def main():
root = tk.Tk()
try:
from ctypes import windll
root.update()
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
hwnd = windll.user32.GetParent(root.winfo_id())
windll.dwmapi.DwmSetWindowAttribute(
hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE,
ctypes.byref(ctypes.c_int(1)), ctypes.sizeof(ctypes.c_int)
)
except Exception:
pass
HackerGUI(root)
root.mainloop()
if __name__ == "__main__":
main()