-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapper.py
More file actions
executable file
·1970 lines (1799 loc) · 85.8 KB
/
Copy pathwrapper.py
File metadata and controls
executable file
·1970 lines (1799 loc) · 85.8 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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""PocketSET v2.0 — Interactive TUI wrapper for the Social-Engineer Toolkit"""
import os, sys, re, json, shutil, signal, textwrap, time, subprocess, socket
import logging, traceback, threading, importlib
from pathlib import Path
from datetime import datetime
from typing import Optional, Callable, Union, Any
# ── Rich imports ──────────────────────────────────────────────────────────────
try:
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.layout import Layout
from rich.live import Live
from rich.text import Text
from rich.columns import Columns
from rich import box
from rich.prompt import Prompt, IntPrompt, Confirm as RichConfirm
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn
from rich.syntax import Syntax
from rich.rule import Rule
from rich.markup import escape
except ImportError as e:
print(f"Error: rich is required. Install: pip install rich\n{e}")
sys.exit(1)
# ── Paths ─────────────────────────────────────────────────────────────────────
try:
BASE_DIR = Path(__file__).resolve().parent
except NameError:
BASE_DIR = Path("/opt/PocketSET")
if not BASE_DIR.exists():
BASE_DIR = Path.cwd()
SCHEMA_PATH = BASE_DIR / "schema.json"
POCKETSET_DIR = Path.home() / ".pocketset"
LOGS_DIR = POCKETSET_DIR / "logs"
TEMP_DIR = POCKETSET_DIR / "temp"
CONFIG_PATH = POCKETSET_DIR / "config.json"
HISTORY_PATH = POCKETSET_DIR / "history.jsonl"
INPUT_HIST_PATH = POCKETSET_DIR / "input_history.json"
PRESETS_DIR = POCKETSET_DIR / "presets"
PLUGINS_DIR = POCKETSET_DIR / "plugins"
REPORTS_DIR = POCKETSET_DIR / "reports"
# ── Globals ───────────────────────────────────────────────────────────────────
console = Console()
VERSION = "2.0.0"
# ── Ensure directories exist before any file ops ─────────────────────────────
for _d in (POCKETSET_DIR, LOGS_DIR, TEMP_DIR, PRESETS_DIR, PLUGINS_DIR, REPORTS_DIR):
_d.mkdir(parents=True, exist_ok=True)
# ── Logging ───────────────────────────────────────────────────────────────────
LOG = logging.getLogger("pocketset")
LOG.setLevel(logging.DEBUG)
_fh = logging.FileHandler(LOGS_DIR / "pocketset.log", encoding="utf-8", delay=True)
_fh.setLevel(logging.DEBUG)
_fh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
LOG.addHandler(_fh)
_ch = logging.StreamHandler(sys.stdout)
_ch.setLevel(logging.WARNING)
_ch.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
LOG.addHandler(_ch)
# ── Schema ────────────────────────────────────────────────────────────────────
if SCHEMA_PATH.exists():
with open(str(SCHEMA_PATH), encoding="utf-8") as _f:
SCHEMA = json.load(_f)
MENU_TREE = SCHEMA.get("menu_tree", {})
else:
SCHEMA = {}
MENU_TREE = {"main_menu": {"1": "Social-Engineering Attacks", "2": "Fast-Track", "3": "Plugins", "4": "Update", "5": "Credits"}}
LOG.warning("schema.json not found, using built-in defaults")
def _load_validation() -> dict:
vpath = BASE_DIR / "validation.json"
if vpath.exists():
try:
return json.loads(vpath.read_text(encoding="utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError):
LOG.warning("validation.json is malformed, ignoring")
return {}
VAL_SCHEMA = _load_validation()
# ── Output Filtering ───────────────────────────────────────────────────────────
HIGHLIGHT_KEYWORDS = [
'generated', 'successful', 'complete',
'launching', 'listening', 'received',
'qrcode', 'listener',
'error:', 'fail', 'timeout', 'exception',
'has been', 'written to', 'saved to',
'opened', 'connecting',
'starting exploit', 'attack complete',
'command execution', 'session opened',
'meterpreter', 'shell',
]
HIGHLIGHT_EXCLUDE_PREFIXES = (
'1)', '2)', '3)', '4)', '5)', '6)', '7)', '8)', '9)', '10)',
'99)',
' 1)', ' 2)', ' 3)', ' 4)', ' 5)', ' 6)', ' 7)', ' 8)', ' 9)',
)
def is_highlight_line(line: str) -> bool:
if not line or len(line) < 10:
return False
low = line.lower().strip()
if low.startswith(HIGHLIGHT_EXCLUDE_PREFIXES):
return False
if 'created by:' in low or 'revision' in low:
return False
if low.startswith('[---]'):
return False
if low.startswith('select from'):
return False
return any(kw in low for kw in HIGHLIGHT_KEYWORDS)
def strip_ansi(text: str) -> str:
ansi_re = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]|\x1b\].*?(?:\x1b\\|$)')
return ansi_re.sub('', text)
def smart_filter_output(text: str) -> str:
lines = text.split('\n')
seen = set()
result = []
for line in lines:
key = line.strip().lower()
if ('social-engineer toolkit' in key or 'set version' in key
or 'select from the menu' in key or '[-]' == line.strip()[:3]):
if key in seen:
continue
seen.add(key)
result.append(line)
return '\n'.join(result)
def detect_artifacts(output: str, attack_name: str) -> list[Path]:
artifacts = []
set_reports = Path.home() / ".set" / "reports"
if set_reports.exists():
now = time.time()
files = sorted(set_reports.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True)
for f in files[:10]:
if now - f.stat().st_mtime < 120:
artifacts.append(f)
if "qrcode" in attack_name.lower():
for f in set_reports.glob("*qrcode*"):
if f not in artifacts:
artifacts.append(f)
return artifacts
# ── Config ────────────────────────────────────────────────────────────────────
DEFAULT_CONFIG: dict[str, Any] = {
"platform": "auto",
"theme": {
"header": "bold cyan",
"success": "bold green",
"error": "bold red",
"warning": "bold yellow",
"info": "white",
"muted": "dim white",
},
"pexpect_delay": 0.3,
"timeout_seconds": 600,
"history_size": 100,
"auto_update": True,
"pre_flight_ping": True,
"default_smtp": "",
"default_lhost": "",
"default_port": "443",
}
def load_config() -> dict:
if CONFIG_PATH.exists():
try:
cfg = json.loads(CONFIG_PATH.read_text())
merged = DEFAULT_CONFIG.copy()
merged.update(cfg)
return merged
except Exception:
pass
return dict(DEFAULT_CONFIG)
def save_config(cfg: dict) -> None:
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(json.dumps(cfg, indent=2))
CONFIG = load_config()
# ── Platform Detection ────────────────────────────────────────────────────────
class Platform:
@staticmethod
def is_termux() -> bool:
return "com.termux" in str(Path.home()) or "TERMUX_VERSION" in os.environ
@staticmethod
def is_kali() -> bool:
try:
r = subprocess.run(["grep", "-qi", "kali", "/etc/os-release"],
capture_output=True, timeout=5)
return r.returncode == 0
except Exception:
return False
@staticmethod
def is_proot() -> bool:
return os.path.exists("/data/data/com.termux/files/usr/bin/proot") or \
"PROOT_TMP_DIR" in os.environ
@staticmethod
def detect() -> str:
if Platform.is_termux():
return "termux"
if Platform.is_kali():
return "kali"
return "linux"
@staticmethod
def name() -> str:
return Platform.detect().title()
# ── Colors (from config) ──────────────────────────────────────────────────────
class Colors:
HEADER = CONFIG["theme"]["header"]
SUCCESS = CONFIG["theme"]["success"]
ERROR = CONFIG["theme"]["error"]
WARNING = CONFIG["theme"]["warning"]
INFO = CONFIG["theme"]["info"]
MUTED = CONFIG["theme"]["muted"]
# ── Utility functions ─────────────────────────────────────────────────────────
def _ensure_dirs() -> None:
for d in (POCKETSET_DIR, LOGS_DIR, TEMP_DIR, PRESETS_DIR, PLUGINS_DIR, REPORTS_DIR):
d.mkdir(parents=True, exist_ok=True)
def _cleanup_temp() -> None:
if TEMP_DIR.exists():
for f in TEMP_DIR.iterdir():
try:
f.unlink()
except Exception:
pass
try:
TEMP_DIR.rmdir()
except Exception:
pass
def _safe_input(prompt_str: str = "") -> str:
try:
return input(prompt_str)
except (EOFError, KeyboardInterrupt):
return ""
def signal_handler(sig, frame) -> None:
console.print("\n[yellow]Shutting down PocketSET...[/]")
_cleanup_temp()
console.print("[yellow]Hack the Gibson...and remember...hugs are worth more than handshakes.[/]")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# ── Validators ────────────────────────────────────────────────────────────────
def validate_ip(ip: str) -> bool:
m = re.match(r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$', ip.strip())
if not m:
return False
return all(0 <= int(g) <= 255 for g in m.groups())
def validate_port(p: str) -> bool:
try:
return 1 <= int(p.strip()) <= 65535
except (ValueError, TypeError):
return False
def validate_url(url: str) -> bool:
u = url.strip()
if not u.startswith(('http://', 'https://')):
return False
return bool(re.match(r'^https?://[^\s/$.?#].[^\s]*$', u))
def validate_email(e: str) -> tuple[bool, str]:
if bool(re.match(r'^[^@\s]+@[^@\s]+\.[^@\s]+$', e.strip())):
return True, ""
return False, "Invalid email format"
def validate_file_read(p: str) -> tuple[bool, str]:
if Path(p.strip()).expanduser().exists():
return True, ""
return False, "File not found"
def validate_cidr(c: str) -> bool:
c = c.strip()
m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,2})$', c)
if not m:
return False
return all(0 <= int(g) <= 255 for g in m.group(1).split('.')) and 0 <= int(m.group(2)) <= 32
def validate_hostname(h: str) -> bool:
return bool(re.match(r'^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$', h.strip()))
class Validator:
@staticmethod
def validate(val_type: str, value: str, rules: dict) -> tuple[bool, str]:
v = value.strip()
if not v and rules.get("required", False):
return False, "This field is required."
if not v and not rules.get("required", False):
return True, ""
custom = rules.get("custom", "")
if custom == "validate_ip":
if not validate_ip(v):
return False, rules.get("error_message", "Invalid IP address")
return True, ""
if custom == "validate_port":
if not validate_port(v):
return False, rules.get("error_message", "Port must be 1-65535")
return True, ""
if custom == "validate_url":
if not validate_url(v):
return False, rules.get("error_message", "Invalid URL format")
return True, ""
if custom == "validate_file_read":
ok, _ = validate_file_read(v)
if not ok:
return False, rules.get("error_message", "File not found")
return True, ""
if custom == "validate_cidr_or_file":
file_ok, _ = validate_file_read(v)
if validate_cidr(v) or validate_ip(v) or file_ok:
return True, ""
return False, rules.get("error_message", "Invalid CIDR, IP, or file path")
if custom == "validate_target":
if validate_ip(v) or validate_hostname(v):
return True, ""
return False, rules.get("error_message", "Enter a valid IP or hostname")
if custom == "validate_emails":
parts = [e.strip() for e in v.replace('\n', ',').split(',') if e.strip()]
if not parts:
return False, "Enter at least one email"
for e in parts:
ok, _ = validate_email(e)
if not ok:
return False, f"Invalid email: {e}"
return True, ""
pattern = rules.get("pattern", "")
if pattern and not re.match(pattern, v):
return False, rules.get("error_message", "Invalid format")
min_len = rules.get("min_length", 0)
max_len = rules.get("max_length", 0)
if min_len and len(v) < min_len:
return False, f"Minimum {min_len} characters"
if max_len and len(v) > max_len:
return False, f"Maximum {max_len} characters"
try:
min_v = rules.get("min")
max_v = rules.get("max")
if min_v is not None or max_v is not None:
n = int(v)
if min_v is not None and n < min_v:
return False, f"Minimum value: {min_v}"
if max_v is not None and n > max_v:
return False, f"Maximum value: {max_v}"
except Exception:
pass
return True, ""
# ── Display helpers ───────────────────────────────────────────────────────────
def show_banner() -> None:
banner = textwrap.dedent(f"""\
[bold cyan]\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
\u2551 PocketSET v{VERSION} \u2551
\u2551 Social-Engineer Toolkit \u2014 Interactive TUI \u2551
\u2551 Platform: {Platform.name():<14} \u2551
\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d[/]""")
console.print()
console.print(Panel(banner, border_style="cyan", box=box.DOUBLE_EDGE))
console.print()
def show_error(title: str, message: str) -> None:
console.print(Panel(f"[red]{message}[/]", title=f"[bold red]{title}[/]", border_style="red"))
def show_success(title: str, message: str) -> None:
console.print(Panel(f"[green]{message}[/]", title=f"[bold green]{title}[/]", border_style="green"))
def show_warning(title: str, message: str) -> None:
console.print(Panel(f"[yellow]{message}[/]", title=f"[bold yellow]{title}[/]", border_style="yellow"))
def show_info(message: str) -> None:
console.print(f"[dim]\u2503[/] {message}")
def show_rule() -> None:
console.print(Rule(style="dim"))
def prompt_text(label: str, default: str = "", password: bool = False,
validate: Optional[Callable] = None,
error_msg: str = "",
history: Optional[list] = None) -> str:
while True:
d = f" [{default}]" if default else ""
try:
if password:
val = Prompt.ask(f"[bold]{label}[/]{d}", password=True)
else:
val = Prompt.ask(f"[bold]{label}[/]{d}")
except (EOFError, KeyboardInterrupt):
return default or ""
if not val and default:
val = default
if validate:
ok, msg = validate(val.strip())
if not ok:
show_error("Validation Error", msg or error_msg)
continue
result = val.strip()
if history is not None:
h = [x for x in history if x != result]
h.insert(0, result)
history[:] = h[:CONFIG.get("history_size", 100)]
return result
def prompt_confirm(label: str, default: bool = False) -> bool:
try:
return RichConfirm.ask(f"[bold]{label}[/]", default=default)
except (EOFError, KeyboardInterrupt):
return default
def prompt_choice(title: str, options: dict, prompt_text_str: str = "Select an option") -> str:
console.print(f"\n[bold cyan]{title}[/]")
show_rule()
table = Table(box=box.SIMPLE, show_header=False, border_style="dim")
table.add_column("#", style="cyan", width=4)
table.add_column("Option", style="white")
for k, v in options.items():
table.add_row(str(k), str(v))
console.print(table)
show_rule()
while True:
try:
choice = Prompt.ask(f"[bold]{prompt_text_str}[/]")
except (EOFError, KeyboardInterrupt):
return "99"
if choice in options:
return choice
show_error("Invalid Choice", f"Enter a valid option: {', '.join(options.keys())}")
def prompt_numbered_list(title: str, items: list, prompt_text_str: str = "Select an option") -> str:
options = {str(i+1): item for i, item in enumerate(items)}
return prompt_choice(title, options, prompt_text_str)
# ── Input history ─────────────────────────────────────────────────────────────
class InputHistory:
_data: dict[str, list[str]] = {}
@classmethod
def load(cls) -> None:
if INPUT_HIST_PATH.exists():
try:
cls._data = json.loads(INPUT_HIST_PATH.read_text(encoding="utf-8"))
except Exception:
cls._data = {}
@classmethod
def save(cls) -> None:
INPUT_HIST_PATH.parent.mkdir(parents=True, exist_ok=True)
try:
INPUT_HIST_PATH.write_text(json.dumps(cls._data, indent=2), encoding="utf-8")
except Exception:
pass
@classmethod
def get(cls, key: str) -> list[str]:
return cls._data.get(key, [])
@classmethod
def push(cls, key: str, value: str) -> None:
h = cls._data.setdefault(key, [])
if not isinstance(h, list):
h = []
h2 = [x for x in h if x != value]
h2.insert(0, value)
cls._data[key] = h2[:CONFIG.get("history_size", 100)]
InputHistory.load()
# ── Disclaimer ────────────────────────────────────────────────────────────────
class Disclaimer:
DISCLAIMER_FILE = POCKETSET_DIR / "disclaimer_accepted"
@classmethod
def is_accepted(cls) -> bool:
return cls.DISCLAIMER_FILE.exists()
@classmethod
def mark_accepted(cls) -> None:
cls.DISCLAIMER_FILE.parent.mkdir(parents=True, exist_ok=True)
cls.DISCLAIMER_FILE.write_text(f"accepted on {datetime.now().isoformat()}\n")
@classmethod
def show(cls) -> bool:
if cls.is_accepted():
return True
console.clear()
panel_text = (
"[bold red]The Social-Engineer Toolkit (SET) is a penetration testing\n"
"framework for AUTHORIZED security assessments ONLY.[/]\n\n"
"By using PocketSET you agree that:\n\n"
" [white]\u2022 You have explicit written permission to test the\n"
" target systems, networks, and/or personnel\n"
" \u2022 You will not use SET for any illegal or unauthorized\n"
" purpose\n"
" \u2022 You accept full responsibility for any consequences\n"
" arising from your use of this tool\n"
" \u2022 You comply with all applicable local, state, federal,\n"
" and international laws[/]\n\n"
"[bold red]Unauthorized use is a criminal offence.[/]\n\n"
"[dim]This disclaimer is displayed once per session.[/]"
)
console.print(Panel(panel_text, border_style="red", title="[bold red]LEGAL DISCLAIMER[/]"))
console.print()
val = Prompt.ask("[bold red]Type I AGREE to accept, or anything else to exit[/]")
if val.strip().upper() == "I AGREE":
cls.mark_accepted()
return True
console.print("[red]Exiting. You must accept the disclaimer to use PocketSET.[/]")
return False
# ── Dependency Checker ────────────────────────────────────────────────────────
class DependencyChecker:
TERMUX_SET_PATHS = [
"/data/data/com.termux/files/usr/local/bin/setoolkit",
"/data/data/com.termux/files/usr/bin/setoolkit",
]
@staticmethod
def find_setoolkit() -> str:
candidates = ["setoolkit", "seautomate", "./setoolkit"]
if Platform.is_termux():
candidates = DependencyChecker.TERMUX_SET_PATHS + candidates
candidates += [
"/usr/local/share/setoolkit/setoolkit",
"/usr/local/bin/setoolkit",
"/opt/setoolkit/setoolkit",
]
for c in candidates:
if "/" in c:
p = Path(c)
if p.is_file() and os.access(str(p), os.X_OK):
return str(p.resolve())
else:
found = shutil.which(c)
if found:
return found
return ""
@staticmethod
def check_setoolkit() -> bool:
return bool(DependencyChecker.find_setoolkit())
@staticmethod
def check_metasploit() -> bool:
if Platform.is_termux():
paths = ["/data/data/com.termux/files/usr/bin/msfconsole",
"/data/data/com.termux/files/usr/local/bin/msfconsole"]
for p in paths:
if Path(p).is_file():
return True
r = subprocess.run(["which", "msfconsole"], capture_output=True, text=True, timeout=30)
return r.returncode == 0
@staticmethod
def check_pexpect() -> bool:
return importlib.util.find_spec("pexpect") is not None
@staticmethod
def install_pexpect() -> bool:
show_info("Installing pexpect...")
r = subprocess.run([sys.executable, "-m", "pip", "install", "pexpect", "-q"],
capture_output=True, text=True, timeout=120)
if r.returncode == 0:
show_success("Success", "pexpect installed")
return True
show_error("Install Failed", f"Could not install pexpect:\n{r.stderr}")
return False
# ── Auto-Update ───────────────────────────────────────────────────────────────
class AutoUpdater:
@staticmethod
def check() -> Optional[str]:
if not CONFIG.get("auto_update", True):
return None
try:
import urllib.request
req = urllib.request.Request(
"https://api.github.com/repos/highoncomputers/PocketSET/releases/latest",
headers={"User-Agent": "PocketSET/2.0"}
)
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read())
latest = data.get("tag_name", "").lstrip("v")
if latest and latest > VERSION:
return latest
except Exception:
pass
return None
@staticmethod
def update() -> bool:
show_info("Updating PocketSET via git pull...")
r = subprocess.run(["git", "-C", str(BASE_DIR), "pull", "--ff-only"],
capture_output=True, text=True, timeout=60)
if r.returncode == 0:
show_success("Updated", "PocketSET updated. Please restart.")
return True
show_error("Update Failed", r.stderr[:500])
return False
# ── Automate Script Builder ───────────────────────────────────────────────────
class AutomateScriptBuilder:
def __init__(self) -> None:
self.lines: list[str] = []
self.script_path = TEMP_DIR / f"automate_{int(time.time())}.txt"
def add(self, line: str) -> None:
self.lines.append(line if line else "")
def add_many(self, *lines: str) -> None:
for line in lines:
self.add(line)
def add_blank(self) -> None:
self.lines.append("")
def write(self, exit_cleanly: bool = True) -> Path:
lines = list(self.lines)
if exit_cleanly:
lines.extend(["99", "99", "99"])
text = "\n".join(lines) + "\n"
self.script_path.parent.mkdir(parents=True, exist_ok=True)
self.script_path.write_text(text)
return self.script_path
def build_social_engineering(self, main_choice: str, sub_choice: str, params: dict) -> None:
self.add("1")
self.add(main_choice)
if main_choice == "2":
self.add(sub_choice)
source_choice = params.get("web_source", "2")
self.add(source_choice)
if source_choice == "2":
self.add(params.get("url", ""))
elif source_choice == "3":
self.add(params.get("import_path", ""))
self.add(params.get("lhost", ""))
elif main_choice == "3":
media_type = params.get("media_type", "1")
self.add(media_type)
if media_type == "1":
self.add(params.get("lhost", ""))
elif main_choice == "4":
self.add(params.get("payload_type", "1"))
self.add(params.get("meterpreter_payload", "2"))
self.add(params.get("lhost", ""))
self.add(params.get("lport", "443"))
self.add(params.get("encoding", "4"))
elif main_choice == "5":
self.add("1")
self.add(params.get("smtp_server", ""))
self.add(params.get("from_email", ""))
self.add(params.get("to_emails", ""))
self.add(params.get("subject", ""))
self.add(params.get("body", ""))
if params.get("email_list_file"):
self.add(params["email_list_file"])
else:
self.add("")
elif main_choice == "6":
self.add(sub_choice)
tt = int(sub_choice)
if tt in (1, 2, 3, 4, 5, 6, 12, 14):
self.add(params.get("lhost", ""))
self.add(params.get("lport", "443"))
elif main_choice == "7":
self.add(params.get("wireless_action", "1"))
if params.get("wireless_action") == "1":
self.add(params.get("ssid", "Free WiFi"))
self.add(params.get("channel", "6"))
self.add(params.get("interface", "wlan0"))
elif main_choice == "8":
self.add(params.get("qr_url", ""))
elif main_choice == "9":
self.add(sub_choice)
pt = int(sub_choice)
if pt in (1, 2, 3):
self.add(params.get("lhost", ""))
self.add(params.get("lport", "443"))
elif main_choice == "1":
self.add(sub_choice)
at = int(sub_choice)
if at == 1:
self.add(params.get("fileformat", "1"))
self.add(params.get("smtp_server", ""))
self.add(params.get("from_email", ""))
self.add(params.get("to_emails", ""))
self.add(params.get("subject", ""))
self.add(params.get("body", ""))
self.add(params.get("email_list_file", ""))
self.add(params.get("lhost", ""))
self.add(params.get("lport", "443"))
elif at == 2:
self.add(params.get("fileformat", "1"))
self.add(params.get("lhost", ""))
self.add(params.get("lport", "443"))
elif at == 3:
pass
def build_fasttrack(self, main_choice: str, sub_choice: str, params: dict) -> None:
self.add("2")
self.add(main_choice)
if main_choice == "1":
self.add(sub_choice)
if sub_choice == "1":
self.add(params.get("scan_source", "1"))
if params.get("scan_source") == "1":
self.add(params.get("target_cidr", ""))
else:
self.add(params.get("target_file", ""))
self.add(params.get("port", "1433"))
self.add(params.get("wordlist", "default"))
self.add(params.get("username", "sa"))
else:
self.add(params.get("target", ""))
self.add(params.get("port", "1433"))
self.add(params.get("username", "sa"))
self.add(params.get("password", ""))
elif main_choice == "2":
self.add(sub_choice)
self.add(params.get("target", ""))
self.add(params.get("port", "445"))
elif main_choice == "4":
self.add(params.get("target", ""))
self.add("")
elif main_choice in ("3", "5"):
self.add(params.get("target", ""))
elif main_choice == "6":
self.add(params.get("target", ""))
self.add(params.get("username", ""))
self.add(params.get("password", ""))
def get_preview(self) -> str:
return "\n".join(self.lines)
# ── SET Executor with Live Output ─────────────────────────────────────────────
class SETExecutor:
def __init__(self, script_path: Path, timeout: int = 600) -> None:
self.script_path = script_path
self.timeout = timeout
self.output_lines: list[str] = []
self.setoolkit_cmd = DependencyChecker.find_setoolkit() or "setoolkit"
self._running = False
def _resolve_cmd(self) -> str:
cmd = self.setoolkit_cmd
if "/" not in cmd and not cmd.startswith("./"):
resolved = shutil.which(cmd)
if resolved:
cmd = resolved
return cmd
def _run_pexpect_live(self, progress=None, live_callback=None) -> tuple[str, bool]:
import pexpect
import pexpect.exceptions as pexcp
child = None
output_chunks: list[str] = []
cmd = self._resolve_cmd()
self._running = True
try:
child = pexpect.spawn(
cmd,
timeout=self.timeout,
encoding="utf-8",
codec_errors="replace",
env={**os.environ, "TERM": "xterm-256color", "POCKETSET": "1", "PYTHONUNBUFFERED": "1"}
)
try:
child.expect(r"99\) Exit the Social-Engineer Toolkit", timeout=120)
except pexcp.TIMEOUT:
return "\n".join(output_chunks) + "\n[!] Initial menu load timed out", True
except pexcp.EOF:
return "\n".join(output_chunks) + "\n[!] SET exited before menu loaded", True
initial = child.before or ""
output_chunks.append(initial)
if live_callback:
live_callback(initial)
script_text = self.script_path.read_text()
lines = [x for x in script_text.split("\n")]
total = len(lines)
for i, line in enumerate(lines):
if not self._running:
break
child.sendline(line.strip() if line.strip() else "")
if progress:
progress.update(progress.task_ids[0] if progress.task_ids else None,
description=f"[cyan]Sending SET commands... ({i+1}/{total})[/]")
time.sleep(CONFIG.get("pexpect_delay", 0.3))
while True:
try:
chunk = child.read_nonblocking(size=8192, timeout=0.3)
if chunk:
output_chunks.append(chunk)
self.output_lines.append(chunk)
if live_callback:
live_callback(chunk)
except pexcp.TIMEOUT:
if not child.isalive():
break
continue
except pexcp.EOF:
break
try:
child.expect(pexcp.EOF, timeout=5)
except Exception:
pass
captured = child.before or ""
try:
rest = child.read()
captured += rest or ""
except Exception:
pass
if captured:
output_chunks.append(captured)
self.output_lines.append(captured)
if live_callback:
live_callback(captured)
finally:
self._running = False
if child:
try:
child.close(force=True)
except Exception:
pass
return "\n".join(output_chunks), False
def _run_subprocess_live(self, progress=None, live_callback=None) -> tuple[str, bool]:
script_text = self.script_path.read_text()
cmd = self._resolve_cmd()
proc = None
stdout_lines: list[str] = []
self._running = True
try:
proc = subprocess.Popen(
[cmd],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
env={**os.environ, "TERM": "xterm-256color", "POCKETSET": "1", "PYTHONUNBUFFERED": "1"}
)
def reader() -> None:
for line in proc.stdout:
stdout_lines.append(line)
self.output_lines.append(line)
if live_callback:
live_callback(line)
t = threading.Thread(target=reader, daemon=True)
t.start()
try:
for line in script_text.split("\n"):
if not self._running:
break
proc.stdin.write(line + "\n")
proc.stdin.flush()
time.sleep(CONFIG.get("pexpect_delay", 0.3))
except Exception:
pass
finally:
try:
proc.stdin.close()
except Exception:
pass
try:
proc.wait(timeout=self.timeout)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
return "".join(stdout_lines) + "\n[red]Command timed out[/]", True
t.join()
finally:
self._running = False
if proc and proc.poll() is None:
try:
proc.kill()
except Exception:
pass
try:
proc.wait(timeout=5)
except Exception:
pass
return "".join(stdout_lines), False
def execute(self, progress=None, live_callback=None) -> str:
try:
if DependencyChecker.check_pexpect():
output, _ = self._run_pexpect_live(progress, live_callback)
return output
else:
output, _ = self._run_subprocess_live(progress, live_callback)
return output
except FileNotFoundError:
return "ERROR: setoolkit not found. Install SET first."
except Exception as e:
LOG.exception("Execution error: %s", e)
return f"ERROR: {e}"
def stop(self) -> None:
self._running = False
# ── Attack History ────────────────────────────────────────────────────────────
class AttackHistory:
@staticmethod
def record(attack_name: str, params: dict, output: str, success: bool) -> None:
HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True)
entry = {
"timestamp": datetime.now().isoformat(),
"attack": attack_name,
"params": {k: v for k, v in params.items() if k not in ("password",)},
"success": success,
"platform": Platform.detect(),
}
try:
with open(str(HISTORY_PATH), "a", encoding="utf-8") as f:
f.write(json.dumps(entry) + "\n")
except Exception:
pass
@staticmethod
def view() -> None:
if not HISTORY_PATH.exists():
show_info("No attack history yet.")
return
try:
entries = []
with open(str(HISTORY_PATH), encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
entries.append(json.loads(line))
if not entries:
show_info("No attack history yet.")
return
table = Table(title="Attack History", box=box.SIMPLE, border_style="dim")
table.add_column("#", style="cyan", width=4)
table.add_column("Time", style="yellow", width=20)
table.add_column("Attack", style="white")
table.add_column("Status", width=8)
for i, e in enumerate(entries[-CONFIG.get("history_size", 100):], 1):
status = "[green]OK[/]" if e.get("success") else "[red]FAIL[/]"
table.add_row(str(i), e.get("timestamp", "?")[:19], e.get("attack", "?"), status)
console.print(table)
except Exception:
show_error("Error", "Could not read history file.")
# ── Attack Presets ────────────────────────────────────────────────────────────
class AttackPreset:
@staticmethod
def save(name: str, attack_type: str, params: dict) -> None:
PRESETS_DIR.mkdir(parents=True, exist_ok=True)
path = PRESETS_DIR / f"{name.replace(' ', '_').lower()}.json"
data = {
"name": name,
"attack_type": attack_type,
"params": {k: v for k, v in params.items() if k not in ("password",)},
"created": datetime.now().isoformat(),
"platform": Platform.detect(),
}
path.write_text(json.dumps(data, indent=2))
show_success("Saved", f"Preset saved to {path.name}")
@staticmethod
def load() -> Optional[tuple[str, dict]]:
PRESETS_DIR.mkdir(parents=True, exist_ok=True)
presets = sorted(PRESETS_DIR.glob("*.json"))
if not presets:
show_info("No presets found.")
return None
opts = {str(i+1): p.stem for i, p in enumerate(presets)}
choice = prompt_choice("Load Preset", opts)
if choice in opts:
path = presets[int(choice) - 1]
try:
data = json.loads(path.read_text())
show_success("Loaded", f"Preset: {data.get('name', path.stem)}")