-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhacking.py
More file actions
2214 lines (1970 loc) · 87.7 KB
/
Copy pathhacking.py
File metadata and controls
2214 lines (1970 loc) · 87.7 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
"""
╔══════════════════════════════════════════════════════════════════════════════╗
║ SNCO ELITE CTF TOOLKIT — All-in-One Competition Script ║
║ Road to Rank 1 | v1.0 ║
╚══════════════════════════════════════════════════════════════════════════════╝
USAGE:
python3 ctf_toolkit.py # Interactive menu
python3 ctf_toolkit.py --auto <file> # Auto-detect & decode file
python3 ctf_toolkit.py --magic <string> # Magic decode a string
INSTALL DEPS:
pip install pycryptodome gmpy2 requests pwntools owiener pyperclip 2>/dev/null
"""
import os, sys, re, base64, codecs, binascii, string, hashlib, itertools
import struct, socket, json, time, math, subprocess, argparse, textwrap
from collections import Counter
from urllib.parse import quote, unquote, urlencode
from pathlib import Path
# ── Optional imports (graceful fallback) ──────────────────────────────────────
try:
from Crypto.Cipher import AES, DES
from Crypto.Util.number import long_to_bytes, bytes_to_long, getPrime
from Crypto.Util.Padding import unpad
HAS_CRYPTO = True
except ImportError:
HAS_CRYPTO = False
try:
import gmpy2
HAS_GMPY2 = True
except ImportError:
HAS_GMPY2 = False
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
import owiener
HAS_OWIENER = True
except ImportError:
HAS_OWIENER = False
try:
import pyperclip
HAS_CLIP = True
except ImportError:
HAS_CLIP = False
# ══════════════════════════════════════════════════════════════════════════════
# COLOURS & UI
# ══════════════════════════════════════════════════════════════════════════════
class C:
RED = '\033[91m'; GREEN = '\033[92m'; YELLOW = '\033[93m'
BLUE = '\033[94m'; PURPLE = '\033[95m'; CYAN = '\033[96m'
WHITE = '\033[97m'; BOLD = '\033[1m'; DIM = '\033[2m'
RESET = '\033[0m'
def banner():
print(f"""{C.CYAN}{C.BOLD}
╔══════════════════════════════════════════════════════════════════════════════╗
║ ███████╗███╗ ██╗ ██████╗ ██████╗ ████████╗██╗ ██╗ ║
║ ██╔════╝████╗ ██║██╔════╝██╔═══██╗ ██╔══╝██║ ██╔╝ ║
║ ███████╗██╔██╗ ██║██║ ██║ ██║ ██║ █████╔╝ ║
║ ╚════██║██║╚██╗██║██║ ██║ ██║ ██║ ██╔═██╗ ║
║ ███████║██║ ╚████║╚██████╗╚██████╔╝ ██║ ██║ ██╗ ║
║ ╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ║
║ ELITE CTF TOOLKIT — Road to Rank 1 ║
╚══════════════════════════════════════════════════════════════════════════════╝
{C.RESET}""")
def section(title):
print(f"\n{C.BOLD}{C.PURPLE}{'═'*60}{C.RESET}")
print(f"{C.BOLD}{C.YELLOW} {title}{C.RESET}")
print(f"{C.BOLD}{C.PURPLE}{'═'*60}{C.RESET}\n")
def ok(msg): print(f" {C.GREEN}[+]{C.RESET} {msg}")
def info(msg): print(f" {C.BLUE}[*]{C.RESET} {msg}")
def warn(msg): print(f" {C.YELLOW}[!]{C.RESET} {msg}")
def err(msg): print(f" {C.RED}[-]{C.RESET} {msg}")
def flag(msg): print(f"\n {C.BOLD}{C.GREEN}🚩 FLAG CANDIDATE: {msg}{C.RESET}\n")
def clip(text):
if HAS_CLIP:
try: pyperclip.copy(str(text)); print(f" {C.DIM}(copied to clipboard){C.RESET}")
except: pass
def menu(title, options):
section(title)
for i, opt in enumerate(options, 1):
print(f" {C.CYAN}[{i:2}]{C.RESET} {opt}")
print(f" {C.CYAN}[ 0]{C.RESET} ← Back / Exit")
try:
choice = int(input(f"\n{C.BOLD} Select > {C.RESET}"))
return choice
except (ValueError, KeyboardInterrupt):
return 0
def get_input(prompt, default=None):
try:
val = input(f" {C.CYAN}{prompt}{C.RESET} ").strip()
return val if val else default
except KeyboardInterrupt:
return default
# ══════════════════════════════════════════════════════════════════════════════
# 1. ENCODING / DECODING
# ══════════════════════════════════════════════════════════════════════════════
def detect_encoding(s):
"""Heuristic encoding detector."""
s = s.strip()
results = []
# Base64
b64_chars = set(string.ascii_letters + string.digits + '+/=')
if all(c in b64_chars for c in s) and len(s) % 4 == 0:
results.append('base64')
# Base32
b32_chars = set(string.ascii_uppercase + '234567=')
if all(c in b32_chars for c in s.upper()) and len(s) % 8 == 0:
results.append('base32')
# Hex
if all(c in string.hexdigits for c in s.replace(' ','').replace('0x','')):
results.append('hex')
# Binary
if all(c in '01 ' for c in s) and len(s.replace(' ','')) % 8 == 0:
results.append('binary')
# URL encoded
if '%' in s:
results.append('url_encoded')
# Decimal (space-separated)
if all(p.isdigit() for p in s.split()) and len(s.split()) > 1:
results.append('decimal_ascii')
# Morse
if all(c in '.-/ ' for c in s):
results.append('morse')
# Only printable ASCII with rot-like shift
results.append('rot13/caesar')
return results
def magic_decode(s):
"""Try every encoding automatically and print results."""
section("MAGIC DECODER")
info(f"Input: {repr(s[:80])}")
print()
attempts = {}
# Base64
try:
pad = s + '=' * (-len(s) % 4)
d = base64.b64decode(pad).decode('utf-8', errors='replace')
if any(32 <= ord(c) <= 126 for c in d):
attempts['Base64'] = d
except: pass
# Base32
try:
pad = s.upper() + '=' * (-len(s) % 8)
d = base64.b32decode(pad).decode('utf-8', errors='replace')
if any(32 <= ord(c) <= 126 for c in d):
attempts['Base32'] = d
except: pass
# Base85
try:
d = base64.b85decode(s).decode('utf-8', errors='replace')
if any(32 <= ord(c) <= 126 for c in d):
attempts['Base85'] = d
except: pass
# Hex
try:
clean = s.replace(' ','').replace('0x','').replace('\\x','')
if len(clean) % 2 == 0:
d = bytes.fromhex(clean).decode('utf-8', errors='replace')
if any(32 <= ord(c) <= 126 for c in d):
attempts['Hex'] = d
except: pass
# Binary
try:
bits = s.replace(' ','')
if len(bits) % 8 == 0 and all(c in '01' for c in bits):
chars = [chr(int(bits[i:i+8],2)) for i in range(0,len(bits),8)]
d = ''.join(chars)
if any(32 <= ord(c) <= 126 for c in d):
attempts['Binary'] = d
except: pass
# URL decode
try:
d = unquote(s)
if d != s:
attempts['URL Decode'] = d
except: pass
# Rot13
attempts['ROT13'] = codecs.decode(s, 'rot_13')
# Caesar brute
best_caesar = None
best_score = 0
for n in range(1, 26):
shifted = ''.join(
chr((ord(c)-65+n)%26+65) if c.isupper() else
chr((ord(c)-97+n)%26+97) if c.islower() else c
for c in s
)
score = sum(1 for w in ['the','flag','ctf','and','is','to','you','key'] if w in shifted.lower())
if score > best_score:
best_score, best_caesar = score, (n, shifted)
if best_caesar and best_score > 0:
attempts[f'Caesar +{best_caesar[0]}'] = best_caesar[1]
# Decimal ASCII
try:
nums = [int(x) for x in s.split()]
if all(32 <= n <= 126 for n in nums):
attempts['Decimal ASCII'] = ''.join(chr(n) for n in nums)
except: pass
# Morse code
MORSE = {'.-':'A','-.':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z','-----':'0','.----':'1','..---':'2',
'...--':'3','....-':'4','.....':'5','-....':'6','--...':'7',
'---..':'8','----.':'9'}
try:
words = s.strip().split(' / ')
decoded = ' '.join(''.join(MORSE.get(c,'?') for c in w.split()) for w in words)
if '?' not in decoded and decoded.strip():
attempts['Morse'] = decoded
except: pass
# HTML entities
try:
import html
d = html.unescape(s)
if d != s:
attempts['HTML Unescape'] = d
except: pass
# Print results
found_flag = False
for method, result in attempts.items():
clean = result.strip()
is_flag = bool(re.search(r'[A-Z_]{2,10}\{[^}]+\}', clean, re.IGNORECASE))
color = C.GREEN if is_flag else C.WHITE
print(f" {C.CYAN}[{method:15}]{C.RESET} {color}{clean[:100]}{C.RESET}")
if is_flag:
flag(clean)
clip(clean)
found_flag = True
if not found_flag:
info("No flag found. Check results above for partial decodes.")
return attempts
# ══════════════════════════════════════════════════════════════════════════════
# 2. CRYPTOGRAPHY ATTACKS
# ══════════════════════════════════════════════════════════════════════════════
def crypto_menu():
while True:
c = menu("CRYPTOGRAPHY ATTACKS", [
"RSA — Small Exponent (cube/eth root)",
"RSA — Common Modulus Attack",
"RSA — Wiener's Attack (small d)",
"RSA — Factor n (known p-q relation / Fermat)",
"RSA — Manual decrypt (given n, e, d or p, q)",
"Vigenere — Crack with Index of Coincidence",
"XOR — Key recovery (known plaintext / brute)",
"Hash — Identify hash type",
"Hash — MD5/SHA1 brute force (wordlist)",
"AES-ECB — Block analysis / byte-at-a-time",
"Padding Oracle — Demo framework",
])
if c == 0: break
elif c == 1: rsa_small_e()
elif c == 2: rsa_common_modulus()
elif c == 3: rsa_wiener()
elif c == 4: rsa_fermat_factor()
elif c == 5: rsa_manual_decrypt()
elif c == 6: vigenere_crack()
elif c == 7: xor_crack()
elif c == 8: hash_identify()
elif c == 9: hash_brute()
elif c == 10: aes_ecb_analysis()
elif c == 11: padding_oracle_demo()
def rsa_small_e():
section("RSA — SMALL EXPONENT ATTACK")
if not HAS_GMPY2: warn("gmpy2 not installed — using Python fallback (slow for large n)");
try:
c = int(get_input("Ciphertext c (integer):"))
e = int(get_input("Exponent e:", "3"))
info(f"Attempting e={e} root of c...")
if HAS_GMPY2:
m, exact = gmpy2.iroot(c, e)
if exact:
result = long_to_bytes(int(m)) if HAS_CRYPTO else m.to_bytes((int(m).bit_length()+7)//8,'big')
ok(f"Exact root found! m = {int(m)}")
ok(f"Decoded: {result}")
flag(result.decode('utf-8','replace'))
clip(result.decode('utf-8','replace'))
else:
warn("No exact root. Message may have padding, or wrong e.")
info("Trying small multiples of n (CRT extension)...")
n = get_input("Enter n (or press Enter to skip):")
if n:
n = int(n)
for k in range(1, 1000):
m, exact = gmpy2.iroot(k*n**1 + c if e==1 else c + k*n**e, e)
# standard broadcast: c + k*n
m2, exact2 = gmpy2.iroot(c + k*n, e)
if exact2:
result = m2.to_bytes((int(m2).bit_length()+7)//8,'big')
ok(f"Found with k={k}: {result}")
flag(result.decode('utf-8','replace'))
return
warn("Broadcast attack failed for k<1000.")
else:
# Pure Python integer nth root
m = round(c ** (1/e))
for candidate in [m-1, m, m+1]:
if candidate**e == c:
result = candidate.to_bytes((candidate.bit_length()+7)//8,'big')
ok(f"m = {candidate}")
flag(result.decode('utf-8','replace'))
return
warn("No exact root found.")
except Exception as ex:
err(f"Error: {ex}")
def rsa_common_modulus():
section("RSA — COMMON MODULUS ATTACK")
info("Requires: same plaintext encrypted with same n but different (e1, e2) where gcd(e1,e2)=1")
try:
n = int(get_input("Modulus n:"))
e1 = int(get_input("Exponent e1:"))
e2 = int(get_input("Exponent e2:"))
c1 = int(get_input("Ciphertext c1:"))
c2 = int(get_input("Ciphertext c2:"))
def extended_gcd(a, b):
if b == 0: return a, 1, 0
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
g, s1, s2 = extended_gcd(e1, e2)
if g != 1:
warn(f"gcd(e1,e2) = {g} ≠ 1. Attack may fail.")
def modinv(a, m):
_, x, _ = extended_gcd(a % m, m)
return x % m
if s1 < 0:
c1 = modinv(c1, n)
s1 = -s1
if s2 < 0:
c2 = modinv(c2, n)
s2 = -s2
m = (pow(c1, s1, n) * pow(c2, s2, n)) % n
result = m.to_bytes((m.bit_length()+7)//8, 'big')
ok(f"Recovered m = {m}")
ok(f"Decoded: {result}")
flag(result.decode('utf-8','replace'))
clip(result.decode('utf-8','replace'))
except Exception as ex:
err(f"Error: {ex}")
def rsa_wiener():
section("RSA — WIENER'S ATTACK (SMALL d)")
if not HAS_OWIENER:
warn("owiener not installed. Run: pip install owiener")
info("Manual continued-fraction implementation follows...")
try:
e = int(get_input("Public exponent e:"))
n = int(get_input("Modulus n:"))
if HAS_OWIENER:
d = owiener.attack(e, n)
if d:
ok(f"Private key d = {d}")
c = get_input("Ciphertext c to decrypt (or Enter to skip):")
if c:
m = pow(int(c), d, n)
result = m.to_bytes((m.bit_length()+7)//8,'big')
flag(result.decode('utf-8','replace'))
else:
warn("Wiener's attack failed — d is likely not small.")
else:
# Minimal continued fractions implementation
def cf_expansion(num, den):
while den:
yield num // den
num, den = den, num % den
def cf_convergents(cf):
n0, d0, n1, d1 = 0, 1, 1, 0
for a in cf:
n0, n1 = n1, a*n1 + n0
d0, d1 = d1, a*d1 + d0
yield n1, d1
for k, d in cf_convergents(cf_expansion(e, n)):
if k == 0: continue
phi, rem = divmod(e*d - 1, k)
if rem != 0: continue
# Check if phi yields valid p,q
b = n - phi + 1
disc = b*b - 4*n
if disc < 0: continue
sq = int(math.isqrt(disc))
if sq*sq == disc and (b+sq) % 2 == 0:
ok(f"Found d = {d}")
c = get_input("Ciphertext c (or Enter to skip):")
if c:
m = pow(int(c), d, n)
result = m.to_bytes((m.bit_length()+7)//8,'big')
flag(result.decode('utf-8','replace'))
return
warn("Wiener's attack failed.")
except Exception as ex:
err(f"Error: {ex}")
def rsa_fermat_factor():
section("RSA — FERMAT FACTORISATION (p ≈ q)")
info("Works when p and q are close together.")
try:
n = int(get_input("Modulus n:"))
info("Running Fermat's factorisation...")
a = math.isqrt(n)
if a * a == n:
ok(f"n is a perfect square! p = q = {a}")
return
a += 1
b2 = a*a - n
max_iter = 1_000_000
for _ in range(max_iter):
b = math.isqrt(b2)
if b*b == b2:
p, q = a - b, a + b
ok(f"Factored! p = {p}")
ok(f" q = {q}")
e = int(get_input("Exponent e (for decryption):", "65537"))
phi = (p-1)*(q-1)
def modinv(a, m):
g, x, _ = _egcd(a, m)
return x % m if g == 1 else None
def _egcd(a, b):
if b == 0: return a, 1, 0
g, x, y = _egcd(b, a%b)
return g, y, x - (a//b)*y
d = modinv(e, phi)
ok(f"Private key d = {d}")
c = get_input("Ciphertext c (or Enter to skip):")
if c:
m = pow(int(c), d, n)
result = m.to_bytes((m.bit_length()+7)//8,'big')
flag(result.decode('utf-8','replace'))
return
a += 1
b2 = a*a - n
warn(f"Fermat failed after {max_iter} iterations. p and q are far apart.")
except Exception as ex:
err(f"Error: {ex}")
def rsa_manual_decrypt():
section("RSA — MANUAL DECRYPT")
info("Provide (n,e,d) or (p,q,e) to decrypt a ciphertext.")
try:
mode = get_input("Mode: (1) n,d given (2) p,q,e given:", "1")
def _egcd(a, b):
if b == 0: return a, 1, 0
g, x, y = _egcd(b, a%b)
return g, y, x-(a//b)*y
def modinv(a, m):
g, x, _ = _egcd(a%m, m)
return x%m if g==1 else None
if mode == "2":
p = int(get_input("p:"))
q = int(get_input("q:"))
e = int(get_input("e:", "65537"))
n = p * q
phi = (p-1)*(q-1)
d = modinv(e, phi)
ok(f"n = {n}")
ok(f"d = {d}")
else:
n = int(get_input("n:"))
d = int(get_input("d:"))
c = int(get_input("Ciphertext c:"))
m = pow(c, d, n)
result = m.to_bytes((m.bit_length()+7)//8,'big')
ok(f"m (int) = {m}")
ok(f"m (bytes) = {result}")
flag(result.decode('utf-8','replace'))
clip(result.decode('utf-8','replace'))
except Exception as ex:
err(f"Error: {ex}")
def vigenere_crack():
section("VIGENERE CRACKER — Index of Coincidence")
ct = get_input("Ciphertext (letters only, case insensitive):").upper()
ct = ''.join(c for c in ct if c.isalpha())
if not ct:
err("No input.")
return
def ioc(text):
n = len(text)
if n < 2: return 0
freq = Counter(text)
return sum(f*(f-1) for f in freq.values()) / (n*(n-1))
def score_text(text):
"""English letter frequency score (higher = more English-like)."""
eng = {c: f for c, f in zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
[8.2,1.5,2.8,4.3,12.7,2.2,2.0,6.1,7.0,0.15,0.77,4.0,2.4,
6.7,7.5,1.9,0.10,6.0,6.3,9.1,2.8,0.98,2.4,0.15,2.0,0.074])}
freq = Counter(text)
total = len(text)
return sum(eng.get(c,0) * freq.get(c,0)/total for c in eng)
info(f"Ciphertext length: {len(ct)}")
# Estimate key length via IoC
best_kl, best_ioc = 1, 0
print(f"\n {'KeyLen':>6} {'IoC':>8} {'Verdict':>12}")
for kl in range(1, min(21, len(ct)//4)):
avg_ioc = sum(ioc(ct[i::kl]) for i in range(kl)) / kl
likely = "★ LIKELY" if avg_ioc > 0.060 else ""
print(f" {kl:6} {avg_ioc:.6f} {likely}")
if avg_ioc > best_ioc:
best_ioc, best_kl = avg_ioc, kl
ok(f"\nBest estimated key length: {best_kl} (IoC={best_ioc:.6f})")
kl = int(get_input(f"Use key length:", str(best_kl)))
# Frequency analysis per column
key = ''
for i in range(kl):
col = ct[i::kl]
freq = Counter(col)
# Assume most frequent letter decrypts to 'E'
most_common = freq.most_common(1)[0][0]
shift = (ord(most_common) - ord('E')) % 26
key += chr(65 + shift)
ok(f"Recovered key: {C.GREEN}{key}{C.RESET}")
# Decrypt
plaintext = ''
ki = 0
for c in ct:
if c.isalpha():
shift = ord(key[ki % kl]) - 65
plaintext += chr((ord(c) - 65 - shift) % 26 + 65)
ki += 1
else:
plaintext += c
ok(f"Plaintext: {plaintext[:200]}")
score = score_text(plaintext)
info(f"English score: {score:.2f} (>4 = likely correct)")
flag_match = re.search(r'[A-Z_]{2,10}\{[^}]+\}', plaintext)
if flag_match:
flag(flag_match.group())
clip(flag_match.group())
def xor_crack():
section("XOR KEY RECOVERY")
info("Options: 1=known-plaintext 2=single-byte brute 3=repeating-key brute")
mode = get_input("Mode (1/2/3):", "2")
ct_hex = get_input("Ciphertext (hex):")
try:
ct = bytes.fromhex(ct_hex.replace(' ','').replace('0x',''))
except:
ct = ct_hex.encode()
if mode == "1":
pt_known = get_input("Known plaintext (ASCII):").encode()
key = bytes(a^b for a,b in zip(ct, pt_known))
ok(f"Recovered key (hex): {key.hex()}")
ok(f"Recovered key (ASCII): {key.decode('utf-8','replace')}")
elif mode == "2":
info("Brute-forcing single byte key...")
results = []
for k in range(256):
pt = bytes(b ^ k for b in ct)
score = sum(c in b' etaoinshrdlu' for c in pt.lower())
results.append((score, k, pt))
results.sort(reverse=True)
print(f"\n {'Key':>5} {'Score':>6} Plaintext")
for score, k, pt in results[:10]:
preview = pt.decode('utf-8','replace')[:60]
flag_match = re.search(r'[A-Za-z_]{2,10}\{[^}]+\}', preview)
marker = f" {C.GREEN}← FLAG?{C.RESET}" if flag_match else ""
print(f" 0x{k:02x} {score:6} {preview}{marker}")
if flag_match:
flag(flag_match.group())
clip(flag_match.group())
elif mode == "3":
max_kl = int(get_input("Max key length to try:", "16"))
info(f"Brute-forcing repeating XOR key up to length {max_kl}...")
for kl in range(1, max_kl+1):
key = b''
for i in range(kl):
col = bytes(ct[j] for j in range(i, len(ct), kl))
best = max(range(256), key=lambda k: sum(c in b' etaoinshrdlu' for c in bytes(b^k for b in col)))
key += bytes([best])
pt = bytes(ct[i] ^ key[i % kl] for i in range(len(ct)))
preview = pt.decode('utf-8','replace')
flag_match = re.search(r'[A-Za-z_]{2,10}\{[^}]+\}', preview)
if flag_match:
ok(f"Key length {kl}: key={key.hex()} key_ascii={key.decode('utf-8','replace')}")
ok(f"Plaintext: {preview[:100]}")
flag(flag_match.group())
clip(flag_match.group())
return
# print top-scoring
ok("Top results (no flag found):")
key = b''
for i in range(1):
col = bytes(ct[j] for j in range(i, len(ct), 1))
best = max(range(256), key=lambda k: sum(c in b' etaoinshrdlu' for c in bytes(b^k for b in col)))
key += bytes([best])
pt = bytes(b ^ key[0] for b in ct)
ok(f"Single-byte key 0x{key[0]:02x}: {pt.decode('utf-8','replace')[:80]}")
def hash_identify():
section("HASH IDENTIFIER")
h = get_input("Hash string:").strip()
patterns = [
(32, 'MD5 / NTLM / LM'),
(40, 'SHA-1 / MySQL5 / Cisco-IOS'),
(56, 'SHA-224 / Haval-224'),
(64, 'SHA-256 / BLAKE2-256 / Keccak-256'),
(96, 'SHA-384'),
(128, 'SHA-512 / Whirlpool / BLAKE2-512'),
]
if all(c in string.hexdigits for c in h):
for length, name in patterns:
if len(h) == length:
ok(f"Likely hash type: {C.GREEN}{name}{C.RESET} (length={length})")
return
warn(f"Hex string of length {len(h)} — no common match")
elif h.startswith('$2'):
ok("bcrypt hash (length-agnostic)")
elif h.startswith('$6$'):
ok("SHA-512 crypt (Unix shadow)")
elif h.startswith('$1$'):
ok("MD5 crypt")
else:
warn("Not a pure hex hash — may be encoded or non-standard")
info(f"Hash length: {len(h)}")
def hash_brute():
section("HASH BRUTE FORCE (WORDLIST)")
target = get_input("Target hash:").strip().lower()
wordlist_path = get_input("Wordlist path:", "/usr/share/wordlists/rockyou.txt")
algo = get_input("Algorithm (md5/sha1/sha256/sha512):", "md5").lower()
hash_funcs = {
'md5': lambda w: hashlib.md5(w).hexdigest(),
'sha1': lambda w: hashlib.sha1(w).hexdigest(),
'sha256': lambda w: hashlib.sha256(w).hexdigest(),
'sha512': lambda w: hashlib.sha512(w).hexdigest(),
}
if algo not in hash_funcs:
err("Unsupported algorithm"); return
fn = hash_funcs[algo]
if not os.path.exists(wordlist_path):
err(f"Wordlist not found: {wordlist_path}")
wordlist_path = get_input("Try another path:")
if not os.path.exists(wordlist_path): return
info(f"Cracking {algo.upper()} hash: {target}")
start = time.time()
count = 0
try:
with open(wordlist_path, 'rb') as f:
for line in f:
word = line.strip()
count += 1
if fn(word) == target:
elapsed = time.time() - start
ok(f"CRACKED after {count} attempts ({elapsed:.2f}s)")
flag(word.decode('utf-8','replace'))
clip(word.decode('utf-8','replace'))
return
if count % 100000 == 0:
print(f"\r {C.DIM}Tried {count:,} words...{C.RESET}", end='', flush=True)
except KeyboardInterrupt:
print()
warn(f"Interrupted after {count:,} attempts")
warn("Hash not found in wordlist.")
def aes_ecb_analysis():
section("AES-ECB BLOCK ANALYSIS")
info("ECB mode encrypts identical 16-byte blocks identically — detect repetition.")
ct_hex = get_input("Ciphertext hex (or path to binary file):")
if os.path.exists(ct_hex):
with open(ct_hex, 'rb') as f:
ct = f.read()
else:
try:
ct = bytes.fromhex(ct_hex.replace(' ',''))
except:
ct = ct_hex.encode()
block_size = 16
blocks = [ct[i:i+block_size] for i in range(0, len(ct), block_size)]
block_counts = Counter(blocks)
duplicates = {b: c for b, c in block_counts.items() if c > 1}
info(f"Total blocks: {len(blocks)}")
if duplicates:
ok(f"ECB detected! {len(duplicates)} repeated block(s):")
for b, c in sorted(duplicates.items(), key=lambda x: -x[1]):
ok(f" Block {b.hex()} appears {c}× — positions: {[i for i,bl in enumerate(blocks) if bl==b]}")
else:
info("No repeated blocks found (not ECB, or no repeated plaintext blocks).")
if HAS_CRYPTO:
key = get_input("AES key (hex, or Enter to skip decryption):")
if key:
try:
k = bytes.fromhex(key.replace(' ',''))
cipher = AES.new(k, AES.MODE_ECB)
pt = cipher.decrypt(ct)
ok(f"Decrypted: {pt}")
try:
pt = unpad(pt, 16)
except: pass
flag(pt.decode('utf-8','replace'))
except Exception as ex:
err(f"Decryption failed: {ex}")
def padding_oracle_demo():
section("PADDING ORACLE — FRAMEWORK DEMO")
info("This is a local demo of the padding oracle byte-flipping logic.")
info("For real attacks, point TARGET_URL at the vulnerable endpoint.")
print(f"""
{C.CYAN}Padding Oracle Concept:{C.RESET}
┌──────────────────────────────────────────────────────┐
│ CBC decryption: P[i] = D(C[i]) XOR C[i-1] │
│ Flip C[i-1] to control P[i] │
│ Oracle tells you when padding is valid (0x01 ... ) │
│ │
│ For byte at position j (from end): │
│ 1. Brute 0x00-0xff for C'[j] │
│ 2. When oracle says VALID: D(C[j]) = 0x01 XOR C'[j] │
│ 3. P[j] = D(C[j]) XOR original C[j] │
└──────────────────────────────────────────────────────┘
{C.YELLOW}Quick-start with padbuster:{C.RESET}
padbuster http://TARGET/decrypt CIPHERTEXT_HEX 16 -encoding 0
{C.YELLOW}Python library:{C.RESET}
pip install cryptography
# Use PaddingOracle class from python-paddingoracle
""")
# ══════════════════════════════════════════════════════════════════════════════
# 3. REVERSE ENGINEERING TOOLS
# ══════════════════════════════════════════════════════════════════════════════
def re_menu():
while True:
c = menu("REVERSE ENGINEERING", [
"Static analysis — run all recon on a binary",
"String extractor — find flags & interesting strings",
"Disassemble function (objdump wrapper)",
"Patch binary — flip bytes / NOP a jump",
"Anti-debug checker (ptrace patterns)",
"ELF header parser",
"RE workflow checklist (interactive)",
])
if c == 0: break
elif c == 1: binary_recon()
elif c == 2: string_extractor()
elif c == 3: disassemble_fn()
elif c == 4: patch_binary()
elif c == 5: antidebug_check()
elif c == 6: elf_header()
elif c == 7: re_checklist()
def _run(cmd):
"""Run shell command, return stdout."""
try:
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=15)
return r.stdout + r.stderr
except Exception as ex:
return f"Error: {ex}"
def binary_recon():
section("BINARY RECON — FULL STATIC SWEEP")
path = get_input("Binary path:")
if not os.path.exists(path):
err(f"File not found: {path}"); return
checks = [
("File type", f"file '{path}'"),
("Size", f"wc -c '{path}'"),
("Shared libs", f"ldd '{path}' 2>/dev/null || echo '(not ELF or static)'"),
("Security flags", f"checksec --file='{path}' 2>/dev/null || python3 -c \""
"import struct,sys; d=open(sys.argv[1],'rb').read(); "
"print('NX:',d[0x47]==1 if len(d)>0x47 else '?')\" '{path}' 2>/dev/null"),
("Symbols (nm)", f"nm -D '{path}' 2>/dev/null | head -30"),
("Interesting strs",f"strings -a '{path}' | grep -Ei 'flag|ctf|key|pass|secret|win|admin|input|correct|wrong' | head -20"),
("Imports", f"objdump -d '{path}' 2>/dev/null | grep '<.*@plt>' | sort -u | head -20"),
("Sections", f"readelf -S '{path}' 2>/dev/null | head -30"),
]
for name, cmd in checks:
result = _run(cmd).strip()
if result:
print(f"\n {C.BOLD}{C.CYAN}── {name} ──{C.RESET}")
for line in result.split('\n')[:8]:
flag_hit = re.search(r'[A-Za-z_]{2,10}\{[^}]+\}', line)
color = C.GREEN if flag_hit else C.WHITE
print(f" {color}{line}{C.RESET}")
if flag_hit:
flag(flag_hit.group())
def string_extractor():
section("STRING EXTRACTOR")
path = get_input("Binary path:")
min_len = int(get_input("Min string length:", "4"))
pattern = get_input("Filter pattern (regex, or Enter for all):", "")
result = _run(f"strings -a -n {min_len} '{path}'")
lines = result.split('\n')
if pattern:
try:
lines = [l for l in lines if re.search(pattern, l, re.IGNORECASE)]
except:
pass
# Highlight flags
for line in lines:
flag_hit = re.search(r'[A-Za-z_]{2,10}\{[^}]+\}', line)
if flag_hit:
print(f" {C.GREEN}{C.BOLD}{line}{C.RESET}")
flag(flag_hit.group())
else:
print(f" {line}")
def disassemble_fn():
section("DISASSEMBLE FUNCTION")
path = get_input("Binary path:")
fn = get_input("Function name (e.g. main, check_flag):", "main")
out = _run(f"objdump -d -M intel '{path}' 2>/dev/null | awk '/<{fn}>:/,/^$/' | head -60")
if out.strip():
print(f"\n{C.CYAN}{out}{C.RESET}")
else:
warn(f"Function '{fn}' not found or objdump failed.")
info("Try: objdump -d -M intel binary | grep -A50 '<main>'")
def patch_binary():
section("BINARY PATCHER")
info("NOP out a jump instruction or change a byte value.")
path = get_input("Binary path:")
offset_str = get_input("Offset (hex, e.g. 0x1234):")
new_bytes_str = get_input("New bytes (hex, e.g. 9090 for NOP NOP):")
try:
offset = int(offset_str, 16)
new_bytes = bytes.fromhex(new_bytes_str.replace(' ',''))
out_path = path + ".patched"
with open(path, 'rb') as f:
data = bytearray(f.read())
old = data[offset:offset+len(new_bytes)]
info(f"Old bytes @ 0x{offset:x}: {old.hex()}")
data[offset:offset+len(new_bytes)] = new_bytes
with open(out_path, 'wb') as f:
f.write(data)
os.chmod(out_path, 0o755)
ok(f"Patched binary saved to: {out_path}")
ok(f"New bytes @ 0x{offset:x}: {new_bytes.hex()}")
except Exception as ex:
err(f"Patch failed: {ex}")
def antidebug_check():
section("ANTI-DEBUG CHECKER")
path = get_input("Binary path:")
info("Scanning for anti-debug patterns...")
patterns = {
"ptrace call": r"ptrace",
"IsDebuggerPresent": r"IsDebuggerPresent",
"PTRACE_TRACEME": r"PTRACE_TRACEME",
"getenv DEBUG": r"getenv.*DEBUG",
"timing check": r"gettimeofday|clock_gettime|RDTSC",
"proc/self/status": r"/proc/self/status",
"parent PID check": r"getppid",
}
found = False
strs = _run(f"strings -a '{path}'")
asm = _run(f"objdump -d '{path}' 2>/dev/null")
for name, pat in patterns.items():
if re.search(pat, strs + asm, re.IGNORECASE):
warn(f"DETECTED: {name}")
found = True
if not found:
ok("No obvious anti-debug patterns detected.")
else:
info("Bypass hints:")
info(" strace ./binary 2>&1 | grep ptrace")
info(" GDB: set follow-fork-mode child")
info(" Patch ptrace call to NOP (use Binary Patcher above)")
def elf_header():
section("ELF HEADER PARSER")
path = get_input("ELF binary path:")
try:
with open(path, 'rb') as f:
data = f.read(64)
if data[:4] != b'\x7fELF':
warn("Not an ELF file.")
return
ei_class = {1:'32-bit', 2:'64-bit'}.get(data[4], '?')
ei_data = {1:'little-endian', 2:'big-endian'}.get(data[5], '?')
ei_type = {1:'REL',2:'EXEC',3:'DYN',4:'CORE'}.get(struct.unpack_from('<H',data,16)[0],'?')
ei_machine= {0x3e:'x86-64', 0x28:'ARM', 0xb7:'AArch64', 3:'x86'}.get(struct.unpack_from('<H',data,18)[0],'?')
ei_entry = struct.unpack_from('<Q' if ei_class=='64-bit' else '<I', data, 24)[0]
print(f"""
Class: {C.GREEN}{ei_class}{C.RESET}
Encoding: {C.GREEN}{ei_data}{C.RESET}
Type: {C.GREEN}{ei_type}{C.RESET}
Machine: {C.GREEN}{ei_machine}{C.RESET}
Entry: {C.GREEN}0x{ei_entry:016x}{C.RESET}
""")
except Exception as ex:
err(f"Error: {ex}")
info("Try: readelf -h binary")
def re_checklist():
section("RE WORKFLOW CHECKLIST")
steps = [
("File ID", "file ./binary && xxd binary | head -2"),
("Strings", "strings -a binary | grep -Ei 'flag|key|pass|ctf|win|correct'"),
("Symbols", "nm -D binary 2>/dev/null; readelf -s binary 2>/dev/null"),
("Shared libs", "ldd binary"),
("Imports", "objdump -d binary | grep '<.*@plt>' | sort -u"),
("Entry / main", "objdump -d -M intel binary | awk '/<main>:/,/^$/'"),
("Ghidra static", "Import → Auto-analyze → Find main() → Decompile → Rename vars"),
("GDB dynamic", "gdb ./binary → break main → run → ni/si through key logic"),
("Anti-debug", "strace ./binary 2>&1 | grep ptrace"),
("Patch if needed","Binary patcher: NOP comparison jumps or return-value fixup"),
]
for i, (name, cmd) in enumerate(steps, 1):
input(f" {C.CYAN}[{i:2}/{len(steps)}] {name:20}{C.RESET} {C.DIM}(press Enter){C.RESET}")
print(f" {C.YELLOW}→ {cmd}{C.RESET}")
ok("Checklist complete!")
# ══════════════════════════════════════════════════════════════════════════════
# 4. WEB EXPLOITATION
# ══════════════════════════════════════════════════════════════════════════════
def web_menu():
while True:
c = menu("WEB EXPLOITATION", [
"SQLi — Tester (error / boolean / time-based)",
"XSS — Payload generator",