forked from elder-plinius/ST3GG
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis_tools.py
More file actions
2703 lines (2256 loc) · 93.3 KB
/
analysis_tools.py
File metadata and controls
2703 lines (2256 loc) · 93.3 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
"""
STEGOSAURUS WRECKS - Comprehensive Analysis Tools
Complete toolkit for steganography detection across all file types
This module provides 264+ analysis functions covering:
- Images: PNG, JPEG, GIF, BMP, WebP, TIFF, ICO, HEIC, AVIF, SVG
- Audio: WAV, MP3, FLAC, OGG
- Video: AVI, MKV
- Documents: PDF, Office
- Archives: ZIP, RAR
- Fonts: TTF, OTF, WOFF
"""
import struct
import zlib
import io
import re
import json
import hashlib
import binascii
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple, Union, BinaryIO
from dataclasses import dataclass, field
from enum import Enum
import math
# Optional imports - gracefully handle missing dependencies
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
try:
from PIL import Image, ExifTags
HAS_PIL = True
except ImportError:
HAS_PIL = False
# ============== CORE INFRASTRUCTURE ==============
@dataclass
class AnalysisResult:
"""Standard result format for all analysis functions"""
success: bool
action: str
file_type: str
data: Dict[str, Any] = field(default_factory=dict)
findings: List[str] = field(default_factory=list)
suspicious: bool = False
confidence: float = 0.0
raw_data: Optional[bytes] = None
error: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
return {
"success": self.success,
"action": self.action,
"file_type": self.file_type,
"data": self.data,
"findings": self.findings,
"suspicious": self.suspicious,
"confidence": self.confidence,
"has_raw_data": self.raw_data is not None,
"error": self.error
}
class FileType(Enum):
PNG = "png"
JPEG = "jpeg"
GIF = "gif"
BMP = "bmp"
WEBP = "webp"
TIFF = "tiff"
ICO = "ico"
HEIC = "heic"
AVIF = "avif"
SVG = "svg"
WAV = "wav"
MP3 = "mp3"
FLAC = "flac"
OGG = "ogg"
AVI = "avi"
MKV = "mkv"
PDF = "pdf"
OFFICE = "office"
ZIP = "zip"
RAR = "rar"
FONT = "font"
AIFF = "aiff"
AU = "au"
MIDI = "midi"
PCAP = "pcap"
SQLITE = "sqlite"
GZIP = "gzip"
TAR = "tar"
UNKNOWN = "unknown"
# Magic bytes for file type detection
MAGIC_SIGNATURES = {
b'\x89PNG\r\n\x1a\n': FileType.PNG,
b'\xff\xd8\xff': FileType.JPEG,
b'GIF87a': FileType.GIF,
b'GIF89a': FileType.GIF,
b'BM': FileType.BMP,
b'RIFF': FileType.WAV, # Could also be AVI - check further
b'\xff\xfb': FileType.MP3,
b'\xff\xfa': FileType.MP3,
b'\xff\xf3': FileType.MP3,
b'\xff\xf2': FileType.MP3,
b'ID3': FileType.MP3,
b'fLaC': FileType.FLAC,
b'OggS': FileType.OGG,
b'%PDF': FileType.PDF,
b'PK\x03\x04': FileType.ZIP, # Could be Office - check further
b'Rar!\x1a\x07': FileType.RAR,
b'\x1aE\xdf\xa3': FileType.MKV,
b'\x00\x00\x01\x00': FileType.ICO,
b'\x00\x00\x02\x00': FileType.ICO, # CUR format
b'\x1f\x8b': FileType.GZIP,
b'MThd': FileType.MIDI,
b'.snd': FileType.AU,
b'\xa1\xb2\xc3\xd4': FileType.PCAP,
b'\xd4\xc3\xb2\xa1': FileType.PCAP, # Little-endian PCAP
b'SQLite format 3': FileType.SQLITE,
}
WEBP_SIGNATURES = [b'WEBP']
HEIC_SIGNATURES = [b'ftyp', b'heic', b'heix', b'hevc', b'mif1']
AVIF_SIGNATURES = [b'ftypavif', b'ftypavis']
def detect_file_type(data: bytes) -> FileType:
"""Detect file type from magic bytes"""
if len(data) < 12:
return FileType.UNKNOWN
# Check standard signatures
for magic, ftype in MAGIC_SIGNATURES.items():
if data.startswith(magic):
# Special handling for RIFF container
if magic == b'RIFF' and len(data) >= 12:
if data[8:12] == b'WAVE':
return FileType.WAV
elif data[8:12] == b'AVI ':
return FileType.AVI
elif data[8:12] == b'WEBP':
return FileType.WEBP
# Special handling for ZIP-based formats
elif magic == b'PK\x03\x04':
# Check if it's an Office document
if b'[Content_Types].xml' in data[:2000] or b'word/' in data[:2000] or b'xl/' in data[:2000] or b'ppt/' in data[:2000]:
return FileType.OFFICE
return FileType.ZIP
return ftype
# Check for HEIC/AVIF (ftyp box)
if len(data) >= 12 and data[4:8] == b'ftyp':
brand = data[8:12]
if brand in [b'heic', b'heix', b'hevc', b'mif1']:
return FileType.HEIC
elif brand in [b'avif', b'avis']:
return FileType.AVIF
# Check for TIFF (II = little-endian, MM = big-endian)
if data[:4] in [b'II\x2a\x00', b'MM\x00\x2a']:
return FileType.TIFF
# Check for AIFF (FORM container with AIFF type)
if data[:4] == b'FORM' and len(data) >= 12:
if data[8:12] == b'AIFF' or data[8:12] == b'AIFC':
return FileType.AIFF
# Check for TAR (magic at offset 257)
if len(data) >= 265 and data[257:262] == b'ustar':
return FileType.TAR
# Check for SVG
if b'<svg' in data[:1000] or b'<?xml' in data[:100] and b'<svg' in data[:2000]:
return FileType.SVG
# Check for fonts
if data[:4] in [b'\x00\x01\x00\x00', b'OTTO', b'true', b'typ1']:
return FileType.FONT
if data[:4] == b'wOFF' or data[:4] == b'wOF2':
return FileType.FONT
return FileType.UNKNOWN
def calculate_entropy(data: bytes) -> float:
"""Calculate Shannon entropy of data"""
if not data:
return 0.0
byte_counts = [0] * 256
for byte in data:
byte_counts[byte] += 1
length = len(data)
entropy = 0.0
for count in byte_counts:
if count > 0:
p = count / length
entropy -= p * math.log2(p)
return entropy
def calculate_chi_square(data: bytes) -> float:
"""Calculate chi-square statistic for randomness test"""
if not data:
return 0.0
byte_counts = [0] * 256
for byte in data:
byte_counts[byte] += 1
expected = len(data) / 256
chi_square = sum((count - expected) ** 2 / expected for count in byte_counts)
return chi_square
def find_strings(data: bytes, min_length: int = 4) -> List[Tuple[int, str]]:
"""Extract printable ASCII strings from binary data"""
strings = []
current = []
start_offset = 0
for i, byte in enumerate(data):
if 32 <= byte < 127:
if not current:
start_offset = i
current.append(chr(byte))
else:
if len(current) >= min_length:
strings.append((start_offset, ''.join(current)))
current = []
if len(current) >= min_length:
strings.append((start_offset, ''.join(current)))
return strings
def hex_dump(data: bytes, offset: int = 0, length: int = 256) -> str:
"""Create hex dump of data"""
result = []
chunk = data[offset:offset + length]
for i in range(0, len(chunk), 16):
line_data = chunk[i:i + 16]
hex_part = ' '.join(f'{b:02x}' for b in line_data)
ascii_part = ''.join(chr(b) if 32 <= b < 127 else '.' for b in line_data)
result.append(f'{offset + i:08x} {hex_part:<48} {ascii_part}')
return '\n'.join(result)
# ============== BIT PLANE ANALYSIS ==============
def extract_bit_plane(data: bytes, bit: int) -> bytes:
"""Extract specific bit plane from data"""
if not HAS_NUMPY:
# Fallback without numpy
result = bytearray()
for i in range(0, len(data), 8):
byte_val = 0
for j in range(8):
if i + j < len(data):
byte_val |= ((data[i + j] >> bit) & 1) << (7 - j)
result.append(byte_val)
return bytes(result)
arr = np.frombuffer(data, dtype=np.uint8)
plane = (arr >> bit) & 1
# Pack bits into bytes
padded = np.pad(plane, (0, (8 - len(plane) % 8) % 8), mode='constant')
packed = np.packbits(padded)
return packed.tobytes()
def analyze_bit_planes(data: bytes) -> Dict[str, Any]:
"""Analyze all 8 bit planes"""
results = {}
for bit in range(8):
plane_data = extract_bit_plane(data, bit)
results[f'plane_{bit}'] = {
'entropy': calculate_entropy(plane_data),
'unique_bytes': len(set(plane_data)),
'sample': plane_data[:64].hex()
}
return results
# ============== LSB EXTRACTION ==============
def extract_lsb(data: bytes, bits: int = 1, channels: str = "RGB") -> bytes:
"""Extract LSB data from raw pixel bytes"""
if not data:
return b''
extracted_bits = []
mask = (1 << bits) - 1
for byte in data:
for bit_pos in range(bits):
extracted_bits.append((byte >> bit_pos) & 1)
# Pack bits into bytes
result = bytearray()
for i in range(0, len(extracted_bits), 8):
byte_val = 0
for j in range(8):
if i + j < len(extracted_bits):
byte_val |= extracted_bits[i + j] << j
result.append(byte_val)
return bytes(result)
# ============== PATTERN DETECTION ==============
def detect_repeated_patterns(data: bytes, min_length: int = 4, max_length: int = 32) -> List[Dict[str, Any]]:
"""Detect repeated byte patterns"""
patterns = []
for length in range(min_length, min(max_length, len(data) // 2) + 1):
seen = {}
for i in range(len(data) - length + 1):
pattern = data[i:i + length]
if pattern in seen:
seen[pattern].append(i)
else:
seen[pattern] = [i]
for pattern, offsets in seen.items():
if len(offsets) >= 3: # At least 3 occurrences
patterns.append({
'pattern': pattern.hex(),
'length': length,
'count': len(offsets),
'offsets': offsets[:10] # First 10 offsets
})
return sorted(patterns, key=lambda x: x['count'], reverse=True)[:20]
def detect_xor_patterns(data: bytes) -> Dict[str, Any]:
"""Detect potential XOR encryption patterns"""
results = {
'single_byte_keys': [],
'repeating_key_likely': False,
'key_length_candidates': []
}
# Try single-byte XOR keys
for key in range(256):
decoded = bytes(b ^ key for b in data[:256])
# Check if result looks like text
printable = sum(1 for b in decoded if 32 <= b < 127 or b in [9, 10, 13])
if printable > len(decoded) * 0.7:
results['single_byte_keys'].append({
'key': key,
'key_hex': f'{key:02x}',
'printable_ratio': printable / len(decoded),
'sample': decoded[:50].decode('ascii', errors='replace')
})
# Detect repeating key by looking at byte frequency at intervals
for key_len in range(2, 17):
columns = [[] for _ in range(key_len)]
for i, b in enumerate(data[:1024]):
columns[i % key_len].append(b)
# Check if each column has low entropy (single-byte XOR characteristic)
avg_entropy = sum(calculate_entropy(bytes(col)) for col in columns) / key_len
if avg_entropy < 5.0: # Lower than random
results['key_length_candidates'].append({
'length': key_len,
'avg_column_entropy': avg_entropy
})
if results['key_length_candidates']:
results['repeating_key_likely'] = True
return results
# ============== ENCODING DETECTION ==============
def detect_base64(data: bytes) -> Dict[str, Any]:
"""Detect and decode potential Base64 encoded content"""
results = {
'found': False,
'segments': []
}
# Base64 pattern
b64_pattern = rb'[A-Za-z0-9+/]{20,}={0,2}'
text = data.decode('ascii', errors='ignore')
matches = re.finditer(r'[A-Za-z0-9+/]{20,}={0,2}', text)
for match in matches:
b64_str = match.group()
try:
# Try to decode
import base64
decoded = base64.b64decode(b64_str)
# Check if decoded content is meaningful
printable = sum(1 for b in decoded if 32 <= b < 127 or b in [9, 10, 13])
results['segments'].append({
'offset': match.start(),
'length': len(b64_str),
'decoded_length': len(decoded),
'printable_ratio': printable / len(decoded) if decoded else 0,
'decoded_preview': decoded[:100].decode('utf-8', errors='replace') if printable > len(decoded) * 0.5 else decoded[:50].hex()
})
results['found'] = True
except:
pass
return results
def detect_hex_strings(data: bytes) -> Dict[str, Any]:
"""Detect hex-encoded strings"""
results = {
'found': False,
'segments': []
}
text = data.decode('ascii', errors='ignore')
# Match continuous hex strings
hex_pattern = r'(?:[0-9a-fA-F]{2}){8,}'
for match in re.finditer(hex_pattern, text):
hex_str = match.group()
try:
decoded = bytes.fromhex(hex_str)
printable = sum(1 for b in decoded if 32 <= b < 127 or b in [9, 10, 13])
results['segments'].append({
'offset': match.start(),
'length': len(hex_str),
'decoded_length': len(decoded),
'printable_ratio': printable / len(decoded) if decoded else 0,
'decoded_preview': decoded[:100].decode('utf-8', errors='replace') if printable > len(decoded) * 0.5 else None
})
results['found'] = True
except:
pass
return results
def detect_unicode_steg(data: bytes) -> Dict[str, Any]:
"""Detect Unicode-based steganography (zero-width chars, homoglyphs)"""
results = {
'found': False,
'zero_width_chars': [],
'homoglyphs': [],
'invisible_chars': 0
}
try:
text = data.decode('utf-8', errors='ignore')
except:
return results
# Zero-width characters
zwc_chars = {
'\u200b': 'ZERO WIDTH SPACE',
'\u200c': 'ZERO WIDTH NON-JOINER',
'\u200d': 'ZERO WIDTH JOINER',
'\u2060': 'WORD JOINER',
'\ufeff': 'ZERO WIDTH NO-BREAK SPACE (BOM)',
'\u180e': 'MONGOLIAN VOWEL SEPARATOR',
}
for char, name in zwc_chars.items():
count = text.count(char)
if count > 0:
results['zero_width_chars'].append({
'char': repr(char),
'name': name,
'count': count
})
results['invisible_chars'] += count
results['found'] = True
# Check for variation selectors
for i, char in enumerate(text):
if '\ufe00' <= char <= '\ufe0f':
results['invisible_chars'] += 1
results['found'] = True
return results
def detect_whitespace_steg(data: bytes) -> Dict[str, Any]:
"""Detect whitespace steganography (tabs/spaces encoding)"""
results = {
'found': False,
'trailing_spaces': 0,
'mixed_indentation': False,
'suspicious_patterns': [],
'potential_message': None
}
try:
text = data.decode('utf-8', errors='ignore')
except:
return results
lines = text.split('\n')
tab_indent_lines = 0
space_indent_lines = 0
for line in lines:
# Count trailing whitespace
stripped = line.rstrip()
trailing = len(line) - len(stripped)
if trailing > 0:
results['trailing_spaces'] += trailing
# Check indentation type
if line.startswith('\t'):
tab_indent_lines += 1
elif line.startswith(' '):
space_indent_lines += 1
if tab_indent_lines > 0 and space_indent_lines > 0:
results['mixed_indentation'] = True
if results['trailing_spaces'] > 10:
results['found'] = True
# Try to decode as binary (space=0, tab=1 or similar)
bits = []
for line in lines:
trailing = line[len(line.rstrip()):]
for char in trailing:
if char == ' ':
bits.append('0')
elif char == '\t':
bits.append('1')
if len(bits) >= 8:
try:
bit_string = ''.join(bits)
message = bytearray()
for i in range(0, len(bit_string) - 7, 8):
byte_val = int(bit_string[i:i+8], 2)
if byte_val == 0:
break
message.append(byte_val)
decoded = bytes(message).decode('utf-8', errors='ignore')
if decoded and all(32 <= ord(c) < 127 or c in '\r\n\t' for c in decoded):
results['potential_message'] = decoded[:200]
except:
pass
return results
# ============== TOOL REGISTRY ==============
class AnalysisToolRegistry:
"""Registry of all analysis tools organized by action name"""
def __init__(self):
self._tools: Dict[str, callable] = {}
self._register_all_tools()
def _register_all_tools(self):
"""Register all analysis tools"""
# Core detection tools
self._tools['detect_base64'] = detect_base64
self._tools['detect_hex_strings'] = detect_hex_strings
self._tools['detect_unicode_steg'] = detect_unicode_steg
self._tools['detect_whitespace_steg'] = detect_whitespace_steg
self._tools['detect_xor_patterns'] = detect_xor_patterns
self._tools['detect_repeated_patterns'] = detect_repeated_patterns
# Analysis tools
self._tools['analyze_entropy'] = lambda data: {'entropy': calculate_entropy(data)}
self._tools['analyze_bit_planes'] = analyze_bit_planes
# Will be populated by format-specific modules
def register(self, action: str, func: callable):
"""Register a tool function"""
self._tools[action] = func
def get(self, action: str) -> Optional[callable]:
"""Get a tool function by action name"""
return self._tools.get(action)
def execute(self, action: str, data: bytes, **kwargs) -> AnalysisResult:
"""Execute an analysis tool"""
func = self._tools.get(action)
if not func:
return AnalysisResult(
success=False,
action=action,
file_type="unknown",
error=f"Unknown action: {action}"
)
try:
result = func(data, **kwargs)
# Convert result to AnalysisResult if needed
if isinstance(result, AnalysisResult):
return result
elif isinstance(result, dict):
return AnalysisResult(
success=True,
action=action,
file_type=kwargs.get('file_type', 'unknown'),
data=result,
suspicious=result.get('found', False) or result.get('suspicious', False)
)
else:
return AnalysisResult(
success=True,
action=action,
file_type=kwargs.get('file_type', 'unknown'),
data={'result': result}
)
except Exception as e:
return AnalysisResult(
success=False,
action=action,
file_type=kwargs.get('file_type', 'unknown'),
error=str(e)
)
def list_tools(self) -> List[str]:
"""List all registered tools"""
return sorted(self._tools.keys())
# Global registry instance
TOOL_REGISTRY = AnalysisToolRegistry()
def execute_action(action: str, data: bytes, **kwargs) -> AnalysisResult:
"""Execute an analysis action"""
return TOOL_REGISTRY.execute(action, data, **kwargs)
def list_available_tools() -> List[str]:
"""List all available analysis tools"""
return TOOL_REGISTRY.list_tools()
# ============== PNG ANALYSIS TOOLS ==============
PNG_MAGIC = b'\x89PNG\r\n\x1a\n'
PNG_CHUNK_TYPES = {
'IHDR': 'Image header',
'PLTE': 'Palette',
'IDAT': 'Image data',
'IEND': 'Image end',
'tEXt': 'Textual data',
'zTXt': 'Compressed textual data',
'iTXt': 'International textual data',
'bKGD': 'Background color',
'cHRM': 'Primary chromaticities',
'gAMA': 'Gamma',
'hIST': 'Palette histogram',
'iCCP': 'ICC profile',
'pHYs': 'Physical pixel dimensions',
'sBIT': 'Significant bits',
'sPLT': 'Suggested palette',
'sRGB': 'Standard RGB color space',
'tIME': 'Last modification time',
'tRNS': 'Transparency',
'eXIf': 'EXIF data',
'acTL': 'Animation control (APNG)',
'fcTL': 'Frame control (APNG)',
'fdAT': 'Frame data (APNG)',
}
def png_parse_chunks(data: bytes) -> Dict[str, Any]:
"""Parse all PNG chunks and return detailed information"""
if not data.startswith(PNG_MAGIC):
return {'error': 'Not a valid PNG file', 'valid': False}
chunks = []
pos = 8 # Skip magic bytes
total_idat_size = 0
chunk_type_counts = {}
while pos < len(data):
if pos + 8 > len(data):
break
chunk_length = struct.unpack('>I', data[pos:pos+4])[0]
chunk_type = data[pos+4:pos+8].decode('ascii', errors='replace')
if pos + 12 + chunk_length > len(data):
chunks.append({
'type': chunk_type,
'offset': pos,
'length': chunk_length,
'error': 'Truncated chunk'
})
break
chunk_data = data[pos+8:pos+8+chunk_length]
stored_crc = struct.unpack('>I', data[pos+8+chunk_length:pos+12+chunk_length])[0]
calculated_crc = zlib.crc32(data[pos+4:pos+8+chunk_length]) & 0xffffffff
chunk_info = {
'type': chunk_type,
'description': PNG_CHUNK_TYPES.get(chunk_type, 'Unknown/Private'),
'offset': pos,
'length': chunk_length,
'crc_valid': stored_crc == calculated_crc,
'crc_stored': f'{stored_crc:08x}',
'crc_calculated': f'{calculated_crc:08x}',
}
# Track chunk type counts
chunk_type_counts[chunk_type] = chunk_type_counts.get(chunk_type, 0) + 1
# Track IDAT size
if chunk_type == 'IDAT':
total_idat_size += chunk_length
# Parse IHDR
if chunk_type == 'IHDR' and chunk_length == 13:
width, height, bit_depth, color_type, compression, filter_method, interlace = struct.unpack('>IIBBBBB', chunk_data)
chunk_info['parsed'] = {
'width': width,
'height': height,
'bit_depth': bit_depth,
'color_type': color_type,
'compression': compression,
'filter': filter_method,
'interlace': interlace
}
# Parse text chunks
elif chunk_type == 'tEXt':
null_pos = chunk_data.find(b'\x00')
if null_pos != -1:
keyword = chunk_data[:null_pos].decode('latin-1', errors='replace')
text = chunk_data[null_pos+1:].decode('latin-1', errors='replace')
chunk_info['parsed'] = {'keyword': keyword, 'text': text[:500]}
elif chunk_type == 'zTXt':
null_pos = chunk_data.find(b'\x00')
if null_pos != -1:
keyword = chunk_data[:null_pos].decode('latin-1', errors='replace')
try:
text = zlib.decompress(chunk_data[null_pos+2:]).decode('latin-1', errors='replace')
chunk_info['parsed'] = {'keyword': keyword, 'text': text[:500], 'compressed': True}
except:
chunk_info['parsed'] = {'keyword': keyword, 'error': 'Decompression failed'}
elif chunk_type == 'iTXt':
null_pos = chunk_data.find(b'\x00')
if null_pos != -1:
keyword = chunk_data[:null_pos].decode('latin-1', errors='replace')
chunk_info['parsed'] = {'keyword': keyword}
# Parse tIME
elif chunk_type == 'tIME' and chunk_length == 7:
year, month, day, hour, minute, second = struct.unpack('>HBBBBB', chunk_data)
chunk_info['parsed'] = {
'timestamp': f'{year:04d}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}'
}
# Parse pHYs
elif chunk_type == 'pHYs' and chunk_length == 9:
ppux, ppuy, unit = struct.unpack('>IIB', chunk_data)
chunk_info['parsed'] = {
'pixels_per_unit_x': ppux,
'pixels_per_unit_y': ppuy,
'unit': 'meter' if unit == 1 else 'unknown'
}
chunks.append(chunk_info)
pos += 12 + chunk_length
if chunk_type == 'IEND':
break
# Check for data after IEND
after_iend = len(data) - pos
return {
'valid': True,
'chunks': chunks,
'chunk_count': len(chunks),
'chunk_type_counts': chunk_type_counts,
'total_idat_size': total_idat_size,
'data_after_iend': after_iend,
'suspicious': after_iend > 0
}
def png_extract_text_chunks(data: bytes) -> Dict[str, Any]:
"""Extract all text metadata from PNG"""
result = png_parse_chunks(data)
if not result.get('valid'):
return result
text_chunks = []
for chunk in result['chunks']:
if chunk['type'] in ('tEXt', 'zTXt', 'iTXt') and 'parsed' in chunk:
text_chunks.append({
'type': chunk['type'],
'keyword': chunk['parsed'].get('keyword', ''),
'text': chunk['parsed'].get('text', ''),
'offset': chunk['offset']
})
return {
'found': len(text_chunks) > 0,
'text_chunks': text_chunks,
'count': len(text_chunks)
}
def png_detect_appended_data(data: bytes) -> Dict[str, Any]:
"""Detect data appended after PNG IEND chunk"""
if not data.startswith(PNG_MAGIC):
return {'found': False, 'error': 'Not a valid PNG file'}
# Parse through PNG chunks to find actual IEND position
pos = 8 # Skip magic
iend_end_pos = None
while pos + 8 <= len(data):
chunk_length = struct.unpack('>I', data[pos:pos+4])[0]
chunk_type = data[pos+4:pos+8]
# Chunk end = pos + 4 (length) + 4 (type) + chunk_length + 4 (CRC)
chunk_end_pos = pos + 12 + chunk_length
if chunk_type == b'IEND':
iend_end_pos = chunk_end_pos
break
pos = chunk_end_pos
if iend_end_pos is None:
return {'found': False, 'error': 'No IEND chunk found'}
if iend_end_pos >= len(data):
return {'found': False, 'appended_size': 0}
appended_data = data[iend_end_pos:]
if len(appended_data) == 0:
return {'found': False, 'appended_size': 0}
# Analyze appended data
result = {
'found': True,
'appended_size': len(appended_data),
'offset': iend_end_pos,
'entropy': calculate_entropy(appended_data),
'preview_hex': appended_data[:64].hex(),
'suspicious': True
}
# Check if appended data is another file
file_type = detect_file_type(appended_data)
if file_type != FileType.UNKNOWN:
result['embedded_file_type'] = file_type.value
# Check for printable text
try:
text = appended_data[:200].decode('utf-8')
if all(c.isprintable() or c in '\r\n\t' for c in text):
result['text_preview'] = text
except:
pass
return result
def png_analyze_idat(data: bytes) -> Dict[str, Any]:
"""Analyze PNG IDAT chunks for anomalies"""
result = png_parse_chunks(data)
if not result.get('valid'):
return result
idat_chunks = []
prev_end = 0
for chunk in result['chunks']:
if chunk['type'] == 'IDAT':
idat_chunks.append({
'offset': chunk['offset'],
'length': chunk['length'],
'crc_valid': chunk['crc_valid']
})
# Check for gap between IDAT chunks
if prev_end > 0 and chunk['offset'] != prev_end:
gap = chunk['offset'] - prev_end
if gap > 12: # More than just the next chunk header
idat_chunks[-1]['gap_before'] = gap
prev_end = chunk['offset'] + 12 + chunk['length']
if not idat_chunks:
return {'found': False, 'error': 'No IDAT chunks found'}
total_size = sum(c['length'] for c in idat_chunks)
sizes = [c['length'] for c in idat_chunks]
return {
'found': True,
'chunk_count': len(idat_chunks),
'total_size': total_size,
'chunks': idat_chunks,
'size_variance': max(sizes) - min(sizes) if len(sizes) > 1 else 0,
'avg_chunk_size': total_size // len(idat_chunks),
'all_crc_valid': all(c['crc_valid'] for c in idat_chunks),
'suspicious': any('gap_before' in c for c in idat_chunks)
}
def png_extract_lsb(data: bytes, bits: int = 1, channels: str = "RGB") -> Dict[str, Any]:
"""Extract LSB data from PNG image pixels"""
if not HAS_PIL:
return {'error': 'PIL not available', 'found': False}
try:
img = Image.open(io.BytesIO(data))
# Convert to RGBA for consistent processing
if img.mode == 'P':
img = img.convert('RGBA')
elif img.mode == 'L':
img = img.convert('RGB')
elif img.mode not in ('RGB', 'RGBA'):
img = img.convert('RGBA')
pixels = list(img.getdata())
# Extract bits from specified channels
channel_map = {'R': 0, 'G': 1, 'B': 2, 'A': 3}
channel_indices = [channel_map[c] for c in channels.upper() if c in channel_map]
extracted_bits = []
mask = (1 << bits) - 1
for pixel in pixels:
for ch_idx in channel_indices:
if ch_idx < len(pixel):
for bit_pos in range(bits):
extracted_bits.append((pixel[ch_idx] >> bit_pos) & 1)
# Pack into bytes
result_bytes = bytearray()
for i in range(0, len(extracted_bits) - 7, 8):
byte_val = 0
for j in range(8):
byte_val |= extracted_bits[i + j] << j
result_bytes.append(byte_val)
raw_data = bytes(result_bytes)
# Look for patterns
result = {
'found': True,
'extracted_size': len(raw_data),
'channels': channels,
'bits_per_channel': bits,
'entropy': calculate_entropy(raw_data[:1024]),
'raw_data': raw_data
}
# Check for STEG magic
if raw_data[:4] == b'STEG':
result['steg_header_found'] = True
result['suspicious'] = True
# Check for file signatures
file_type = detect_file_type(raw_data)
if file_type != FileType.UNKNOWN:
result['embedded_file_type'] = file_type.value