-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpoly.py
More file actions
2206 lines (1809 loc) · 98.3 KB
/
poly.py
File metadata and controls
2206 lines (1809 loc) · 98.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
#!/usr/bin/env python3
"""
PolyZip - A tool for creating polyglot files (FILE + ZIP)
Based on the work of DavidBuchanan314 (https://github.com/DavidBuchanan314/tweetable-polyglot-png)
Author: InfoSecREDD
Version: 2.1.3
"""
import zlib
import sys
import os
import glob
import json
import struct
import mimetypes
import subprocess
import importlib.util
import platform
import tempfile
import zipfile
import datetime
import base64
import secrets
import shutil
ARGON2_AVAILABLE = False
def check_and_install_dependencies():
"""Always ensure we're running in our own virtual environment with all dependencies"""
venv_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.poly_venv')
if platform.system() == 'Windows':
our_venv_python = os.path.join(venv_dir, 'Scripts', 'python.exe')
else:
our_venv_python = os.path.join(venv_dir, 'bin', 'python')
current_python = os.path.abspath(sys.executable)
our_python = os.path.abspath(our_venv_python)
in_our_venv = (
current_python == our_python or
os.path.basename(current_python) == os.path.basename(our_python) and current_python.startswith(os.path.abspath(venv_dir)) or
(hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix and os.path.abspath(sys.prefix) == os.path.abspath(venv_dir))
)
if not in_our_venv:
venv_exists = os.path.exists(venv_dir)
venv_python_working = False
if platform.system() == 'Windows':
venv_python = os.path.join(venv_dir, 'Scripts', 'python.exe')
else:
venv_python = os.path.join(venv_dir, 'bin', 'python')
if venv_exists and os.path.exists(venv_python):
try:
result = subprocess.run([venv_python, '--version'],
capture_output=True, timeout=10)
venv_python_working = result.returncode == 0
except Exception:
venv_python_working = False
if not venv_exists or not venv_python_working:
if venv_exists and not venv_python_working:
print(f"[\033[33m!\033[0m] Virtual environment is corrupted, recreating...")
try:
shutil.rmtree(venv_dir)
except Exception as e:
print(f"[\033[33m!\033[0m] Warning: Could not remove old venv: {e}")
print(f"[\033[36m*\033[0m] Setting up dedicated virtual environment...")
print(f"[\033[36m+\033[0m] Creating virtual environment in {venv_dir}")
try:
subprocess.check_call([sys.executable, '-m', 'venv', venv_dir])
except Exception as e:
print(f"[\033[31m!\033[0m] Failed to create virtual environment: {e}")
sys.exit(1)
print(f"[\033[36m*\033[0m] Restarting script in virtual environment...")
if not os.path.exists(venv_python):
print(f"[\033[31m!\033[0m] Virtual environment Python not found at {venv_python}")
sys.exit(1)
try:
result = subprocess.run([venv_python, '--version'],
capture_output=True, timeout=10)
if result.returncode != 0:
print(f"[\033[31m!\033[0m] Virtual environment Python is not functional")
sys.exit(1)
except Exception as e:
print(f"[\033[31m!\033[0m] Virtual environment Python test failed: {e}")
sys.exit(1)
os.execl(venv_python, venv_python, *sys.argv)
required_packages = [
{'package': 'python-magic', 'import_name': 'magic', 'optional': True},
{'package': 'cryptography', 'import_name': 'cryptography', 'optional': False}
]
missing_packages = []
for package_info in required_packages:
if importlib.util.find_spec(package_info['import_name']) is None:
missing_packages.append(package_info['package'])
if missing_packages:
print(f"[\033[36m*\033[0m] Installing missing packages: {', '.join(missing_packages)}")
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install'] + missing_packages)
print(f"[\033[32m✓\033[0m] Dependencies installed successfully!")
except Exception as e:
print(f"[\033[33m!\033[0m] pip failed: {e}, trying pip3...")
try:
subprocess.check_call([sys.executable, '-m', 'pip3', 'install'] + missing_packages)
print(f"[\033[32m✓\033[0m] Dependencies installed successfully using pip3!")
except Exception as e2:
print(f"[\033[31m!\033[0m] Failed to install dependencies with both pip and pip3: {e2}")
print(f"[\033[31m!\033[0m] Please install manually in the virtual environment:")
print(f" source {venv_dir}/bin/activate # or {venv_dir}\\Scripts\\activate on Windows")
print(f" pip install {' '.join(missing_packages)}")
sys.exit(1)
else:
print(f"[\033[32m✓\033[0m] Using virtual environment")
def import_cryptography():
"""Import cryptography modules after dependency checking"""
global ARGON2_AVAILABLE, Cipher, algorithms, modes, Scrypt, hashes, default_backend, Argon2id
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
try:
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
ARGON2_AVAILABLE = True
except ImportError:
ARGON2_AVAILABLE = False
except ImportError as e:
print(f"\033[31m[!] Error importing cryptography: {e}\033[0m")
print(f"\033[31m[!] Please install cryptography: pip install cryptography\033[0m")
sys.exit(1)
if __name__ == "__main__":
check_and_install_dependencies()
import_cryptography()
BANNER = r'''
██████╗ ██████╗ ██╗ ██╗ ██╗███████╗██╗██████╗
██╔══██╗██╔═══██╗██║ ╚██╗ ██╔╝╚══███╔╝██║██╔══██╗
██████╔╝██║ ██║██║ ╚████╔╝ ███╔╝ ██║██████╔╝
██╔═══╝ ██║ ██║██║ ╚██╔╝ ███╔╝ ██║██╔═══╝
██║ ╚██████╔╝███████╗██║ ███████╗██║██║
╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚══════╝╚═╝╚═╝
[ Multi-Format Polyglot Tool - Hide Any Data ]
╔══════════════════════════════════════════╗
║ pack ≫ extract ≫ detect ≫ ghost in file ║
╚══════════════════════════════════════════╝
'''
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
JPEG_MAGIC = b"\xff\xd8\xff"
GIF_MAGIC = b"GIF8"
PDF_MAGIC = b"%PDF-"
BMP_MAGIC = b"BM"
WEBP_MAGIC = b"RIFF"
TIFF_MAGIC_LE = b"II*\x00"
TIFF_MAGIC_BE = b"MM\x00*"
WAV_MAGIC = b"RIFF"
MP3_MAGIC = b"\xFF\xFB"
MP3_MAGIC2 = b"\xFF\xF3"
MP3_MAGIC3 = b"\xFF\xFA"
MP3_MAGIC4 = b"\xFF\xF2"
FLAC_MAGIC = b"fLaC"
OGG_MAGIC = b"OggS"
AVI_MAGIC = b"RIFF"
MKV_MAGIC = b"\x1a\x45\xdf\xa3"
M4A_MAGIC = b"ftyp"
WEBM_MAGIC = b"\x1a\x45\xdf\xa3"
FLV_MAGIC = b"FLV"
ICO_MAGIC = b"\x00\x00\x01\x00"
CUR_MAGIC = b"\x00\x00\x02\x00"
ICNS_MAGIC = b"icns"
MP4_MAGIC = b"ftyp"
MZ_MAGIC = b"MZ"
ELF_MAGIC = b"\x7fELF"
MSI_MAGIC = b"\xd0\xcf\x11\xe0"
TTF_MAGIC = b"\x00\x01\x00\x00"
OTF_MAGIC = b"OTTO"
WOFF_MAGIC = b"wOFF"
def print_banner():
colors = {
'cyan': '\033[36m',
'green': '\033[32m',
'blue': '\033[34m',
'red': '\033[31m',
'magenta': '\033[35m',
'yellow': '\033[33m',
'white': '\033[37m',
'reset': '\033[0m'
}
colored_banner = colors['cyan'] + BANNER + colors['reset']
print(colored_banner)
version_info = f"{colors['green']}[+]{colors['reset']} {colors['white']}Version 2.1.3{colors['reset']} | " + \
f"{colors['green']}[+]{colors['reset']} {colors['white']}Data Hidden in Plain Sight{colors['reset']}"
print(version_info)
print(f"{colors['green']}[+]{colors['reset']} {colors['white']}Use {colors['cyan']}detect{colors['reset']} to scan for hidden data")
print()
def print_usage():
colors = {
'cyan': '\033[36m',
'green': '\033[32m',
'blue': '\033[34m',
'red': '\033[31m',
'magenta': '\033[35m',
'yellow': '\033[33m',
'white': '\033[37m',
'bold': '\033[1m',
'reset': '\033[0m'
}
print(f"\n{colors['bold']}{colors['cyan']}USAGE:{colors['reset']}")
print(f" {colors['white']}{sys.argv[0]}{colors['reset']} {colors['yellow']}[command]{colors['reset']} {colors['green']}[options...]{colors['reset']}")
print(f"\n{colors['bold']}{colors['magenta']}COMMANDS:{colors['reset']}")
print(f"\n {colors['bold']}{colors['cyan']}pack{colors['reset']} - {colors['white']}Hide files inside images/documents{colors['reset']}")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} pack {colors['green']}cover_file{colors['reset']} {colors['blue']}file1 [file2 ...]{colors['reset']} {colors['magenta']}output_file{colors['reset']} {colors['red']}[encryption]{colors['reset']}")
print(f" {colors['yellow']}Example:{colors['reset']} {sys.argv[0]} pack photo.png secret.txt hidden_photo.png")
print(f" {colors['yellow']}Encrypted:{colors['reset']} {sys.argv[0]} pack photo.png secret.txt hidden_photo.png --key=my.key")
print(f" {colors['yellow']}Supports:{colors['reset']} PNG, JPEG, GIF, PDF, BMP, WebP, TIFF, WAV, MP3, FLAC, OGG,")
print(f" AVI, MKV, WebM, FLV, ICO, CUR, ICNS, MP4, MOV, M4A, EXE, DLL, ELF, MSI, TTF, OTF, WOFF")
print(f"\n {colors['bold']}{colors['cyan']}extract{colors['reset']} - {colors['white']}Extract hidden files from images/documents{colors['reset']}")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} extract {colors['green']}input_file{colors['reset']} {colors['blue']}[output_directory]{colors['reset']} {colors['red']}[encryption]{colors['reset']}")
print(f" {colors['yellow']}Example:{colors['reset']} {sys.argv[0]} extract hidden_photo.png extracted_files/")
print(f" {colors['yellow']}Encrypted:{colors['reset']} {sys.argv[0]} extract hidden_photo.png extracted_files/ --key=my.key")
print(f" {colors['yellow']}Note:{colors['reset']} If output directory is omitted, extracts to folder named after input file")
print(f"\n {colors['bold']}{colors['cyan']}detect{colors['reset']} - {colors['white']}Scan for hidden data in files{colors['reset']}")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} detect {colors['green']}[file]{colors['reset']}")
print(f" {colors['yellow']}Example:{colors['reset']} {sys.argv[0]} detect suspicious_image.png")
print(f" {colors['yellow']}Note:{colors['reset']} If no file specified, scans all supported files in current directory")
print(f"\n {colors['bold']}{colors['cyan']}chat{colors['reset']} - {colors['white']}Create encrypted hidden chat logs in images{colors['reset']}")
print(f" {colors['bold']}{colors['green']}Subcommands:{colors['reset']}")
print(f"\n {colors['bold']}{colors['yellow']}create{colors['reset']} - Create new encrypted chat")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} chat create {colors['green']}cover.[any]{colors['reset']} {colors['magenta']}output.[any]{colors['reset']} {colors['blue']}[\"title\"]{colors['reset']} {colors['red']}[encryption]{colors['reset']}")
print(f" {colors['yellow']}Examples:{colors['reset']}")
print(f" {sys.argv[0]} chat create photo.jpg secret_chat.jpg \"Team Chat\" --key=team.key")
print(f" {sys.argv[0]} chat create document.pdf secret_chat.pdf \"Private\" --password=mypass123")
print(f" {sys.argv[0]} chat create image.gif secret_chat.gif # Unencrypted")
print(f" {sys.argv[0]} chat create cover.png output.png \"Any file type works!\"")
print(f" {colors['cyan']}Supported formats:{colors['reset']} PNG, JPG, GIF, PDF, BMP, WEBP, TIFF, WAV, MP3, FLAC, OGG, AVI, MKV, WebM, FLV, ICO, MP4, MOV, EXE, and more")
print(f"\n {colors['bold']}{colors['yellow']}add{colors['reset']} - Add message to existing chat")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} chat add {colors['green']}chat.[any]{colors['reset']} {colors['blue']}sender{colors['reset']} {colors['cyan']}\"message\"{colors['reset']} {colors['magenta']}[output.[any]]{colors['reset']} {colors['red']}[encryption]{colors['reset']}")
print(f" {colors['yellow']}Examples:{colors['reset']}")
print(f" {sys.argv[0]} chat add secret_chat.jpg Alice \"Hello team!\" --key=team.key")
print(f" {sys.argv[0]} chat add secret_chat.pdf Bob \"Secret message\" --password=mypass123")
print(f" {sys.argv[0]} chat add hidden_chat.gif Charlie \"Works with any file type!\"")
print(f"\n {colors['bold']}{colors['yellow']}read{colors['reset']} - Display chat messages")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} chat read {colors['green']}chat.[any]{colors['reset']} {colors['blue']}[--format=terminal|json|html]{colors['reset']} {colors['red']}[encryption]{colors['reset']}")
print(f" {colors['yellow']}Examples:{colors['reset']}")
print(f" {sys.argv[0]} chat read secret_chat.jpg --key=team.key")
print(f" {sys.argv[0]} chat read secret_chat.pdf --format=json --password=mypass123")
print(f" {sys.argv[0]} chat read hidden_chat.mp4 --format=html")
print(f"\n {colors['bold']}{colors['yellow']}export{colors['reset']} - Export chat to file")
print(f" {colors['yellow']}Usage:{colors['reset']} {sys.argv[0]} chat export {colors['green']}chat.[any]{colors['reset']} {colors['magenta']}output.[txt|json|html]{colors['reset']} {colors['red']}[encryption]{colors['reset']}")
print(f" {colors['yellow']}Examples:{colors['reset']}")
print(f" {sys.argv[0]} chat export secret_chat.jpg backup.html --key=team.key")
print(f" {sys.argv[0]} chat export secret_chat.pdf backup.json --password=mypass123")
print(f" {sys.argv[0]} chat export hidden_chat.mkv backup.txt")
print(f"\n {colors['bold']}{colors['red']}ENCRYPTION OPTIONS:{colors['reset']}")
print(f" {colors['cyan']}--key=filename.key{colors['reset']} Use AES-256 encryption with key file (auto-generated if missing)")
print(f" {colors['cyan']}--password=yourpass{colors['reset']} Use AES-256 encryption with password (Argon2id + salt)")
print(f" {colors['yellow']}Note:{colors['reset']} Encrypted chats are completely secure and undetectable")
print(f"\n{colors['bold']}{colors['green']}QUICK EXAMPLES:{colors['reset']}")
print(f" {colors['white']}Hide files:{colors['reset']} {sys.argv[0]} pack photo.jpg document.pdf hidden.jpg")
print(f" {colors['white']}Hide files encrypted:{colors['reset']} {sys.argv[0]} pack photo.jpg secret.txt hidden.jpg --key=my.key")
print(f" {colors['white']}Extract files:{colors['reset']} {sys.argv[0]} extract hidden.jpg")
print(f" {colors['white']}Extract encrypted:{colors['reset']} {sys.argv[0]} extract hidden.jpg output/ --key=my.key")
print(f" {colors['white']}Scan for hidden data:{colors['reset']} {sys.argv[0]} detect")
print(f" {colors['white']}Create encrypted chat:{colors['reset']} {sys.argv[0]} chat create cover.jpg chat.jpg --key=my.key")
print(f" {colors['white']}Add encrypted message:{colors['reset']} {sys.argv[0]} chat add chat.pdf Alice \"Hello!\" --key=my.key")
print(f" {colors['white']}Read encrypted chat:{colors['reset']} {sys.argv[0]} chat read chat.gif --key=my.key")
print(f" {colors['cyan']}💡 Both files AND chat work with ANY file format - images, videos, documents, executables, etc!{colors['reset']}")
print(f"\n{colors['bold']}{colors['yellow']}SECURITY FEATURES:{colors['reset']}")
print(f" • {colors['green']}AES-256-GCM encryption{colors['reset']} with authenticated encryption for files & chat")
print(f" • {colors['green']}Perfect steganography{colors['reset']} - files appear completely normal")
print(f" • {colors['green']}Key file generation{colors['reset']} - automatic secure key creation")
print(f" • {colors['green']}Password protection{colors['reset']} - Argon2id or Scrypt with secure parameters")
print(f" • {colors['green']}Tamper detection{colors['reset']} - GCM authentication prevents modification")
print(f"\n{colors['bold']}{colors['cyan']}💡 TIP:{colors['reset']} {colors['white']}Files with hidden data can be opened normally in any image viewer/PDF reader!{colors['reset']}")
print()
sys.exit(1)
if len(sys.argv) < 2:
print_banner()
print_usage()
def create_chat_data(title="Chat Log"):
"""Create initial chat data structure"""
return {
"version": "1.0",
"title": title,
"created": datetime.datetime.now().isoformat(),
"participants": [],
"messages": []
}
def add_message_to_chat(chat_data, sender, message):
"""Add a message to the chat data"""
timestamp = datetime.datetime.now().isoformat()
if sender not in chat_data["participants"]:
chat_data["participants"].append(sender)
chat_data["messages"].append({
"timestamp": timestamp,
"sender": sender,
"message": message
})
return chat_data
def generate_key():
"""Generate a new AES-256 key"""
return secrets.token_bytes(32)
def save_key_to_file(key, filename):
"""Save AES key to file in base64 format"""
with open(filename, 'wb') as f:
f.write(base64.b64encode(key))
print(f"[\033[32m+\033[0m] New encryption key saved to: {filename}")
def load_key_from_file(filename):
"""Load AES key from file"""
try:
with open(filename, 'rb') as f:
return base64.b64decode(f.read())
except Exception as e:
raise ValueError(f"Could not load key from {filename}: {e}")
def derive_key_from_password(password, salt):
"""Derive AES key from password using Argon2id or Scrypt fallback"""
if 'Cipher' not in globals():
import_cryptography()
if ARGON2_AVAILABLE:
kdf = Argon2id(
salt=salt,
length=32,
lanes=4,
memory_cost=65536,
iterations=3
)
else:
kdf = Scrypt(
salt=salt,
length=32,
n=2**15, # 32768
r=8,
p=1,
backend=default_backend()
)
return kdf.derive(password.encode())
def encrypt_data(data, key):
"""Encrypt text data using AES-256-GCM"""
if 'Cipher' not in globals():
import_cryptography()
iv = secrets.token_bytes(12)
cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(data.encode()) + encryptor.finalize()
encrypted_payload = iv + encryptor.tag + ciphertext
return base64.b64encode(encrypted_payload).decode()
def decrypt_data(encrypted_data, key):
"""Decrypt text data using AES-256-GCM"""
if 'Cipher' not in globals():
import_cryptography()
try:
encrypted_payload = base64.b64decode(encrypted_data.encode())
iv = encrypted_payload[:12]
auth_tag = encrypted_payload[12:28]
ciphertext = encrypted_payload[28:]
cipher = Cipher(algorithms.AES(key), modes.GCM(iv, auth_tag), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext.decode()
except Exception as e:
raise ValueError(f"Decryption failed: {e}")
def encrypt_file_data(data, key):
"""Encrypt binary file data using AES-256-GCM"""
if 'Cipher' not in globals():
import_cryptography()
iv = secrets.token_bytes(12)
cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(data) + encryptor.finalize()
encrypted_payload = iv + encryptor.tag + ciphertext
return encrypted_payload
def decrypt_file_data(encrypted_data, key):
"""Decrypt binary file data using AES-256-GCM"""
if 'Cipher' not in globals():
import_cryptography()
try:
iv = encrypted_data[:12]
auth_tag = encrypted_data[12:28]
ciphertext = encrypted_data[28:]
cipher = Cipher(algorithms.AES(key), modes.GCM(iv, auth_tag), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext
except Exception as e:
raise ValueError(f"File decryption failed: {e}")
def parse_encryption_args(args):
"""Parse encryption arguments from command line"""
key_file = None
password = None
for arg in args:
if arg.startswith("--key="):
key_file = arg.split("=", 1)[1]
elif arg.startswith("--password="):
password = arg.split("=", 1)[1]
return key_file, password
def get_encryption_key(key_file, password, create_if_missing=False):
"""Get encryption key from file or password"""
if key_file and password:
raise ValueError("Cannot specify both --key and --password options")
if key_file:
if os.path.exists(key_file):
return load_key_from_file(key_file), None
elif create_if_missing:
key = generate_key()
save_key_to_file(key, key_file)
return key, None
else:
raise ValueError(f"Key file '{key_file}' not found")
elif password:
salt = secrets.token_bytes(16)
key = derive_key_from_password(password, salt)
return key, salt
else:
return None, None
def format_chat_terminal(chat_data):
"""Format chat data for terminal display"""
output = []
output.append(f"\n[\033[36m*\033[0m] \033[1m{chat_data['title']}\033[0m")
output.append(f"[\033[36m+\033[0m] Created: {chat_data['created']}")
output.append(f"[\033[36m+\033[0m] Participants: {', '.join(chat_data['participants'])}")
output.append(f"[\033[36m+\033[0m] Messages: {len(chat_data['messages'])}")
output.append("\n" + "=" * 60)
for msg in chat_data["messages"]:
timestamp = datetime.datetime.fromisoformat(msg["timestamp"]).strftime("%Y-%m-%d %H:%M:%S")
output.append(f"\n[\033[32m{timestamp}\033[0m] \033[1m{msg['sender']}\033[0m:")
output.append(f" {msg['message']}")
output.append("\n" + "=" * 60)
return "\n".join(output)
def format_chat_html(chat_data):
"""Format chat data as HTML"""
html = f"""<!DOCTYPE html>
<html>
<head>
<title>{chat_data['title']}</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
.header {{ background-color: #f0f0f0; padding: 10px; border-radius: 5px; }}
.message {{ margin: 10px 0; padding: 10px; border-left: 3px solid #007acc; }}
.sender {{ font-weight: bold; color: #007acc; }}
.timestamp {{ color: #666; font-size: 0.9em; }}
</style>
</head>
<body>
<div class="header">
<h1>{chat_data['title']}</h1>
<p>Created: {chat_data['created']}</p>
<p>Participants: {', '.join(chat_data['participants'])}</p>
<p>Messages: {len(chat_data['messages'])}</p>
</div>
"""
for msg in chat_data["messages"]:
timestamp = datetime.datetime.fromisoformat(msg["timestamp"]).strftime("%Y-%m-%d %H:%M:%S")
html += f"""
<div class="message">
<div class="timestamp">{timestamp}</div>
<div class="sender">{msg['sender']}:</div>
<div>{msg['message']}</div>
</div>"""
html += """
</body>
</html>"""
return html
def extract_chat_from_image(image_path, encryption_key=None, password=None):
"""Extract chat data from image file with optional decryption"""
input_type = detect_cover_file_type(image_path)
if not input_type:
raise ValueError(f"Unsupported image format: {image_path}")
with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp_zip_file:
temp_zip_path = temp_zip_file.name
try:
with open(image_path, "rb") as f_in:
if input_type == "png":
png_header = f_in.read(len(PNG_MAGIC))
if png_header != PNG_MAGIC:
raise ValueError(f"Not a valid PNG file: {image_path}")
zip_data_start = None
while True:
chunk_len_bytes = f_in.read(4)
if not chunk_len_bytes or len(chunk_len_bytes) < 4:
break
chunk_len = int.from_bytes(chunk_len_bytes, "big")
chunk_type = f_in.read(4)
if not chunk_type or len(chunk_type) < 4:
break
if chunk_type == b"IEND":
f_in.seek(chunk_len + 4, 1)
zip_data_start = f_in.tell()
break
else:
f_in.seek(chunk_len + 4, 1)
if zip_data_start is None:
raise ValueError(f"Could not find chat data in {image_path}")
f_in.seek(zip_data_start)
zip_data = f_in.read()
elif input_type == "jpeg":
jpeg_data = f_in.read()
eoi_pos = jpeg_data.rfind(b'\xFF\xD9')
if eoi_pos == -1:
raise ValueError(f"Invalid JPEG file: {image_path}")
zip_data = jpeg_data[eoi_pos+2:]
elif input_type == "gif":
gif_data = f_in.read()
trailer_pos = gif_data.rfind(b'\x3B')
if trailer_pos == -1:
raise ValueError(f"Invalid GIF file: {image_path}")
zip_data = gif_data[trailer_pos+1:]
elif input_type == "pdf":
pdf_data = f_in.read()
eof_pos = pdf_data.rfind(b'%%EOF')
if eof_pos == -1:
raise ValueError(f"Invalid PDF file: {image_path}")
eol_pos = pdf_data.find(b'\n', eof_pos)
if eol_pos == -1:
eol_pos = pdf_data.find(b'\r', eof_pos)
if eol_pos == -1:
eol_pos = len(pdf_data)
else:
eol_pos += 1
else:
eol_pos += 1
zip_data = pdf_data[eol_pos:]
else:
data = f_in.read()
zip_signatures = [b'PK\x03\x04', b'PK\x05\x06', b'PK\x07\x08']
for sig in zip_signatures:
sig_pos = data.find(sig)
if sig_pos > 0:
zip_data = data[sig_pos:]
break
else:
raise ValueError(f"Could not find chat data in {image_path}")
with open(temp_zip_path, "wb") as f_out:
f_out.write(zip_data)
with zipfile.ZipFile(temp_zip_path, 'r') as zipf:
file_list = zipf.namelist()
if 'metadata.json' in file_list and 'chat.enc' in file_list:
metadata_json = zipf.read('metadata.json').decode('utf-8')
metadata = json.loads(metadata_json)
if not metadata.get('encrypted', False):
raise ValueError(f"Invalid encrypted chat format in {image_path}")
if not encryption_key and not password:
raise ValueError(f"Chat is encrypted but no decryption key/password provided")
if password:
if 'salt' not in metadata:
raise ValueError(f"Password-encrypted chat but no salt found in metadata")
salt = base64.b64decode(metadata['salt'].encode())
actual_key = derive_key_from_password(password, salt)
else:
actual_key = encryption_key
encrypted_json = zipf.read('chat.enc').decode('utf-8')
chat_json = decrypt_data(encrypted_json, actual_key)
return json.loads(chat_json)
elif 'chat.json' in file_list:
if encryption_key or password:
print("[\033[33m!\033[0m] Warning: Decryption key/password provided but chat is not encrypted")
chat_json = zipf.read('chat.json').decode('utf-8')
return json.loads(chat_json)
else:
raise ValueError(f"No chat data found in {image_path}")
finally:
try:
os.unlink(temp_zip_path)
except:
pass
def extract_cover_from_chat_image(chat_image_path):
"""Extract original cover image from a chat image (before the embedded data)"""
input_type = detect_cover_file_type(chat_image_path)
if not input_type:
raise ValueError(f"Unsupported image format: {chat_image_path}")
with open(chat_image_path, "rb") as f_in:
if input_type == "png":
png_header = f_in.read(len(PNG_MAGIC))
if png_header != PNG_MAGIC:
raise ValueError(f"Not a valid PNG file: {chat_image_path}")
cover_data = bytearray(png_header)
while True:
chunk_len_bytes = f_in.read(4)
if not chunk_len_bytes or len(chunk_len_bytes) < 4:
break
chunk_len = int.from_bytes(chunk_len_bytes, "big")
chunk_type = f_in.read(4)
if not chunk_type or len(chunk_type) < 4:
break
chunk_body = f_in.read(chunk_len)
if len(chunk_body) < chunk_len:
break
chunk_csum_bytes = f_in.read(4)
if not chunk_csum_bytes or len(chunk_csum_bytes) < 4:
break
cover_data.extend(chunk_len_bytes)
cover_data.extend(chunk_type)
cover_data.extend(chunk_body)
cover_data.extend(chunk_csum_bytes)
if chunk_type == b"IEND":
break
return bytes(cover_data)
elif input_type == "jpeg":
jpeg_data = f_in.read()
eoi_pos = jpeg_data.rfind(b'\xFF\xD9')
if eoi_pos == -1:
raise ValueError(f"Invalid JPEG file: {chat_image_path}")
return jpeg_data[:eoi_pos+2]
elif input_type == "gif":
gif_data = f_in.read()
trailer_pos = gif_data.rfind(b'\x3B')
if trailer_pos == -1:
raise ValueError(f"Invalid GIF file: {chat_image_path}")
return gif_data[:trailer_pos+1]
elif input_type == "pdf":
pdf_data = f_in.read()
eof_pos = pdf_data.rfind(b'%%EOF')
if eof_pos == -1:
raise ValueError(f"Invalid PDF file: {chat_image_path}")
eol_pos = pdf_data.find(b'\n', eof_pos)
if eol_pos == -1:
eol_pos = pdf_data.find(b'\r', eof_pos)
if eol_pos == -1:
eol_pos = len(pdf_data)
else:
eol_pos += 1
else:
eol_pos += 1
return pdf_data[:eol_pos]
else:
data = f_in.read()
zip_signatures = [b'PK\x03\x04', b'PK\x05\x06', b'PK\x07\x08']
for sig in zip_signatures:
sig_pos = data.find(sig)
if sig_pos > 0:
return data[:sig_pos]
raise ValueError(f"Could not find original cover in {chat_image_path}")
def save_chat_to_image(cover_image, chat_data, output_image, encryption_key=None, salt=None):
"""Save chat data embedded in an image with optional encryption"""
with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as temp_zip_file:
temp_zip_path = temp_zip_file.name
try:
with zipfile.ZipFile(temp_zip_path, 'w') as zipf:
chat_json = json.dumps(chat_data, indent=2)
if encryption_key:
encrypted_json = encrypt_data(chat_json, encryption_key)
metadata = {
"encrypted": True,
"version": "1.0"
}
if salt:
metadata["salt"] = base64.b64encode(salt).decode()
zipf.writestr('chat.enc', encrypted_json)
zipf.writestr('metadata.json', json.dumps(metadata))
else:
zipf.writestr('chat.json', chat_json)
cover_type = detect_cover_file_type(cover_image)
if not cover_type:
raise ValueError(f"Unsupported cover image format: {cover_image}")
try:
cover_in = open(cover_image, "rb")
content_in = open(temp_zip_path, "rb")
output_out = open(output_image, "wb")
except Exception as e:
raise ValueError(f"Error opening files: {e}")
try:
if cover_type == "png":
png_header = cover_in.read(len(PNG_MAGIC))
if png_header != PNG_MAGIC:
raise ValueError(f"Not a valid PNG file: {cover_image}")
output_out.write(png_header)
content_embedded = False
while True:
chunk_len_bytes = cover_in.read(4)
if not chunk_len_bytes or len(chunk_len_bytes) < 4:
break
chunk_len = int.from_bytes(chunk_len_bytes, "big")
chunk_type = cover_in.read(4)
if not chunk_type or len(chunk_type) < 4:
break
chunk_body = cover_in.read(chunk_len)
if len(chunk_body) < chunk_len:
break
chunk_csum_bytes = cover_in.read(4)
if not chunk_csum_bytes or len(chunk_csum_bytes) < 4:
break
chunk_csum = int.from_bytes(chunk_csum_bytes, "big")
output_out.write(chunk_len.to_bytes(4, "big"))
output_out.write(chunk_type)
output_out.write(chunk_body)
output_out.write(chunk_csum.to_bytes(4, "big"))
if chunk_type == b"IEND" and not content_embedded:
current_pos = output_out.tell()
start_offset = current_pos
content_dat = bytearray(content_in.read())
fixup_zip(content_dat, start_offset)
output_out.write(content_dat)
content_embedded = True
break
elif cover_type == "jpeg":
jpeg_data = cover_in.read()
eoi_pos = jpeg_data.rfind(b'\xFF\xD9')
if eoi_pos == -1:
raise ValueError(f"Invalid JPEG file: {cover_image}")
output_out.write(jpeg_data[:eoi_pos+2])
start_offset = eoi_pos + 2
content_dat = bytearray(content_in.read())
fixup_zip(content_dat, start_offset)
output_out.write(content_dat)
elif cover_type == "gif":
gif_data = cover_in.read()
trailer_pos = gif_data.rfind(b'\x3B')
if trailer_pos == -1:
raise ValueError(f"Invalid GIF file: {cover_image}")
output_out.write(gif_data[:trailer_pos+1])
start_offset = trailer_pos + 1
content_dat = bytearray(content_in.read())
fixup_zip(content_dat, start_offset)
output_out.write(content_dat)
elif cover_type == "pdf":
pdf_data = cover_in.read()
eof_pos = pdf_data.rfind(b'%%EOF')
if eof_pos == -1:
raise ValueError(f"Invalid PDF file: {cover_image}")
eol_pos = pdf_data.find(b'\n', eof_pos)
if eol_pos == -1:
eol_pos = pdf_data.find(b'\r', eof_pos)
if eol_pos == -1:
eol_pos = len(pdf_data)
else:
eol_pos += 1
else:
eol_pos += 1
output_out.write(pdf_data[:eol_pos])
start_offset = eol_pos
content_dat = bytearray(content_in.read())
fixup_zip(content_dat, start_offset)
output_out.write(content_dat)
else:
format_data = cover_in.read()
output_out.write(format_data)
start_offset = len(format_data)
content_dat = bytearray(content_in.read())
fixup_zip(content_dat, start_offset)
output_out.write(content_dat)
finally:
cover_in.close()
content_in.close()
output_out.close()
finally:
try:
os.unlink(temp_zip_path)
except:
pass
if len(sys.argv) == 4 and sys.argv[1] not in ["pack", "extract", "detect", "chat"]:
sys.argv = [sys.argv[0], "pack"] + sys.argv[1:]
command = sys.argv[1]
print_banner()
def fixup_zip(data, start_offset):
try:
end_central_dir_offset = data.rindex(b"PK\x05\x06")
cdent_count = int.from_bytes(data[end_central_dir_offset+10:end_central_dir_offset+10+2], "little")
cd_range = slice(end_central_dir_offset+16, end_central_dir_offset+16+4)
central_dir_start_offset = int.from_bytes(data[cd_range], "little")
data[cd_range] = (central_dir_start_offset + start_offset).to_bytes(4, "little")
for _ in range(cdent_count):
central_dir_start_offset = data.index(b"PK\x01\x02", central_dir_start_offset)
off_range = slice(central_dir_start_offset+42, central_dir_start_offset+42+4)
off = int.from_bytes(data[off_range], "little")
data[off_range] = (off + start_offset).to_bytes(4, "little")
central_dir_start_offset += 1
return True
except Exception as e:
print(f"Error fixing ZIP file: {e}")
return False
def detect_png_file(png_path):
if not os.path.exists(png_path):
print(f"Error: File '{png_path}' not found")
return False
try:
with open(png_path, "rb") as png_in:
png_header = png_in.read(len(PNG_MAGIC))
if png_header != PNG_MAGIC:
print(f"Not a valid PNG file: {png_path}")
return False
idat_chunks = 0
total_data_size = 0
suspicious_patterns = []
while True:
chunk_len_bytes = png_in.read(4)
if not chunk_len_bytes or len(chunk_len_bytes) < 4:
break
chunk_len = int.from_bytes(chunk_len_bytes, "big")
chunk_type = png_in.read(4)
if not chunk_type or len(chunk_type) < 4:
break
chunk_position = png_in.tell() - 8
if chunk_type == b"IDAT":
idat_chunks += 1
total_data_size += chunk_len
if idat_chunks > 1:
peek_data = png_in.read(16)
if b"PK\x03\x04" in peek_data:
suspicious_patterns.append(f"ZIP header at offset {chunk_position + 8}")
elif b"\x50\x4B\x05\x06" in peek_data:
suspicious_patterns.append(f"ZIP end header at offset {chunk_position + 8}")
elif b"\x89PNG" in peek_data:
suspicious_patterns.append(f"PNG signature at offset {chunk_position + 8}")
elif b"PDF-" in peek_data:
suspicious_patterns.append(f"PDF header at offset {chunk_position + 8}")
elif b"\xFF\xD8\xFF" in peek_data:
suspicious_patterns.append(f"JPEG header at offset {chunk_position + 8}")
elif b"POLY" in peek_data:
suspicious_patterns.append(f"POLY multi-file header at offset {chunk_position + 8}")
png_in.seek(chunk_position + 8)
png_in.seek(chunk_len, 1)
png_in.seek(4, 1)
if chunk_type == b"IEND":
break
is_suspicious = idat_chunks > 1 or len(suspicious_patterns) > 0
print(f"\n[\033[36m*\033[0m] PNG File: \033[1m{png_path}\033[0m")
print(f"[\033[36m+\033[0m] Total IDAT chunks: {idat_chunks}")
if idat_chunks > 1:
print(f"[\033[33m!\033[0m] Multiple IDAT chunks detected ({idat_chunks}), which could indicate embedded data")
if idat_chunks > 1:
print(f"[\033[36m+\033[0m] Total size of all IDAT chunks: {total_data_size} bytes")
if suspicious_patterns:
print("[\033[31m!\033[0m] Potential embedded content detected:")
for pattern in suspicious_patterns:
print(f" [\033[31m>\033[0m] {pattern}")
print("[\033[31m!\033[0m] This file likely contains embedded data")
else:
if idat_chunks > 1:
print("[\033[33m!\033[0m] Multiple IDAT chunks found, but no obvious embedded file signatures detected")
print("[\033[33m!\033[0m] The file might still contain embedded data in an uncommon format")
else:
print("[\033[32m✓\033[0m] No evidence of embedded data found")
return is_suspicious
except Exception as e:
print(f"\033[31m[!] Error analyzing {png_path}: {e}\033[0m")
return False
def detect_file_type(data):
signatures = {
b'\x89PNG\r\n\x1a\n': '.png',
b'\xff\xd8\xff': '.jpg',
b'GIF87a': '.gif',
b'GIF89a': '.gif',
b'%PDF': '.pdf',
b'PK\x03\x04': '.zip',
b'Rar!\x1a\x07': '.rar',
b'\x1f\x8b\x08': '.gz',
b'BM': '.bmp',
b'\x49\x49\x2a\x00': '.tif',
b'\x4d\x4d\x00\x2a': '.tif',
b'RIFF': '.wav',
b'OggS': '.ogg',
b'\x50\x4b\x05\x06': '.zip',
b'\x50\x4b\x07\x08': '.zip',
b'\x75\x73\x74\x61\x72': '.tar',
b'7z\xbc\xaf\x27\x1c': '.7z',
b'\x00\x01\x00\x00\x00': '.ttf',
b'OTTO': '.otf',