-
Notifications
You must be signed in to change notification settings - Fork 376
Expand file tree
/
Copy pathwebui.py
More file actions
2993 lines (2510 loc) · 119 KB
/
Copy pathwebui.py
File metadata and controls
2993 lines (2510 loc) · 119 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
"""
STEGOSAURUS WRECKS - NiceGUI Web Interface
Ultimate steganography suite with hacker aesthetic
Run with: python webui.py
"""
from nicegui import ui, app
from fastapi import Request
from fastapi.responses import JSONResponse
from PIL import Image
import io
import base64
import tempfile
import os
from pathlib import Path
from typing import Optional
import asyncio
import json
# Import our steg modules
import steg_core
from steg_core import (
encode, decode, create_config, calculate_capacity,
analyze_image, detect_encoding, CHANNEL_PRESETS,
Channel, StegConfig, EncodingStrategy, _extract_bit_units,
_bits_array_to_bytes, _generate_pixel_indices
)
import crypto
import numpy as np
import re
import string
# ============== THEME / STYLING ==============
DARK_CSS = """
:root {
--primary: #00ff41;
--primary-dim: #00aa2a;
--primary-glow: rgba(0, 255, 65, 0.4);
--secondary: #00d4ff;
--accent: #ff00ff;
--warning: #ffd000;
--error: #ff3333;
--bg-dark: #0a0a0a;
--bg-card: #0d1117;
--bg-hover: #161b22;
--text: #00ff41;
--text-dim: #555;
--border: #30363d;
}
body {
background: var(--bg-dark) !important;
font-family: 'JetBrains Mono', 'Fira Code', 'Courier New', monospace !important;
}
.q-card {
background: var(--bg-card) !important;
border: 1px solid var(--border) !important;
}
.nicegui-content {
background: var(--bg-dark) !important;
}
/* Matrix scanline effect - subtler */
.matrix-bg {
background: repeating-linear-gradient(
0deg,
transparent,
transparent 2px,
rgba(0, 255, 65, 0.015) 2px,
rgba(0, 255, 65, 0.015) 4px
);
pointer-events: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
}
/* Glow effect for headers */
.glow {
text-shadow: 0 0 10px var(--primary), 0 0 20px var(--primary-glow);
}
/* Cyber border animation */
@keyframes border-pulse {
0%, 100% { border-color: var(--primary); box-shadow: 0 0 5px var(--primary-glow); }
50% { border-color: var(--secondary); box-shadow: 0 0 15px rgba(0, 212, 255, 0.3); }
}
@keyframes glow-pulse {
0%, 100% { opacity: 0.6; }
50% { opacity: 1; }
}
.cyber-border {
border: 1px solid var(--primary) !important;
animation: border-pulse 3s infinite;
}
/* Status indicators */
.status-success { color: var(--primary) !important; }
.status-error { color: var(--error) !important; }
.status-warning { color: var(--warning) !important; }
.status-info { color: var(--secondary) !important; }
/* Custom scrollbar */
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--bg-dark); }
::-webkit-scrollbar-thumb { background: var(--primary-dim); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--primary); }
/* File upload area - MODERNIZED */
.drop-zone {
border: 1px solid var(--border) !important;
background: linear-gradient(135deg, rgba(0, 255, 65, 0.03) 0%, rgba(0, 212, 255, 0.03) 100%) !important;
transition: all 0.3s ease;
padding: 16px;
text-align: center;
cursor: pointer;
border-radius: 8px;
position: relative;
overflow: hidden;
}
.drop-zone::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(0, 255, 65, 0.1), transparent);
transition: left 0.5s ease;
}
.drop-zone:hover {
border-color: var(--primary) !important;
background: linear-gradient(135deg, rgba(0, 255, 65, 0.08) 0%, rgba(0, 212, 255, 0.05) 100%) !important;
box-shadow: 0 0 20px rgba(0, 255, 65, 0.15), inset 0 0 30px rgba(0, 255, 65, 0.05);
}
.drop-zone:hover::before {
left: 100%;
}
/* Terminal style output */
.terminal {
background: #000 !important;
border: 1px solid var(--border) !important;
font-family: 'JetBrains Mono', monospace !important;
color: var(--primary) !important;
padding: 16px !important;
white-space: pre-wrap;
overflow-x: auto;
border-radius: 6px;
}
/* Button overrides for cooler look */
.q-btn {
text-transform: uppercase !important;
letter-spacing: 1px !important;
font-weight: 600 !important;
}
/* Input fields */
.q-field--dark .q-field__control {
background: var(--bg-card) !important;
border: 1px solid var(--border) !important;
border-radius: 6px !important;
}
.q-field--dark .q-field__control:hover {
border-color: var(--primary-dim) !important;
}
.q-field--focused .q-field__control {
border-color: var(--primary) !important;
box-shadow: 0 0 10px var(--primary-glow) !important;
}
/* Select dropdowns */
.q-menu {
background: var(--bg-card) !important;
border: 1px solid var(--border) !important;
}
/* Tabs styling */
.q-tab--active {
color: var(--primary) !important;
text-shadow: 0 0 10px var(--primary-glow);
}
.q-tab:hover {
color: var(--secondary) !important;
}
/* Switches */
.q-toggle__track {
background: var(--border) !important;
}
.q-toggle--active .q-toggle__track {
background: var(--primary-dim) !important;
}
/* Image preview container */
.image-preview {
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
background: #000;
}
/* Stats/info boxes */
.info-box {
background: linear-gradient(135deg, var(--bg-card) 0%, var(--bg-hover) 100%);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
}
.info-box:hover {
border-color: var(--primary-dim);
}
/* Section headers */
.section-header {
font-size: 14px;
font-weight: 700;
letter-spacing: 2px;
text-transform: uppercase;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.section-header::after {
content: '';
flex: 1;
height: 1px;
background: linear-gradient(90deg, var(--border), transparent);
}
/* Capacity meter */
.capacity-meter {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 6px;
padding: 12px;
margin: 8px 0;
}
.capacity-bar-outer {
background: var(--bg-dark);
border-radius: 4px;
height: 6px;
overflow: hidden;
margin: 8px 0;
}
.capacity-bar-inner {
height: 100%;
border-radius: 4px;
transition: width 0.3s ease, background 0.3s ease;
}
/* Notification styling */
.q-notification {
background: var(--bg-card) !important;
border: 1px solid var(--border) !important;
}
/* 🪆 MATRYOSHKA MODE - Easter egg activation zone (stealth) */
.matryoshka-trigger {
position: fixed;
bottom: 0;
left: 0;
width: 12px;
height: 12px;
z-index: 99999;
opacity: 0;
background: transparent;
pointer-events: auto !important;
}
.matryoshka-trigger:hover {
opacity: 0;
}
/* Matryoshka mode indicator */
.matryoshka-active {
animation: matryoshka-glow 2s ease-in-out infinite;
}
@keyframes matryoshka-glow {
0%, 100% { box-shadow: 0 0 5px #ff00ff, 0 0 10px #ff00ff; }
50% { box-shadow: 0 0 20px #ff00ff, 0 0 40px #ff00ff, 0 0 60px #ff00ff; }
}
/* Nested results tree styling */
.matryoshka-tree {
font-family: monospace;
padding: 12px;
background: #000;
border: 1px solid var(--accent);
border-radius: 6px;
}
.matryoshka-layer {
padding-left: 20px;
border-left: 2px solid var(--accent);
margin-left: 10px;
}
.matryoshka-layer-0 { border-color: #ff00ff; }
.matryoshka-layer-1 { border-color: #ff66ff; }
.matryoshka-layer-2 { border-color: #ff99ff; }
.matryoshka-layer-3 { border-color: #ffccff; }
"""
BANNER_ASCII = """
███████╗████████╗███████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗
██╔════╝╚══██╔══╝██╔════╝██╔════╝ ██╔═══██╗██╔════╝██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝
███████╗ ██║ █████╗ ██║ ███╗██║ ██║███████╗███████║██║ ██║██████╔╝██║ ██║███████╗
╚════██║ ██║ ██╔══╝ ██║ ██║██║ ██║╚════██║██╔══██║██║ ██║██╔══██╗██║ ██║╚════██║
███████║ ██║ ███████╗╚██████╔╝╚██████╔╝███████║██║ ██║╚██████╔╝██║ ██║╚██████╔╝███████║
╚══════╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝
W R E C K S v3.0
"""
STEGO_ASCII = """
__
/ '-.
/ .-. | STEGOSAURUS
/.' \\| WRECKS
// |\\ \\
|| | \\ | >> LSB Suite <<
/|| | \\ |
/ ||__/ \\/
\\ --' |\\_\\
'._____.' \\/
"""
# ============== STATE MANAGEMENT ==============
class AppState:
"""Global application state"""
def __init__(self):
# Encode state
self.carrier_image: Optional[Image.Image] = None
self.carrier_path: Optional[str] = None
self.encoded_image: Optional[Image.Image] = None
self.encode_file_data: Optional[bytes] = None
self.encode_file_name: Optional[str] = None
self.encode_result: Optional[Image.Image] = None
# Decode state
self.decode_image: Optional[Image.Image] = None
self.detected_config: Optional[dict] = None
self.extracted_file: Optional[bytes] = None
self.extracted_filename: Optional[str] = None
# Analyze state
self.analyze_image: Optional[Image.Image] = None
# General
self.advanced_mode: bool = False
self.capacity_info: dict = {}
# UI state - track active tab across reloads
self.active_tab: str = 'encode'
# 🪆 MATRYOSHKA MODE - Russian nesting doll steganography
self.matryoshka_mode: bool = False
self.matryoshka_depth: int = 3 # Default depth (1-11)
# Store nested decode results
self.matryoshka_results: list = []
# Matryoshka encoding - carrier images (outermost first)
self.matryoshka_carriers: list = [] # List of (Image, filename) tuples
self.matryoshka_encode_result: Optional[Image.Image] = None
state = AppState()
def generate_blank_image(width: int = 1024, height: int = 1024, color: str = 'noise') -> Image.Image:
"""Generate a blank or noise image for steganography"""
import numpy as np
if color == 'noise':
# Random noise - best for hiding data
pixels = np.random.randint(0, 256, (height, width, 4), dtype=np.uint8)
pixels[:, :, 3] = 255 # Full alpha
return Image.fromarray(pixels, 'RGBA')
elif color == 'black':
return Image.new('RGBA', (width, height), (0, 0, 0, 255))
elif color == 'white':
return Image.new('RGBA', (width, height), (255, 255, 255, 255))
else:
# Gradient - looks nicer
pixels = np.zeros((height, width, 4), dtype=np.uint8)
for y in range(height):
for x in range(width):
pixels[y, x] = [
int(255 * x / width),
int(255 * y / height),
128,
255
]
return Image.fromarray(pixels, 'RGBA')
# ============== HELPER FUNCTIONS ==============
def image_to_base64(img: Image.Image, format: str = "PNG") -> str:
"""Convert PIL Image to base64 string for display"""
buffer = io.BytesIO()
img.save(buffer, format=format)
return base64.b64encode(buffer.getvalue()).decode()
def base64_to_image(b64: str) -> Image.Image:
"""Convert base64 string to PIL Image"""
# Handle data URL format
if ',' in b64:
b64 = b64.split(',')[1]
data = base64.b64decode(b64)
return Image.open(io.BytesIO(data))
def format_size(size_bytes: int) -> str:
"""Format bytes to human readable"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.1f} TB"
# ============== SMART DECODE / APERI'SOLVE STYLE ==============
def detect_coherent_text(data: bytes, min_printable_ratio: float = 0.85) -> dict:
"""
Detect if data looks like coherent readable text.
Returns analysis dict with confidence and detected text preview.
Properly handles Unicode text, not just ASCII.
"""
if not data or len(data) == 0:
return {"is_text": False, "confidence": 0, "preview": "", "reason": "empty"}
# Try UTF-8 decode
try:
text = data.decode('utf-8', errors='strict')
except:
try:
text = data.decode('latin-1', errors='replace')
except:
return {"is_text": False, "confidence": 0, "preview": "", "reason": "decode_failed"}
if len(text) == 0:
return {"is_text": False, "confidence": 0, "preview": "", "reason": "empty_text"}
# Calculate printable character ratio - Unicode aware
# Count chars that are NOT control characters as printable
# Control chars: 0x00-0x1F (except \t, \n, \r), 0x7F, 0x80-0x9F
def is_printable_unicode(c):
code = ord(c)
# Whitespace is fine
if c in '\t\n\r ':
return True
# ASCII control chars
if code <= 0x1F or code == 0x7F:
return False
# C1 control chars
if 0x80 <= code <= 0x9F:
return False
# Everything else (printable ASCII, Latin-1 supplement, Unicode) is OK
return True
printable_count = sum(1 for c in text[:500] if is_printable_unicode(c))
printable_ratio = printable_count / min(len(text), 500)
# Check for null bytes in first 100 chars (binary indicator)
null_count = text[:100].count('\x00')
has_nulls = null_count > 2
# Check for common words (English)
common_words = ['the', 'and', 'is', 'in', 'to', 'of', 'a', 'for', 'on', 'that',
'this', 'with', 'are', 'be', 'as', 'at', 'by', 'or', 'an', 'it',
'from', 'was', 'have', 'has', 'not', 'but', 'what', 'all', 'were',
'flag', 'ctf', 'secret', 'hidden', 'password', 'key', 'message']
text_lower = text.lower()
word_matches = sum(1 for w in common_words if w in text_lower)
# Check for repeated patterns (often indicates noise)
is_repetitive = False
if len(text) > 20:
first_20 = text[:20]
repetition = text.count(first_20)
is_repetitive = repetition > 2
# Calculate entropy (lower = more structured/text-like)
char_freq = {}
for c in text[:500]: # Sample first 500 chars
char_freq[c] = char_freq.get(c, 0) + 1
total = sum(char_freq.values())
entropy = -sum((f/total) * np.log2(f/total) for f in char_freq.values() if f > 0)
# Score calculation
confidence = 0
# Printable ratio is crucial
if printable_ratio >= 0.95:
confidence += 40
elif printable_ratio >= 0.85:
confidence += 25
elif printable_ratio >= 0.70:
confidence += 10
# Word matches boost confidence
confidence += min(30, word_matches * 5)
# Low entropy (structured text) is good
if entropy < 4.5:
confidence += 15
elif entropy < 5.5:
confidence += 5
# Penalties
if has_nulls:
confidence -= 30
if len(text) > 20 and is_repetitive:
confidence -= 20
# Clean preview - keep Unicode, only replace control chars
preview_text = text[:200]
preview_clean = ''.join(c if is_printable_unicode(c) else '·' for c in preview_text)
is_text = confidence >= 35 and printable_ratio >= min_printable_ratio
return {
"is_text": is_text,
"confidence": max(0, min(100, confidence)),
"preview": preview_clean,
"printable_ratio": printable_ratio,
"entropy": entropy,
"word_matches": word_matches,
"reason": "looks_like_text" if is_text else "binary_data"
}
def extract_raw_lsb(image: Image.Image, channels: list, bits: int = 1,
bit_offset: int = 0, max_bytes: int = 4096,
strategy: EncodingStrategy = EncodingStrategy.INTERLEAVED,
seed: int = None) -> bytes:
"""
Extract raw LSB data without requiring STEG header.
For blind extraction like Aperi'Solve does.
Args:
image: PIL Image to extract from
channels: List of Channel enums to extract from
bits: Bits per channel (1-8)
bit_offset: Bit offset within each channel
max_bytes: Maximum bytes to extract
strategy: Encoding strategy used (SEQUENTIAL, INTERLEAVED, SPREAD, RANDOMIZED)
seed: Random seed for RANDOMIZED strategy
"""
img = image.convert("RGBA")
pixels = np.array(img, dtype=np.uint8)
height, width = pixels.shape[:2]
total_pixels = height * width
flat_pixels = pixels.reshape(-1, 4)
# Create simple extraction config
channel_indices = np.array([c.value for c in channels], dtype=np.uint8)
num_channels = len(channels)
# Calculate how many units we need
bits_needed = max_bytes * 8
units_needed = bits_needed // bits
if bits_needed % bits:
units_needed += 1
bit_mask = ((1 << bits) - 1) << bit_offset
result = np.zeros(units_needed, dtype=np.uint8)
if strategy == EncodingStrategy.INTERLEAVED:
# Cycle through channels at each pixel
pixels_needed = (units_needed + num_channels - 1) // num_channels
pixel_indices = _generate_pixel_indices(total_pixels, min(pixels_needed, total_pixels), strategy, seed)
unit_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if unit_idx >= units_needed:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= units_needed:
break
elif strategy == EncodingStrategy.SEQUENTIAL:
# Fill each channel completely before moving to next
unit_idx = 0
for ch in channel_indices:
pixels_for_channel = min(total_pixels, units_needed - unit_idx)
pixel_indices = _generate_pixel_indices(total_pixels, pixels_for_channel, strategy, seed)
for pix_idx in pixel_indices:
if unit_idx >= units_needed:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= units_needed:
break
elif strategy == EncodingStrategy.SPREAD:
# Spread evenly across image
pixels_needed = (units_needed + num_channels - 1) // num_channels
pixel_indices = _generate_pixel_indices(total_pixels, min(pixels_needed, total_pixels), strategy, seed)
unit_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if unit_idx >= units_needed:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= units_needed:
break
elif strategy == EncodingStrategy.RANDOMIZED:
# Pseudo-random order (seeded for reproducibility)
pixels_needed = (units_needed + num_channels - 1) // num_channels
pixel_indices = _generate_pixel_indices(total_pixels, min(pixels_needed, total_pixels), strategy, seed or 42)
unit_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if unit_idx >= units_needed:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= units_needed:
break
# Convert to bytes
return _bits_array_to_bytes(result, bits, bits_needed)[:max_bytes]
def smart_scan_image(image: Image.Image, password: str = None) -> list:
"""
Aperi'Solve-style multi-config scan.
Tries multiple channel/bit/strategy combinations and reports findings.
"""
results = []
# Base channel/bit configurations (ordered by likelihood)
base_configs = [
# Common single channels - 1 bit
{"name": "R", "channels": [Channel.R], "bits": 1},
{"name": "G", "channels": [Channel.G], "bits": 1},
{"name": "B", "channels": [Channel.B], "bits": 1},
{"name": "A", "channels": [Channel.A], "bits": 1},
# Common single channels - 2 bit
{"name": "R-2bit", "channels": [Channel.R], "bits": 2},
{"name": "G-2bit", "channels": [Channel.G], "bits": 2},
{"name": "B-2bit", "channels": [Channel.B], "bits": 2},
{"name": "A-2bit", "channels": [Channel.A], "bits": 2},
# RGB combos - 1 and 2 bit
{"name": "RGB", "channels": [Channel.R, Channel.G, Channel.B], "bits": 1},
{"name": "RGB-2bit", "channels": [Channel.R, Channel.G, Channel.B], "bits": 2},
# RGBA - 1 and 2 bit
{"name": "RGBA", "channels": [Channel.R, Channel.G, Channel.B, Channel.A], "bits": 1},
{"name": "RGBA-2bit", "channels": [Channel.R, Channel.G, Channel.B, Channel.A], "bits": 2},
# Two channel combos - 1 bit
{"name": "RG", "channels": [Channel.R, Channel.G], "bits": 1},
{"name": "RB", "channels": [Channel.R, Channel.B], "bits": 1},
{"name": "GB", "channels": [Channel.G, Channel.B], "bits": 1},
{"name": "RA", "channels": [Channel.R, Channel.A], "bits": 1},
{"name": "GA", "channels": [Channel.G, Channel.A], "bits": 1},
{"name": "BA", "channels": [Channel.B, Channel.A], "bits": 1},
# Two channel combos - 2 bit
{"name": "RG-2bit", "channels": [Channel.R, Channel.G], "bits": 2},
{"name": "RB-2bit", "channels": [Channel.R, Channel.B], "bits": 2},
{"name": "GB-2bit", "channels": [Channel.G, Channel.B], "bits": 2},
{"name": "RA-2bit", "channels": [Channel.R, Channel.A], "bits": 2},
{"name": "GA-2bit", "channels": [Channel.G, Channel.A], "bits": 2},
{"name": "BA-2bit", "channels": [Channel.B, Channel.A], "bits": 2},
# Higher bit depths (4-bit)
{"name": "R-4bit", "channels": [Channel.R], "bits": 4},
{"name": "RGB-4bit", "channels": [Channel.R, Channel.G, Channel.B], "bits": 4},
]
# All encoding strategies to try
strategies_to_try = [
{"name": "interleaved", "strategy": EncodingStrategy.INTERLEAVED},
{"name": "sequential", "strategy": EncodingStrategy.SEQUENTIAL},
{"name": "spread", "strategy": EncodingStrategy.SPREAD},
{"name": "randomized", "strategy": EncodingStrategy.RANDOMIZED},
]
# Generate all combinations of base configs and strategies
configs_to_try = []
for base in base_configs:
for strat in strategies_to_try:
# Interleaved is default, so omit suffix for cleaner names
if strat["strategy"] == EncodingStrategy.INTERLEAVED:
name = base["name"]
else:
name = f"{base['name']}-{strat['name']}"
configs_to_try.append({
"name": name,
"channels": base["channels"],
"bits": base["bits"],
"strategy": strat["strategy"],
})
# First check for STEG header (our own format)
detection = detect_encoding(image)
if detection:
results.append({
"name": f"STEG-HEADER ({detection['config']['channels']})",
"channels": detection['config']['channels'],
"bits": detection['config']['bits_per_channel'],
"has_header": True,
"is_text": True,
"confidence": 95,
"preview": f"[STEG v3 detected - {format_size(detection['original_length'])}]",
"payload_size": detection['original_length'],
"status": "STEG_DETECTED",
"can_decode": True,
})
# Scan each config
for cfg in configs_to_try:
try:
raw_data = extract_raw_lsb(
image,
channels=cfg["channels"],
bits=cfg["bits"],
max_bytes=2048, # Sample first 2KB
strategy=cfg["strategy"]
)
# Check for STEG magic at start
has_magic = raw_data[:4] == b'STEG'
# Decrypt if password provided
data_to_check = raw_data
if password and not has_magic:
try:
data_to_check = crypto.decrypt(raw_data, password)
except:
pass # Decryption failed, use raw
# Analyze for coherent text
text_analysis = detect_coherent_text(data_to_check)
# Determine status
if has_magic:
status = "STEG_HEADER"
elif text_analysis["is_text"] and text_analysis["confidence"] >= 50:
status = "TEXT_FOUND"
elif text_analysis["is_text"]:
status = "POSSIBLE_TEXT"
elif text_analysis["printable_ratio"] > 0.5:
status = "MIXED_DATA"
else:
status = "BINARY/NOISE"
results.append({
"name": cfg["name"],
"channels": [c.name for c in cfg["channels"]],
"bits": cfg["bits"],
"strategy": cfg["strategy"].value,
"has_header": has_magic,
"is_text": text_analysis["is_text"],
"confidence": text_analysis["confidence"],
"preview": text_analysis["preview"][:100] if text_analysis["preview"] else raw_data[:50].hex(),
"printable_ratio": text_analysis.get("printable_ratio", 0),
"entropy": text_analysis.get("entropy", 8),
"status": status,
"can_decode": has_magic or text_analysis["is_text"],
"raw_data": raw_data if (has_magic or text_analysis["confidence"] >= 30) else None,
})
except Exception as e:
results.append({
"name": cfg["name"],
"channels": [c.name for c in cfg["channels"]],
"bits": cfg["bits"],
"strategy": cfg["strategy"].value,
"has_header": False,
"is_text": False,
"confidence": 0,
"preview": f"Error: {str(e)[:50]}",
"status": "ERROR",
"can_decode": False,
})
# Sort by confidence (highest first), then by whether text was found
results.sort(key=lambda x: (
x.get("has_header", False), # STEG headers first
x.get("status") == "TEXT_FOUND",
x.get("confidence", 0)
), reverse=True)
return results
# ============== 🪆 MATRYOSHKA MODE - RECURSIVE STEG ==============
def is_image_data(data: bytes) -> bool:
"""Check if bytes look like an image file"""
if len(data) < 8:
return False
# PNG magic bytes
if data[:8] == b'\x89PNG\r\n\x1a\n':
return True
# JPEG magic bytes
if data[:2] == b'\xff\xd8':
return True
# GIF magic bytes
if data[:6] in (b'GIF87a', b'GIF89a'):
return True
# BMP magic bytes
if data[:2] == b'BM':
return True
return False
# Valid file extensions for file format detection
VALID_FILE_EXTENSIONS = {
# Images
'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'ico', 'svg', 'tiff', 'tif',
# Documents
'txt', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'rtf',
# Code
'py', 'js', 'ts', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'md', 'csv',
'java', 'c', 'cpp', 'h', 'hpp', 'rs', 'go', 'rb', 'php', 'sh', 'bash',
# Archives
'zip', 'tar', 'gz', 'bz2', '7z', 'rar',
# Media
'mp3', 'mp4', 'wav', 'avi', 'mkv', 'mov', 'flac', 'ogg',
# Other
'bin', 'dat', 'exe', 'dll', 'so', 'key', 'pem', 'crt',
}
def extract_file_from_data(data: bytes) -> tuple:
"""
Extract filename and file data from encoded bytes.
Returns (filename, file_data) or (None, data) if not a file format.
File format: <length_byte><filename><file_data>
Where length_byte is the length of the filename (1-100 bytes).
"""
if len(data) < 3:
return (None, data)
fname_len = data[0]
# Filename length must be reasonable (3-100 chars for "a.b" to reasonable max)
if fname_len < 3 or fname_len > 100:
return (None, data)
# Must have enough data for filename + at least 1 byte of content
if len(data) < fname_len + 2:
return (None, data)
try:
filename = data[1:1+fname_len].decode('utf-8')
except UnicodeDecodeError:
return (None, data)
# Validate filename structure
if '.' not in filename:
return (None, data)
# Check for invalid characters (only allow alphanumeric, ., -, _, space)
if not re.match(r'^[\w\-. ]+$', filename):
return (None, data)
# Filename must not start with . or space
if filename[0] in '. ':
return (None, data)
# Extract and validate extension
ext = filename.rsplit('.', 1)[-1].lower()
if ext not in VALID_FILE_EXTENSIONS:
return (None, data)
# All checks passed - this looks like a real file
file_data = data[1+fname_len:]
return (filename, file_data)
def matryoshka_decode(image: Image.Image, max_depth: int = 3, password: str = None,
current_depth: int = 0) -> list:
"""
🪆 Recursively decode nested steganographic images.
Args:
image: The image to decode
max_depth: Maximum recursion depth (1-11)
password: Optional decryption password
current_depth: Current recursion level (internal)
Returns:
List of extraction results at each layer
"""
results = []
layer_info = {
"depth": current_depth,
"type": "unknown",
"filename": None,
"data_size": 0,
"preview": "",
"has_nested": False,
"nested_results": [],
}
if current_depth >= max_depth:
layer_info["type"] = "max_depth_reached"
layer_info["preview"] = f"⚠️ Max depth ({max_depth}) reached"
results.append(layer_info)
return results
try:
# Try auto-decode first (looks for STEG header)
try:
data = decode(image, None)
layer_info["type"] = "steg_header"
except:
# If no STEG header, try smart scan
scan_results = smart_scan_image(image, password)
best_result = None
for r in scan_results:
if r.get("status") in ["STEG_DETECTED", "STEG_HEADER", "TEXT_FOUND"]:
best_result = r
break
if best_result and best_result.get("raw_data"):
data = best_result["raw_data"]
layer_info["type"] = f"smart_scan_{best_result['name']}"
else:
layer_info["type"] = "no_data_found"
layer_info["preview"] = "No hidden data detected"
results.append(layer_info)
return results
# Decrypt if password provided
if password:
try:
data = crypto.decrypt(data, password)
except:
pass # Decryption failed, use raw data
layer_info["data_size"] = len(data)
# Check if it's a file
filename, file_data = extract_file_from_data(data)
if filename:
layer_info["filename"] = filename
layer_info["data_size"] = len(file_data)
# Check if the extracted file is an image
if is_image_data(file_data):
layer_info["type"] = "nested_image"
layer_info["has_nested"] = True
# Recursively decode the nested image
try:
nested_img = Image.open(io.BytesIO(file_data))
nested_results = matryoshka_decode(
nested_img,
max_depth=max_depth,
password=password,
current_depth=current_depth + 1
)
layer_info["nested_results"] = nested_results
layer_info["preview"] = f"🪆 Found nested image: {filename}"
except Exception as e:
layer_info["preview"] = f"📁 Image file: {filename} (failed to recurse: {e})"
else:
layer_info["type"] = "file"
# Try to show preview of text files
ext = filename.split('.')[-1].lower() if '.' in filename else ''
if ext in ['txt', 'md', 'json', 'xml', 'html', 'css', 'js', 'py', 'csv']:
try:
layer_info["preview"] = file_data[:200].decode('utf-8')