-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathFadCrypt.py
More file actions
2250 lines (1904 loc) · 105 KB
/
FadCrypt.py
File metadata and controls
2250 lines (1904 loc) · 105 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
"""
FadCrypt - PyQt6 Entry Point (Cross-Platform)
Modern application locker with PyQt6 UI
Detects platform and loads appropriate platform-specific main window.
"""
# CRITICAL: Handle --cleanup flag FIRST, before any GUI imports
# This is called by the uninstaller to restore disabled tools
import sys
import os
import platform
import tempfile
import io
# CRITICAL: Force unbuffered output for live progress display in PowerShell/CMD
os.environ['PYTHONUNBUFFERED'] = '1'
# CRITICAL: Force UTF-8 encoding everywhere - MUST be first thing
# This handles all cases: console=True, console=False, packaged app, development
try:
import codecs
# Try method 1: reconfigure() - works with console=True
if hasattr(sys.stdout, 'reconfigure'):
try:
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
except Exception:
pass
# Method 2: Wrap with TextIOWrapper - works when stdout exists but can't reconfigure
if sys.stdout is not None and not hasattr(sys.stdout, 'reconfigure'):
try:
if hasattr(sys.stdout, 'buffer'):
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
except Exception:
pass
# Method 3: If stdout is None (console=False), create UTF-8 capable streams
if sys.stdout is None:
try:
sys.stdout = open(os.devnull, 'w', encoding='utf-8', errors='replace')
sys.stderr = open(os.devnull, 'w', encoding='utf-8', errors='replace')
except Exception:
pass
# Set console code page to UTF-8 on Windows
if platform.system() == 'Windows':
try:
import subprocess
subprocess.run(['chcp', '65001'], capture_output=True)
except Exception:
pass
except Exception:
pass # If all else fails, continue anyway
def get_fadcrypt_logs_folder():
"""Get the unified FadCrypt logs folder for the current platform."""
if platform.system() == 'Windows':
appdata = os.environ.get('APPDATA', os.path.expanduser('~'))
logs_dir = os.path.join(appdata, 'FadCrypt', 'logs')
os.makedirs(logs_dir, exist_ok=True)
return logs_dir
else:
# For Linux, keep using home directory for now
user_home = os.path.expanduser('~')
logs_dir = os.path.join(user_home, '.config', 'FadCrypt', 'logs')
os.makedirs(logs_dir, exist_ok=True)
return logs_dir
# Save the original working directory before any changes
# This is important for CLI mode to work in user's current directory
# CRITICAL: When launched from PATH, Windows sets CWD to exe location
# We need to get the ACTUAL terminal directory from environment or parent process
def get_actual_terminal_directory():
"""
Get the actual terminal directory where user ran the command.
When launched from PATH, os.getcwd() returns exe location, not terminal location.
"""
# Try to get from environment variable (we'll set this in a wrapper if needed)
if 'FADCRYPT_LAUNCH_DIR' in os.environ:
return os.environ['FADCRYPT_LAUNCH_DIR']
# For Windows, try to get parent process (cmd/powershell) working directory
if platform.system() == 'Windows':
try:
import psutil
# Get parent process (cmd.exe or powershell.exe)
parent = psutil.Process(os.getppid())
# Get the current working directory of the parent process
parent_cwd = parent.cwd()
return parent_cwd
except (ImportError, Exception):
# If psutil not available or fails, fall back to os.getcwd()
pass
# Fallback to os.getcwd()
return os.getcwd()
ORIGINAL_CWD = get_actual_terminal_directory()
# Global verbose flag - set to True if --verbose is in sys.argv
VERBOSE_MODE = '--verbose' in sys.argv
# CRITICAL FIX: Ensure working directory is correct for PyInstaller DLL loading
# This fixes CMD/PowerShell working directory mismatch when launched from .lnk shortcuts
if hasattr(sys, '_MEIPASS'):
# Running from PyInstaller bundle - set cwd to bundle directory for DLL loading
exe_dir = os.path.dirname(sys.executable)
os.chdir(exe_dir)
# Also ensure TMPDIR points to the correct temp location
os.environ['TMPDIR'] = tempfile.gettempdir()
os.environ['TEMP'] = tempfile.gettempdir()
os.environ['TMP'] = tempfile.gettempdir()
# IMPORTANT: Restore working directory immediately for CLI operations
# Check if this is a CLI operation (not GUI, not installer operations)
is_cli_operation = (
'--cli' in sys.argv or
'--lock' in sys.argv or
'--unlock' in sys.argv or
'--list' in sys.argv or
'--list-locked' in sys.argv or
(len(sys.argv) == 1) # No arguments = TUI mode
)
is_gui_operation = '--gui' in sys.argv or '--auto-monitor' in sys.argv
# Restore original directory for CLI operations (but not for GUI)
if is_cli_operation and not is_gui_operation:
try:
os.chdir(ORIGINAL_CWD)
except (OSError, FileNotFoundError):
# If original directory no longer exists, stay in current directory
pass
# CRITICAL: Define safe_print and safe_flush BEFORE they're used in CLI handling
def safe_print(*args, **kwargs):
"""Safely print to stdout, handling None or closed streams"""
try:
if sys.stdout is not None and hasattr(sys.stdout, 'write'):
# Try to print normally
print(*args, **kwargs)
except (AttributeError, ValueError, OSError, BrokenPipeError):
# If stdout is broken or None, silently fail - we can't do much else
pass
def safe_flush(stream=None):
"""Safely flush stdout/stderr even if None or doesn't have flush method"""
if stream is None:
stream = sys.stdout
if stream is not None and hasattr(stream, 'flush'):
try:
stream.flush()
except (AttributeError, ValueError, OSError):
pass
# NOTE: Installer will perform context menu registration and PATH changes
# Use --register-context to register context menu (this is invoked by installer)
if '--register-context' in sys.argv:
# SECURITY: Require password UNLESS called with --internal-auth flag
# The --internal-auth flag is only used by GUI/installer after they've authenticated
if '--internal-auth' not in sys.argv:
from colorama import just_fix_windows_console
just_fix_windows_console()
from core.cli.colors import print_error
from core.password_manager import PasswordManager
from core.cli.password_prompt import PasswordPrompt
from core.crypto_manager import CryptoManager
# Get config folder
if platform.system() == "Windows":
appdata = os.environ.get('APPDATA', os.path.expanduser('~'))
config_folder = os.path.join(appdata, 'FadCrypt', 'config')
else:
config_folder = os.path.join(os.path.expanduser('~'), '.config', 'FadCrypt')
password_file = os.path.join(config_folder, "encrypted_password.bin")
recovery_codes_file = os.path.join(config_folder, "recovery_codes.json")
crypto_manager = CryptoManager()
password_manager = PasswordManager(password_file, crypto_manager, recovery_codes_file)
password_prompt = PasswordPrompt(password_manager)
# Verify password before allowing registration
if not password_prompt.verify_password():
print_error("Authentication failed. Context menu registration cancelled.")
sys.exit(1)
import subprocess
import platform
print("[CONTEXT MENU] Registering FadCrypt context menu...", flush=True)
# Log to file for debugging
try:
log_file = os.path.join(get_fadcrypt_logs_folder(), 'fadcrypt_register_context.log')
with open(log_file, 'w') as f:
f.write(f"[REGISTER-CONTEXT] Started at {os.times()}\n")
f.write(f"[REGISTER-CONTEXT] Executable: {sys.executable}\n")
f.write(f"[REGISTER-CONTEXT] Arguments: {sys.argv}\n")
f.write(f"[REGISTER-CONTEXT] Platform: {platform.system()}\n")
except Exception as e:
print(f"[CONTEXT MENU] Could not create log file: {e}", flush=True)
try:
from core.windows.shell_extension import ContextMenuManager
manager = ContextMenuManager()
success = manager.force_register_context_menu()
if success:
print("[CONTEXT MENU] Registration completed successfully", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Force registration result: True\n")
# Always restart explorer after registration to ensure context menu takes effect
print("[CONTEXT MENU] Registration completed, restarting Explorer...", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Restarting Explorer...\n")
try:
subprocess.run(['taskkill', '/f', '/im', 'explorer.exe'],
stderr=subprocess.DEVNULL, timeout=5)
subprocess.Popen('explorer.exe')
print("[CONTEXT MENU] Explorer restarted successfully", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Explorer restarted successfully\n")
except Exception as e:
print(f"[CONTEXT MENU] Warning: Could not restart Explorer: {e}", flush=True)
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Warning: Could not restart Explorer: {e}\n")
else:
print("[CONTEXT MENU] Registration failed", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Registration failed\n")
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Completed successfully\n")
except Exception as e:
print(f"[CONTEXT MENU] Error during registration: {e}", flush=True)
import traceback
traceback.print_exc()
try:
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Error: {e}\n")
f.write(f"[REGISTER-CONTEXT] Traceback: {traceback.format_exc()}\n")
except:
pass
sys.exit(0)
# Use --unregister-context to unregister context menu (this is invoked by uninstaller)
if '--unregister-context' in sys.argv:
# SECURITY: Require password UNLESS called with --internal-auth flag
if '--internal-auth' not in sys.argv:
from colorama import just_fix_windows_console
just_fix_windows_console()
from core.cli.colors import print_error
from core.password_manager import PasswordManager
from core.cli.password_prompt import PasswordPrompt
from core.crypto_manager import CryptoManager
# Get config folder
if platform.system() == "Windows":
appdata = os.environ.get('APPDATA', os.path.expanduser('~'))
config_folder = os.path.join(appdata, 'FadCrypt', 'config')
else:
config_folder = os.path.join(os.path.expanduser('~'), '.config', 'FadCrypt')
password_file = os.path.join(config_folder, "encrypted_password.bin")
recovery_codes_file = os.path.join(config_folder, "recovery_codes.json")
crypto_manager = CryptoManager()
password_manager = PasswordManager(password_file, crypto_manager, recovery_codes_file)
password_prompt = PasswordPrompt(password_manager)
# Verify password before allowing unregistration
if not password_prompt.verify_password():
print_error("Authentication failed. Context menu unregistration cancelled.")
sys.exit(1)
import subprocess
import platform
print("[CONTEXT MENU] Unregistering FadCrypt context menu...", flush=True)
# Log to file for debugging
try:
log_file = os.path.join(get_fadcrypt_logs_folder(), 'fadcrypt_unregister_context.log')
with open(log_file, 'w') as f:
f.write(f"[UNREGISTER-CONTEXT] Started at {os.times()}\n")
f.write(f"[UNREGISTER-CONTEXT] Executable: {sys.executable}\n")
f.write(f"[UNREGISTER-CONTEXT] Arguments: {sys.argv}\n")
f.write(f"[UNREGISTER-CONTEXT] Platform: {platform.system()}\n")
except Exception as e:
print(f"[CONTEXT MENU] Could not create log file: {e}", flush=True)
try:
from core.windows.shell_extension import ContextMenuManager
manager = ContextMenuManager()
success = manager.unregister_context_menu()
if success:
print("[CONTEXT MENU] Unregistration completed successfully", flush=True)
with open(log_file, 'a') as f:
f.write("[UNREGISTER-CONTEXT] Unregistration result: True\n")
# Always restart explorer after unregistration to ensure context menu changes take effect
print("[CONTEXT MENU] Unregistration completed, restarting Explorer...", flush=True)
with open(log_file, 'a') as f:
f.write("[UNREGISTER-CONTEXT] Restarting Explorer...\n")
try:
subprocess.run(['taskkill', '/f', '/im', 'explorer.exe'],
stderr=subprocess.DEVNULL, timeout=5)
subprocess.Popen('explorer.exe')
print("[CONTEXT MENU] Explorer restarted successfully", flush=True)
with open(log_file, 'a') as f:
f.write("[UNREGISTER-CONTEXT] Explorer restarted successfully\n")
except Exception as e:
print(f"[CONTEXT MENU] Warning: Could not restart Explorer: {e}", flush=True)
with open(log_file, 'a') as f:
f.write(f"[UNREGISTER-CONTEXT] Warning: Could not restart Explorer: {e}\n")
else:
print("[CONTEXT MENU] Unregistration failed or no entries found", flush=True)
with open(log_file, 'a') as f:
f.write("[UNREGISTER-CONTEXT] Unregistration failed or no entries found\n")
with open(log_file, 'a') as f:
f.write(f"[UNREGISTER-CONTEXT] Completed successfully\n")
except Exception as e:
print(f"[CONTEXT MENU] Error during unregistration: {e}", flush=True)
import traceback
traceback.print_exc()
try:
with open(log_file, 'a') as f:
f.write(f"[UNREGISTER-CONTEXT] Error: {e}\n")
f.write(f"[UNREGISTER-CONTEXT] Traceback: {traceback.format_exc()}\n")
except:
pass
sys.exit(0)
try:
# Log to file for debugging installer issues
import tempfile
log_file = os.path.join(tempfile.gettempdir(), 'fadcrypt_register_context.log')
with open(log_file, 'w') as f:
f.write(f"[REGISTER-CONTEXT] Started at {os.times()}\n")
f.write(f"[REGISTER-CONTEXT] Executable: {sys.executable}\n")
f.write(f"[REGISTER-CONTEXT] Arguments: {sys.argv}\n")
f.write(f"[REGISTER-CONTEXT] Platform: {platform.system()}\n")
from core.windows.shell_extension import ContextMenuManager
import subprocess
manager = ContextMenuManager()
# Force registration on every install to ensure it's always up to date
success = manager.force_register_context_menu()
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Force registration result: {success}\n")
if success:
# Always restart explorer after registration to ensure context menu takes effect
print("[CONTEXT MENU] Registration completed, restarting Explorer...", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Restarting Explorer...\n")
try:
subprocess.run(['taskkill', '/f', '/im', 'explorer.exe'],
stderr=subprocess.DEVNULL, timeout=5)
subprocess.Popen('explorer.exe')
print("[CONTEXT MENU] Explorer restarted successfully", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Explorer restarted successfully\n")
except Exception as e:
print(f"[CONTEXT MENU] Warning: Could not restart Explorer: {e}", flush=True)
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Warning: Could not restart Explorer: {e}\n")
else:
print("[CONTEXT MENU] Registration failed", flush=True)
with open(log_file, 'a') as f:
f.write("[REGISTER-CONTEXT] Registration failed\n")
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Completed successfully\n")
except Exception as e:
print(f"[CONTEXT MENU] Error during registration: {e}", flush=True)
import traceback
traceback.print_exc()
try:
with open(log_file, 'a') as f:
f.write(f"[REGISTER-CONTEXT] Error: {e}\n")
f.write(f"[REGISTER-CONTEXT] Traceback: {traceback.format_exc()}\n")
except:
pass
sys.exit(0)
# DEV MODE: Test context menu without registry (for development/testing)
# Usage: python FadCrypt.py --test-context-lock <path> [<path2> ...]
# python FadCrypt.py --test-context-unlock <path> [<path2> ...]
if '--test-context-lock' in sys.argv or '--test-context-unlock' in sys.argv:
print(f"[DEV MODE] Testing context menu: {sys.argv}", flush=True)
try:
if '--test-context-lock' in sys.argv:
idx = sys.argv.index('--test-context-lock')
# Get all paths after the flag (filter out other flags)
paths = [arg for arg in sys.argv[idx + 1:] if not arg.startswith('--')]
if not paths:
print(f"[DEV MODE] No paths provided", flush=True)
sys.exit(1)
if len(paths) == 1:
# Single file
print(f"[DEV MODE] Test-locking file: {paths[0]}", flush=True)
from core.windows.cli_lock_handler import lock_file_with_password
success, info = lock_file_with_password(paths[0])
print(f"[DEV MODE] Test-lock result: {success}", flush=True)
else:
# Batch operation
print(f"[DEV MODE] Test-locking {len(paths)} files: {paths}", flush=True)
from core.windows.cli_lock_handler import lock_multiple_with_password
success, info = lock_multiple_with_password(paths)
print(f"[DEV MODE] Test-lock result: {success} - {info['success']}/{len(paths)} succeeded", flush=True)
sys.exit(0 if success else 1)
elif '--test-context-unlock' in sys.argv:
idx = sys.argv.index('--test-context-unlock')
# Get all paths after the flag (filter out other flags)
paths = [arg for arg in sys.argv[idx + 1:] if not arg.startswith('--')]
if not paths:
print(f"[DEV MODE] No paths provided", flush=True)
sys.exit(1)
if len(paths) == 1:
# Single file
print(f"[DEV MODE] Test-unlocking file: {paths[0]}", flush=True)
from core.windows.cli_lock_handler import unlock_file_with_password
success, info = unlock_file_with_password(paths[0])
print(f"[DEV MODE] Test-unlock result: {success}", flush=True)
else:
# Batch operation
print(f"[DEV MODE] Test-unlocking {len(paths)} files: {paths}", flush=True)
from core.windows.cli_lock_handler import unlock_multiple_with_password
success, info = unlock_multiple_with_password(paths)
print(f"[DEV MODE] Test-unlock result: {success} - {info['success']}/{len(paths)} succeeded", flush=True)
sys.exit(0 if success else 1)
except Exception as e:
print(f"[DEV MODE] Error: {e}", flush=True)
import traceback
traceback.print_exc()
sys.exit(1)
# Handle --context-lock and --context-unlock from context menu
if '--context-lock' in sys.argv or '--context-unlock' in sys.argv:
safe_print(f"[CONTEXT MENU] Processing context menu arguments: {sys.argv}")
try:
if '--context-lock' in sys.argv:
idx = sys.argv.index('--context-lock')
if idx + 1 < len(sys.argv):
# Get the first path after --context-lock
first_path = sys.argv[idx + 1]
# Use batch coordinator to handle multiple context menu calls
if platform.system() == 'Windows':
from core.windows.batch_coordinator import coordinate_batch_operation
paths, should_show_ui = coordinate_batch_operation('lock', first_path)
else:
# On Linux, no batch coordination needed (uses symlink approach)
paths = [arg for arg in sys.argv[idx + 1:] if not arg.startswith('--')]
should_show_ui = True
# Only show UI and process if this is the primary caller
if should_show_ui:
if not paths:
safe_print(f"[CONTEXT MENU] No paths provided")
sys.exit(1)
safe_print(f"[CONTEXT MENU] Locking {len(paths)} item(s): {paths}")
from core.windows.cli_lock_handler import lock_multiple_with_password
success, info = lock_multiple_with_password(paths)
safe_print(f"[CONTEXT MENU] Lock result: {success}")
sys.exit(0 if success else 1)
else:
# Secondary caller - wait for primary to complete
safe_print(f"[CONTEXT MENU] Waiting for primary caller to process batch...")
sys.exit(0)
elif '--context-unlock' in sys.argv:
idx = sys.argv.index('--context-unlock')
if idx + 1 < len(sys.argv):
# Get the first path after --context-unlock
first_path = sys.argv[idx + 1]
# Use batch coordinator to handle multiple context menu calls
if platform.system() == 'Windows':
from core.windows.batch_coordinator import coordinate_batch_operation
paths, should_show_ui = coordinate_batch_operation('unlock', first_path)
else:
# On Linux, no batch coordination needed
paths = [arg for arg in sys.argv[idx + 1:] if not arg.startswith('--')]
should_show_ui = True
# Only show UI and process if this is the primary caller
if should_show_ui:
if not paths:
safe_print(f"[CONTEXT MENU] No paths provided")
sys.exit(1)
safe_print(f"[CONTEXT MENU] Unlocking {len(paths)} item(s): {paths}")
from core.windows.cli_lock_handler import unlock_multiple_with_password
success, info = unlock_multiple_with_password(paths)
safe_print(f"[CONTEXT MENU] Unlock result: {success}")
sys.exit(0 if success else 1)
else:
# Secondary caller - wait for primary to complete
safe_print(f"[CONTEXT MENU] Waiting for primary caller to process batch...")
sys.exit(0)
except Exception as e:
safe_print(f"[CLI] Error: {e}")
import traceback
traceback.print_exc(file=sys.stderr if sys.stderr is not None else None)
sys.exit(1)
if '--cleanup' in sys.argv:
# SECURITY: Require password UNLESS called with --internal-auth flag
if '--internal-auth' not in sys.argv:
from colorama import just_fix_windows_console
just_fix_windows_console()
from core.cli.colors import print_error
from core.password_manager import PasswordManager
from core.cli.password_prompt import PasswordPrompt
from core.crypto_manager import CryptoManager
# Get config folder
if platform.system() == "Windows":
appdata = os.environ.get('APPDATA', os.path.expanduser('~'))
config_folder = os.path.join(appdata, 'FadCrypt', 'config')
else:
config_folder = os.path.join(os.path.expanduser('~'), '.config', 'FadCrypt')
password_file = os.path.join(config_folder, "encrypted_password.bin")
recovery_codes_file = os.path.join(config_folder, "recovery_codes.json")
crypto_manager = CryptoManager()
password_manager = PasswordManager(password_file, crypto_manager, recovery_codes_file)
password_prompt = PasswordPrompt(password_manager)
# Verify password before allowing cleanup
if not password_prompt.verify_password():
print_error("Authentication failed. Cleanup operation cancelled.")
sys.exit(1)
import subprocess
import platform
print("[CLEANUP] Starting FadCrypt cleanup...", flush=True)
# Log to file for debugging uninstall issues
try:
log_file = os.path.join(get_fadcrypt_logs_folder(), 'fadcrypt_cleanup.log')
with open(log_file, 'w') as f:
f.write(f"[CLEANUP] Started at {os.times()}\n")
f.write(f"[CLEANUP] Executable: {sys.executable}\n")
f.write(f"[CLEANUP] Arguments: {sys.argv}\n")
f.write(f"[CLEANUP] Platform: {platform.system()}\n")
except Exception as e:
print(f"[CLEANUP] Could not create log file: {e}", flush=True)
try:
system = platform.system()
if system == "Linux":
# Get user's home directory (handle sudo context)
if 'SUDO_USER' in os.environ:
import pwd
user_home = pwd.getpwnam(os.environ['SUDO_USER']).pw_dir
print(f"[CLEANUP] Running as sudo, user home: {user_home}", flush=True)
else:
user_home = os.path.expanduser('~')
print(f"[CLEANUP] User home: {user_home}", flush=True)
fadcrypt_folder = os.path.join(user_home, '.config', 'FadCrypt')
fadcrypt_backup_folder = os.path.join(user_home, '.local', 'share', 'FadCrypt', 'Backup')
# CRITICAL: Remove all locks before deleting data directories
print("[CLEANUP] Removing locks from all locked items...", flush=True)
try:
config_folder_path = os.path.join(fadcrypt_folder, 'config')
config_file = os.path.join(config_folder_path, 'apps_config.json')
if os.path.exists(config_file):
import json
# Read and close file immediately to release handle
with open(config_file, 'r') as f:
config = json.load(f)
locked_items = config.get("locked_files_and_folders", [])
if locked_items:
print(f"[CLEANUP] Found {len(locked_items)} locked items", flush=True)
# Create a temporary file lock manager to unlock items
from core.linux.file_lock_manager_linux import FileLockManagerLinux
lock_manager = FileLockManagerLinux(config_folder_path)
unlocked_count = 0
for item in locked_items:
try:
item_path = item.get('path', '')
item_name = item.get('name', os.path.basename(item_path))
# Unlock via file lock manager (handles daemon communication)
if lock_manager.remove_item(item_path):
print(f"[CLEANUP] ✓ Unlocked: {item_name}", flush=True)
unlocked_count += 1
else:
print(f"[CLEANUP] ⚠ Could not unlock: {item_name}", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Error unlocking item {item_name}: {e}", flush=True)
if unlocked_count > 0:
print(f"[CLEANUP] Successfully unlocked {unlocked_count}/{len(locked_items)} items", flush=True)
# Force garbage collection to release any remaining handles
import gc
gc.collect()
else:
print("[CLEANUP] No locked items found", flush=True)
else:
print("[CLEANUP] Config file not found, skipping unlock", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Could not unlock items: {e}", flush=True)
import traceback
traceback.print_exc()
# Give system time to release file handles
import time
time.sleep(0.5)
# CRITICAL: Remove immutable flags before deletion (files may have chattr +i from file protection)
folders_to_clean = [
fadcrypt_folder,
fadcrypt_backup_folder
]
print("[CLEANUP] Removing immutable flags from protected files...", flush=True)
for folder in folders_to_clean:
if os.path.exists(folder):
try:
# Use elevated daemon for chattr operations
from core.linux.elevated_daemon_client import get_elevated_client
daemon_client = get_elevated_client()
if daemon_client and daemon_client.is_available():
# Find all files in the folder
import glob
all_files = []
for root, dirs, files in os.walk(folder):
for file in files:
all_files.append(os.path.join(root, file))
if all_files:
# Remove immutable flags via daemon (batch operation)
success, message = daemon_client.chattr(all_files, set_immutable=False)
if success:
print(f"[CLEANUP] ✓ Removed immutable flags from {len(all_files)} files in {folder}", flush=True)
else:
print(f"[CLEANUP] ⚠ Daemon failed to remove immutable flags: {message}", flush=True)
else:
# Fallback: Try direct chattr (may fail without root)
result = subprocess.run(
['find', folder, '-type', 'f', '-exec', 'chattr', '-i', '{}', '+'],
capture_output=True,
text=True,
check=False,
timeout=10
)
if result.returncode == 0:
print(f"[CLEANUP] ✓ Removed immutable flags from {folder}", flush=True)
else:
print(f"[CLEANUP] ⚠ Could not remove immutable flags via chattr (daemon not available)", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Could not remove immutable flags from {folder}: {e}", flush=True)
# Remove all FadCrypt config and backup folders
print("[CLEANUP] Removing FadCrypt data directories...", flush=True)
folders_to_remove = [
fadcrypt_folder,
fadcrypt_backup_folder
]
removed_count = 0
for folder in folders_to_remove:
if os.path.exists(folder):
try:
import shutil
shutil.rmtree(folder)
print(f"[CLEANUP] ✓ Removed: {folder}", flush=True)
removed_count += 1
except PermissionError as e:
# Try with sudo if permission denied
try:
subprocess.run(['rm', '-rf', folder], check=True, timeout=10)
print(f"[CLEANUP] ✓ Removed (via rm): {folder}", flush=True)
removed_count += 1
except Exception as rm_error:
print(f"[CLEANUP] ⚠ Warning: Could not remove {folder}: {rm_error}", flush=True)
except Exception as e:
print(f"[CLEANUP] ⚠ Warning: Could not remove {folder}: {e}", flush=True)
if removed_count > 0:
print(f"[CLEANUP] ✓ Removed {removed_count} data directories", flush=True)
# List of common system tools that might have been disabled
all_tools = [
'/usr/bin/gnome-terminal',
'/usr/bin/konsole',
'/usr/bin/xterm',
'/usr/bin/gnome-system-monitor',
'/usr/bin/htop',
'/usr/bin/top',
'/usr/bin/gnome-control-center'
]
print(f"[CLEANUP] Checking {len(all_tools)} common system tools...", flush=True)
# Find tools that need restoring
tools_to_restore = []
for tool in all_tools:
if os.path.exists(tool):
try:
stat_info = os.stat(tool)
# Check if execute permission is missing (was disabled)
if not (stat_info.st_mode & 0o111):
tools_to_restore.append(tool)
print(f"[CLEANUP] Will restore: {tool}", flush=True)
except Exception as e:
print(f"[CLEANUP] Error checking {tool}: {e}", flush=True)
# Restore permissions for disabled tools
if tools_to_restore:
print(f"[CLEANUP] Restoring {len(tools_to_restore)} disabled tools...", flush=True)
chmod_commands = [f'chmod 755 "{tool}"' for tool in tools_to_restore]
full_command = ' && '.join(chmod_commands)
# Direct chmod (prerm script runs with root)
result = subprocess.run(['bash', '-c', full_command],
capture_output=True,
text=True,
check=False)
if result.returncode == 0:
print(f"[CLEANUP] OK Restored {len(tools_to_restore)} tools", flush=True)
else:
print(f"[CLEANUP] WARN Warning: {result.stderr}", flush=True)
else:
print("[CLEANUP] No disabled tools found", flush=True)
# Remove lock file if it exists
lock_file = '/tmp/fadcrypt.lock'
if os.path.exists(lock_file):
try:
os.remove(lock_file)
print(f"[CLEANUP] ✓ Removed lock file: {lock_file}", flush=True)
except PermissionError:
# Lock file might be owned by different user - cleanup script runs as root
try:
subprocess.run(['rm', '-f', lock_file], check=True, timeout=5)
print(f"[CLEANUP] ✓ Removed lock file: {lock_file}", flush=True)
except Exception as e:
print(f"[CLEANUP] ⚠ Warning: Could not remove lock file: {e}", flush=True)
except Exception as e:
print(f"[CLEANUP] ⚠ Warning: Could not remove lock file: {e}", flush=True)
# Remove autostart entry
autostart_file = os.path.join(user_home, '.config', 'autostart', 'fadcrypt.desktop')
if os.path.exists(autostart_file):
try:
os.remove(autostart_file)
print(f"[CLEANUP] ✓ Removed autostart entry: {autostart_file}", flush=True)
except Exception as e:
print(f"[CLEANUP] ⚠ Warning: Could not remove autostart entry: {e}", flush=True)
print("[CLEANUP] ✓ Cleanup completed successfully", flush=True)
elif system == "Windows":
print("[CLEANUP] Windows cleanup - restoring system tools and cleaning registry...", flush=True)
import winreg
# Remove FadCrypt from PATH
print("[CLEANUP] Removing FadCrypt from PATH...", flush=True)
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Environment", 0, winreg.KEY_READ | winreg.KEY_SET_VALUE)
try:
current_path, _ = winreg.QueryValueEx(key, "Path")
if not current_path:
print("[CLEANUP] [INFO] PATH is empty", flush=True)
else:
# Get the installation directory (where this executable should be)
# During uninstall, we should be running from the installed location
exe_path = sys.executable
if hasattr(sys, '_MEIPASS'):
# Running from PyInstaller bundle - get the directory containing the exe
exe_dir = os.path.dirname(exe_path)
else:
# Running from source - don't modify PATH
exe_dir = None
if exe_dir:
print(f"[CLEANUP] Removing directory from PATH: {exe_dir}", flush=True)
# Split PATH and filter out the exe directory
path_parts = current_path.split(';')
original_count = len(path_parts)
# Remove empty strings and the exe directory
filtered_parts = [p for p in path_parts if p and p.strip() and p.strip() != exe_dir]
if len(filtered_parts) != original_count:
new_path = ';'.join(filtered_parts)
winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
print("[CLEANUP] OK Removed FadCrypt from PATH", flush=True)
else:
print("[CLEANUP] INFO FadCrypt directory not found in PATH", flush=True)
else:
print("[CLEANUP] INFO Not running from PyInstaller bundle, skipping PATH removal", flush=True)
except FileNotFoundError:
print("[CLEANUP] INFO PATH environment variable not found", flush=True)
finally:
winreg.CloseKey(key)
# Notify system of environment change
try:
import ctypes
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
result = ctypes.windll.user32.SendMessageTimeoutW(
HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",
SMTO_ABORTIFHUNG, 5000, None
)
if result:
print("[CLEANUP] [OK] Notified system of PATH change", flush=True)
except Exception as e:
print("[CLEANUP] [INFO] Could not notify system of PATH change: {e}", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Could not remove from PATH: {e}", flush=True)
# Registry keys that FadCrypt may have disabled
# Note: These are set in HKEY_USERS\{user_sid}, so we need to find the current user's SID
import win32security
import win32api
import win32con
try:
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
user_sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
user_sid_str = win32security.ConvertSidToStringSid(user_sid)
win32api.CloseHandle(token)
keys_to_restore = [
# Note: CMD is not managed by system tools anymore
(r'Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableTaskMgr'),
(r'Software\Microsoft\Windows\CurrentVersion\Policies\Explorer', 'NoControlPanel'),
(r'Software\Microsoft\Windows\CurrentVersion\Policies\System', 'DisableRegistryTools')
]
restored_count = 0
for reg_path, value_name in keys_to_restore:
try:
full_reg_path = f"{user_sid_str}\\{reg_path}"
key = winreg.OpenKey(winreg.HKEY_USERS, full_reg_path, 0, winreg.KEY_SET_VALUE)
try:
winreg.DeleteValue(key, value_name)
restored_count += 1
print(f"[CLEANUP] Restored: {value_name}", flush=True)
except FileNotFoundError:
pass # Value doesn't exist
finally:
winreg.CloseKey(key)
except FileNotFoundError:
pass # Key doesn't exist
except Exception as e:
print(f"[CLEANUP] Warning: Could not restore {value_name}: {e}", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Could not get user SID for registry cleanup: {e}", flush=True)
# Remove FadCrypt context menu entries
print("[CLEANUP] Removing FadCrypt context menu entries...", flush=True)
try:
from core.windows.shell_extension import ContextMenuManager
manager = ContextMenuManager()
if manager.unregister_context_menu():
print("[CLEANUP] [OK] Removed context menu entries", flush=True)
# Restart File Explorer to clear context menu cache
print("[CLEANUP] Restarting File Explorer to clear context menu cache...", flush=True)
try:
# Kill explorer and restart it properly
subprocess.run(['taskkill.exe', '/f', '/im', 'explorer.exe'],
capture_output=True, timeout=5)
# Give it a moment to fully terminate
import time
time.sleep(1)
# Start explorer again (don't wait for it since it's long-running)
subprocess.Popen(['explorer.exe'])
print("[CLEANUP] [OK] File Explorer restarted (context menu cache cleared)", flush=True)
except Exception as e:
print(f"[CLEANUP] WARNING: Could not restart File Explorer: {e}", flush=True)
print("[CLEANUP] INFO: Context menu changes will take effect on next login", flush=True)
else:
print("[CLEANUP] [INFO] No context menu entries found to remove", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Could not remove context menu entries: {e}", flush=True)
# Remove from Windows startup
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0, winreg.KEY_SET_VALUE)
winreg.DeleteValue(key, "FadCrypt")
winreg.CloseKey(key)
print("[CLEANUP] Removed from Windows startup", flush=True)
except FileNotFoundError:
pass # Not in startup
except Exception as e:
print(f"[CLEANUP] Warning: Could not remove startup entry: {e}", flush=True)
print(f"[CLEANUP] OK Restored {restored_count} Windows settings", flush=True)
# CRITICAL: Remove all locks before deleting data directories
print("[CLEANUP] Removing locks from all locked items...", flush=True)
try:
appdata = os.environ.get('APPDATA', '')
config_file = os.path.join(appdata, 'FadCrypt', 'config', 'apps_config.json')
if os.path.exists(config_file):
import json
# Read and close file immediately to release handle
with open(config_file, 'r') as f:
config = json.load(f)
locked_items = config.get("locked_files_and_folders", [])
if locked_items:
print(f"[CLEANUP] Found {len(locked_items)} locked items", flush=True)
# Create a temporary file lock manager to unlock items
from core.windows.file_lock_manager_windows import FileLockManagerWindows
temp_config = os.path.join(appdata, 'FadCrypt', 'config')
lock_manager = FileLockManagerWindows(temp_config)
unlocked_count = 0
for item in locked_items:
try:
item_path = item.get('path', '')
item_name = item.get('name', os.path.basename(item_path))
if lock_manager.remove_item(item_path):
print(f"[CLEANUP] ✓ Unlocked: {item_name}", flush=True)
unlocked_count += 1
else:
print(f"[CLEANUP] ⚠ Could not unlock: {item_name}", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Error unlocking item: {e}", flush=True)
if unlocked_count > 0:
print(f"[CLEANUP] Successfully unlocked {unlocked_count}/{len(locked_items)} items", flush=True)
# Force garbage collection to release any remaining handles
import gc
gc.collect()
else:
print("[CLEANUP] No locked items found", flush=True)
else:
print("[CLEANUP] Config file not found, skipping unlock", flush=True)
except Exception as e:
print(f"[CLEANUP] Warning: Could not unlock items: {e}", flush=True)
import traceback
traceback.print_exc()
# Give system time to release file handles
import time
time.sleep(0.5)
# Remove FadCrypt data directories
print("[CLEANUP] Removing FadCrypt data directories...", flush=True)
import shutil
# Get standard Windows directories
appdata = os.environ.get('APPDATA', '')
local_appdata = os.environ.get('LOCALAPPDATA', '')
programdata = os.environ.get('PROGRAMDATA', '')
data_dirs_to_remove = []
if appdata:
data_dirs_to_remove.append(os.path.join(appdata, 'FadCrypt'))