-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnulltrace.py
More file actions
1146 lines (1005 loc) · 43.4 KB
/
nulltrace.py
File metadata and controls
1146 lines (1005 loc) · 43.4 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
# ─────────────────────────────────────────────────────────────────────
# NullTrace v2.5 — Modern System Trace Removal Tool
# Developed by benzoXdev
# ─────────────────────────────────────────────────────────────────────
import os
import sys
import json
import time
import shutil
import string
import ctypes
import pathlib
import tempfile
import argparse
import threading
import subprocess
import datetime
import random
from dataclasses import dataclass, field
from typing import Optional
# ─── Windows Console Fix ────────────────────────────────────────────
if sys.platform.startswith("win"):
try:
kernel32 = ctypes.windll.kernel32
handle = kernel32.GetStdHandle(-11)
mode = ctypes.c_ulong()
kernel32.GetConsoleMode(handle, ctypes.byref(mode))
kernel32.SetConsoleMode(handle, mode.value | 0x0004)
kernel32.SetConsoleOutputCP(65001)
except Exception:
pass
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.progress import (
Progress, SpinnerColumn, BarColumn, TextColumn,
TimeElapsedColumn, MofNCompleteColumn
)
from rich.text import Text
from rich.align import Align
from rich.rule import Rule
from rich.prompt import Confirm, Prompt
from rich import box
# ─── Constants ──────────────────────────────────────────────────────
VERSION = "2.5"
AUTHOR = "benzoXdev"
GITHUB = "github.com/benzoXdev/NullTrace"
ACCENT = "bright_magenta"
ACCENT2 = "bright_cyan"
SUCCESS = "bright_green"
ERROR_C = "bright_red"
WARNING = "bright_yellow"
DIM = "dim"
TEXT_C = "white"
console = Console(force_terminal=True)
# ─── Stats Tracker ──────────────────────────────────────────────────
@dataclass
class CleanStats:
files_overwritten: int = 0
files_deleted: int = 0
folders_deleted: int = 0
registry_keys_deleted: int = 0
dns_flushed: bool = False
bytes_freed: int = 0
errors: int = 0
skipped: int = 0
error_details: list = field(default_factory=list)
log_lines: list = field(default_factory=list)
_lock: threading.Lock = field(default_factory=threading.Lock)
def add_file(self, size: int = 0):
with self._lock:
self.files_deleted += 1
self.bytes_freed += size
def add_overwrite(self):
with self._lock:
self.files_overwritten += 1
def add_folder(self):
with self._lock:
self.folders_deleted += 1
def add_registry(self):
with self._lock:
self.registry_keys_deleted += 1
def add_error(self, detail: str):
with self._lock:
self.errors += 1
if len(self.error_details) < 50:
self.error_details.append(detail)
def add_skip(self):
with self._lock:
self.skipped += 1
def log(self, action: str, category: str, target: str, status: str = "OK"):
with self._lock:
ts = datetime.datetime.now().strftime("%H:%M:%S")
self.log_lines.append(f"[{ts}] [{status}] [{category}] {action}: {target}")
@property
def total_actions(self):
return self.files_deleted + self.folders_deleted + self.registry_keys_deleted
def format_bytes(self, b: int) -> str:
val = float(b)
for unit in ["B", "KB", "MB", "GB", "TB"]:
if val < 1024:
return f"{val:.1f} {unit}"
val /= 1024
return f"{val:.1f} PB"
# ─── OS Detection ───────────────────────────────────────────────────
def detect_os() -> str:
if sys.platform.startswith("win"):
return "Windows"
elif sys.platform.startswith("linux"):
return "Linux"
return "Unknown"
def is_admin() -> bool:
os_name = detect_os()
if os_name == "Windows":
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except Exception:
return False
elif os_name == "Linux":
try:
return os.geteuid() == 0
except Exception:
return False
return False
def request_elevation():
"""Re-launch the script with admin/root privileges."""
os_name = detect_os()
if os_name == "Windows":
try:
params = " ".join([f'"{arg}"' for arg in sys.argv])
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, params, None, 1
)
sys.exit(0)
except Exception:
return False
elif os_name == "Linux":
try:
os.execvp("sudo", ["sudo", sys.executable] + sys.argv)
except Exception:
return False
return False
def set_title(title: str):
os_name = detect_os()
if os_name == "Windows":
try:
ctypes.windll.kernel32.SetConsoleTitleW(title)
except Exception:
pass
elif os_name == "Linux":
sys.stdout.write(f"\x1b]2;{title}\x07")
sys.stdout.flush()
# ─── Path Resolution ────────────────────────────────────────────────
def get_env_paths() -> dict:
os_name = detect_os()
paths = {}
if os_name == "Windows":
paths = {
"%PATH_APPDATA_LOCAL%": os.getenv("LOCALAPPDATA", ""),
"%PATH_APPDATA_ROAMING%": os.getenv("APPDATA", ""),
"%PATH_USER%": os.getenv("USERPROFILE", ""),
"%PATH_SYSTEM_ROOT%": os.getenv("SystemRoot", ""),
"%PATH_PROGRAM_DATA%": os.getenv("ProgramData", ""),
"%PATH_TOR%": "",
}
elif os_name == "Linux":
user_home = os.path.expanduser("~")
paths = {
"%PATH_USER%": user_home,
"%PATH_VAR%": "/var",
"%PATH_TMP_1%": "/tmp",
"%PATH_TMP_2%": tempfile.gettempdir(),
}
return paths
def build_full_path(path_parts: list, env_paths: dict) -> str:
replaced = []
for part in path_parts:
for key, val in env_paths.items():
if val:
part = part.replace(key, val)
replaced.append(part)
return os.path.join(*replaced)
# ─── Firefox Profile Discovery ──────────────────────────────────────
def get_firefox_file_paths(env_paths: dict) -> list:
os_name = detect_os()
results = []
target_files = [
"places.sqlite", "formhistory.sqlite", "permissions.sqlite",
"content-prefs.sqlite", "cookies.sqlite", "cookies.sqlite-wal",
"cache", "cache1", "cache2", "cache3", "storage",
]
profile_roots = []
if os_name == "Windows":
for base_key in ["%PATH_APPDATA_LOCAL%", "%PATH_APPDATA_ROAMING%"]:
base = env_paths.get(base_key, "")
if base:
profile_roots.append(os.path.join(base, "Mozilla", "Firefox", "Profiles"))
elif os_name == "Linux":
user = env_paths.get("%PATH_USER%", "")
if user:
profile_roots.append(os.path.join(user, ".mozilla", "firefox"))
for root in profile_roots:
if not os.path.exists(root):
continue
try:
for profile in os.listdir(root):
if ".default" in profile:
profile_path = os.path.join(root, profile)
for fname in target_files:
fpath = os.path.join(profile_path, fname)
if os.path.exists(fpath) and fpath not in results:
results.append(fpath)
except PermissionError:
pass
return results
# ─── Chromium Profile Discovery ─────────────────────────────────────
def get_chromium_profiles(browser_name: str, env_paths: dict) -> list:
"""Discover all Chromium-based browser profiles (Default, Profile 1, etc.)."""
os_name = detect_os()
results = []
# Map browser name to its User Data path
browser_paths = {
"Windows": {
"Google Chrome": ["%PATH_APPDATA_LOCAL%", "Google", "Chrome", "User Data"],
"Microsoft Edge": ["%PATH_APPDATA_LOCAL%", "Microsoft", "Edge", "User Data"],
"Brave Browser": ["%PATH_APPDATA_LOCAL%", "BraveSoftware", "Brave-Browser", "User Data"],
"Opera Browser": ["%PATH_APPDATA_ROAMING%", "Opera Software", "Opera Stable"],
},
"Linux": {
"Google Chrome": ["%PATH_USER%", ".config", "google-chrome"],
"Brave Browser": ["%PATH_USER%", ".config", "BraveSoftware", "Brave-Browser"],
"Opera Browser": ["%PATH_USER%", ".config", "opera"],
},
}
paths_map = browser_paths.get(os_name, {})
path_parts = paths_map.get(browser_name)
if not path_parts:
return results
try:
user_data = build_full_path(path_parts, env_paths)
except Exception:
return results
if not os.path.exists(user_data):
return results
# Find all profile directories
try:
for entry in os.listdir(user_data):
full = os.path.join(user_data, entry)
if os.path.isdir(full) and (entry == "Default" or entry.startswith("Profile ")):
results.append(full)
except PermissionError:
pass
return results
# ─── Tor Path Resolution ───────────────────────────────────────────
def resolve_tor_path(tool_folder: str) -> Optional[str]:
tor_file = os.path.join(tool_folder, "Paths", "PathTor.txt")
# Auto-discover common Windows Tor paths if file doesn't exist or is empty
if not os.path.exists(tor_file) or os.path.getsize(tor_file) == 0:
common_paths = [
os.path.join(os.environ.get("USERPROFILE", ""), "Desktop", "Tor Browser"),
os.path.join(os.environ.get("USERPROFILE", ""), "Downloads", "Tor Browser"),
"C:\\Tor Browser",
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Tor Browser")
]
found_path = ""
for p in common_paths:
if os.path.isdir(p):
found_path = p
break
# Create the file autonomously
try:
os.makedirs(os.path.dirname(tor_file), exist_ok=True)
with open(tor_file, "w", encoding="utf-8") as f:
if found_path:
f.write(found_path)
else:
f.write("# Put your Tor Browser path here (e.g. C:\\Users\\Name\\Desktop\\Tor Browser)\n")
except Exception:
pass
if not found_path:
return None
path = found_path
else:
try:
with open(tor_file, "r", encoding="utf-8") as f:
path = f.read().strip()
# Ignore placeholder comments
if not path or path.startswith("#"):
return None
except Exception:
return None
if os.path.exists(path):
if os.path.basename(path) == "Tor Browser":
return os.path.join(path, "Browser")
return path
return None
# ─── Core Cleaning Engine ───────────────────────────────────────────
class CleaningEngine:
def __init__(self, stats: CleanStats, dry_run: bool = False,
silent: bool = False, wipe_passes: int = 1):
self.stats = stats
self.dry_run = dry_run
self.silent = silent
self.wipe_passes = max(1, wipe_passes)
def overwrite_file(self, file_path: str) -> bool:
"""Overwrite file contents. Supports multi-pass DoD 5220.22-M wipe."""
try:
fp = pathlib.Path(file_path)
size = fp.stat().st_size
if size == 0:
return True
if self.dry_run:
self.stats.add_overwrite()
return True
with open(fp, "r+b") as f:
for pass_num in range(self.wipe_passes):
f.seek(0)
if self.wipe_passes == 1:
# Single pass: null bytes
f.write(b"\x00" * size)
elif pass_num == 0:
# Pass 1: all zeros
f.write(b"\x00" * size)
elif pass_num == 1:
# Pass 2: all ones
f.write(b"\xFF" * size)
elif pass_num == 2:
# Pass 3: random data
f.write(random.randbytes(size))
else:
# Extra passes: random
f.write(random.randbytes(size))
f.flush()
os.fsync(f.fileno())
f.truncate(size)
self.stats.add_overwrite()
return True
except FileNotFoundError:
return False
except PermissionError:
self.stats.add_error(f"Permission denied: {file_path}")
return False
except Exception as e:
self.stats.add_error(f"{file_path}: {e}")
return False
def delete_file(self, category: str, file_path: str) -> bool:
"""Securely delete a file (overwrite + remove)."""
if not os.path.exists(file_path) or not os.path.isfile(file_path):
return False
try:
file_size = os.path.getsize(file_path)
self.overwrite_file(file_path)
if not self.dry_run:
os.remove(file_path)
self.stats.add_file(file_size)
self.stats.log("DELETE FILE", category, file_path)
return True
except FileNotFoundError:
return False
except PermissionError:
self.stats.add_error(f"Permission denied: {file_path}")
self.stats.log("DELETE FILE", category, file_path, "DENIED")
return False
except Exception as e:
self.stats.add_error(f"{file_path}: {e}")
self.stats.log("DELETE FILE", category, file_path, "ERROR")
return False
def delete_folder(self, category: str, folder_path: str) -> bool:
"""Recursively delete a folder after overwriting all files."""
if not os.path.exists(folder_path) or not os.path.isdir(folder_path):
return False
if self.dry_run:
self.stats.add_folder()
self.stats.log("DELETE DIR", category, folder_path, "DRY")
return True
try:
for root, dirs, files in os.walk(folder_path, topdown=False):
for name in files:
self.delete_file(category, os.path.join(root, name))
for name in dirs:
dir_path = os.path.join(root, name)
try:
shutil.rmtree(dir_path, ignore_errors=True)
self.stats.add_folder()
except Exception as e:
self.stats.add_error(f"{dir_path}: {e}")
try:
shutil.rmtree(folder_path, ignore_errors=True)
self.stats.add_folder()
self.stats.log("DELETE DIR", category, folder_path)
except Exception as e:
self.stats.add_error(f"{folder_path}: {e}")
return True
except PermissionError:
self.stats.add_error(f"Permission denied: {folder_path}")
return False
except Exception as e:
self.stats.add_error(f"{folder_path}: {e}")
return False
def delete_all_from_folder(self, category: str, folder_path: str) -> bool:
"""Delete all contents inside a folder (but keep the folder)."""
if not os.path.exists(folder_path):
return False
if self.dry_run:
self.stats.add_folder()
self.stats.log("CLEAN DIR", category, folder_path, "DRY")
return True
try:
for entry in os.listdir(folder_path):
full_path = os.path.join(folder_path, entry)
if os.path.isfile(full_path) or os.path.islink(full_path):
self.delete_file(category, full_path)
elif os.path.isdir(full_path):
self.delete_folder(category, full_path)
return True
except PermissionError:
self.stats.add_error(f"Permission denied: {folder_path}")
return False
except Exception as e:
self.stats.add_error(f"{folder_path}: {e}")
return False
def delete_registry_key(self, category: str, registry_key: str) -> bool:
"""Delete a Windows registry key and all its subkeys."""
if detect_os() != "Windows":
return False
import winreg
root_keys = {
"HKEY_CURRENT_USER": winreg.HKEY_CURRENT_USER,
"HKCU": winreg.HKEY_CURRENT_USER,
"HKEY_LOCAL_MACHINE": winreg.HKEY_LOCAL_MACHINE,
"HKLM": winreg.HKEY_LOCAL_MACHINE,
"HKEY_CLASSES_ROOT": winreg.HKEY_CLASSES_ROOT,
"HKCR": winreg.HKEY_CLASSES_ROOT,
"HKEY_USERS": winreg.HKEY_USERS,
"HKU": winreg.HKEY_USERS,
"HKEY_CURRENT_CONFIG": winreg.HKEY_CURRENT_CONFIG,
"HKCC": winreg.HKEY_CURRENT_CONFIG,
}
if "<SID>" in registry_key or "<" in registry_key:
self.stats.add_skip()
return False
try:
key_name, subkey_path = registry_key.split("\\", 1)
hkey = root_keys.get(key_name.upper())
if hkey is None:
return False
except ValueError:
return False
return self._delete_subkeys(category, hkey, subkey_path, registry_key)
def _delete_subkeys(self, category, key, subkey_path, registry_key):
if detect_os() != "Windows":
return False
import winreg
if self.dry_run:
try:
with winreg.OpenKey(key, subkey_path, 0, winreg.KEY_READ) as k:
pass
self.stats.add_registry()
self.stats.log("DELETE KEY", category, registry_key, "DRY")
return True
except FileNotFoundError:
return False
except PermissionError:
self.stats.add_error(f"Permission denied: {registry_key}")
return False
except Exception:
return False
try:
with winreg.OpenKey(key, subkey_path, 0, winreg.KEY_READ | winreg.KEY_WRITE) as k:
while True:
try:
subkey_name = winreg.EnumKey(k, 0)
self._delete_subkeys(category, k, subkey_name, f"{registry_key}\\{subkey_name}")
except OSError:
break
winreg.DeleteKey(key, subkey_path)
self.stats.add_registry()
self.stats.log("DELETE KEY", category, registry_key)
return True
except FileNotFoundError:
return False
except PermissionError:
self.stats.add_error(f"Permission denied: {registry_key}")
return False
except Exception as e:
self.stats.add_error(f"{registry_key}: {e}")
return False
def delete_disk_trash(self) -> bool:
"""Empty recycle bin / trash on all drives."""
os_name = detect_os()
trash_folders = ["$Recycle.Bin", ".Trash-1000", ".Trash"]
if os_name == "Windows":
for letter in string.ascii_uppercase:
drive = f"{letter}:\\"
if os.path.exists(drive):
for name in trash_folders:
folder_path = os.path.join(drive, name)
if os.path.exists(folder_path):
self.delete_folder("Trash", folder_path)
if not self.dry_run:
try:
ctypes.windll.shell32.SHEmptyRecycleBinW(None, None, 0x00000001 | 0x00000004)
except Exception:
pass
elif os_name == "Linux":
try:
media_path = f"/run/media/{os.getlogin()}"
if os.path.exists(media_path):
for entry in os.listdir(media_path):
full = os.path.join(media_path, entry)
if os.path.isdir(full):
for folder in trash_folders:
fp = os.path.join(full, folder)
if os.path.exists(fp):
self.delete_folder("Trash", fp)
except Exception:
pass
self.stats.log("EMPTY TRASH", "Trash", "all drives")
return True
def flush_dns(self) -> bool:
"""Flush the DNS resolver cache."""
os_name = detect_os()
if self.dry_run:
self.stats.dns_flushed = True
self.stats.log("FLUSH DNS", "DNS", "resolver cache", "DRY")
return True
try:
if os_name == "Windows":
subprocess.run(
["ipconfig", "/flushdns"],
capture_output=True, timeout=10
)
elif os_name == "Linux":
# Try systemd-resolve first, then resolvectl
try:
subprocess.run(
["resolvectl", "flush-caches"],
capture_output=True, timeout=10
)
except FileNotFoundError:
subprocess.run(
["systemd-resolve", "--flush-caches"],
capture_output=True, timeout=10
)
self.stats.dns_flushed = True
self.stats.log("FLUSH DNS", "DNS", "resolver cache")
return True
except Exception as e:
self.stats.add_error(f"DNS flush failed: {e}")
return False
def flush_arp(self) -> bool:
"""Flush the ARP cache (Windows only)."""
if detect_os() != "Windows":
return False
if self.dry_run:
self.stats.log("FLUSH ARP", "Network", "ARP cache", "DRY")
return True
try:
subprocess.run(
["netsh", "interface", "ip", "delete", "arpcache"],
capture_output=True, timeout=10
)
self.stats.log("FLUSH ARP", "Network", "ARP cache")
return True
except Exception as e:
self.stats.add_error(f"ARP flush failed: {e}")
return False
# ─── Category Discovery ─────────────────────────────────────────────
def discover_categories(tool_folder: str) -> dict:
"""Load all JSON configs and merge categories."""
os_name = detect_os()
paths_dir = os.path.join(tool_folder, "Paths")
categories = {}
if os_name == "Windows":
configs = [
("WindowsFilePaths.json", "files"),
("WindowsFolderPaths.json", "folders"),
("WindowsRegistryKeys.json", "registry"),
]
elif os_name == "Linux":
configs = [
("LinuxFilePaths.json", "files"),
("LinuxFolderPaths.json", "folders"),
]
else:
return {}
for filename, kind in configs:
filepath = os.path.join(paths_dir, filename)
if not os.path.exists(filepath):
continue
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
for cat_name, items in data.items():
if cat_name not in categories:
categories[cat_name] = {"files": [], "folders": [], "registry": []}
categories[cat_name][kind] = items
except Exception:
pass
# Built-in categories (always present)
for name in ("Firefox", "Trash", "DNS Cache"):
if name not in categories:
categories[name] = {"files": [], "folders": [], "registry": []}
return categories
# ─── UI Components ──────────────────────────────────────────────────
def render_banner():
"""Render the modern banner."""
lines = [
"",
"[bold bright_magenta]+=============================================+[/bold bright_magenta]",
"[bold bright_magenta]|[/bold bright_magenta] [bold white] << N U L L T R A C E v2.5 >> [/bold white] [bold bright_magenta]|[/bold bright_magenta]",
"[bold bright_magenta]|[/bold bright_magenta] [dim] Modern System Trace Removal Tool [/dim] [bold bright_magenta]|[/bold bright_magenta]",
"[bold bright_magenta]+=============================================+[/bold bright_magenta]",
f"[bright_cyan] {GITHUB}[/bright_cyan]",
"",
]
for line in lines:
console.print(line, justify="center")
def render_category_table(categories: dict, selected: set) -> Table:
"""Build the interactive category selection table."""
table = Table(
title="[bold]Available Categories[/bold]",
box=box.ROUNDED,
border_style="bright_magenta",
title_style="bold bright_cyan",
header_style="bold bright_magenta",
show_lines=True,
padding=(0, 1),
)
table.add_column("#", justify="center", style="bold bright_cyan", width=4)
table.add_column("Category", style="bold white", min_width=20)
table.add_column("Files", justify="center", style="dim", width=8)
table.add_column("Folders", justify="center", style="dim", width=8)
table.add_column("Registry", justify="center", style="dim", width=10)
table.add_column("Status", justify="center", width=10)
for i, (name, data) in enumerate(sorted(categories.items()), 1):
n_files = len(data.get("files", []))
n_folders = len(data.get("folders", []))
n_registry = len(data.get("registry", []))
# DNS Cache / Trash are special — show as built-in
if name in ("DNS Cache", "Trash", "Firefox"):
if n_files == 0 and n_folders == 0 and n_registry == 0:
n_files_str = "-"
n_folders_str = "built-in"
n_registry_str = "-"
else:
n_files_str = str(n_files) if n_files else "-"
n_folders_str = str(n_folders) if n_folders else "-"
n_registry_str = str(n_registry) if n_registry else "-"
else:
n_files_str = str(n_files) if n_files else "-"
n_folders_str = str(n_folders) if n_folders else "-"
n_registry_str = str(n_registry) if n_registry else "-"
if name in selected:
status = Text("[ON]", style="bold bright_green")
else:
status = Text("[OFF]", style="dim")
table.add_row(str(i), name, n_files_str, n_folders_str, n_registry_str, status)
return table
def render_summary(stats: CleanStats, elapsed: float, dry_run: bool, wipe_passes: int):
"""Render the final summary dashboard."""
console.print()
label = "DRY RUN Summary" if dry_run else "Cleaning Summary"
console.print(Rule(f"[bold bright_magenta]{label}[/bold bright_magenta]"))
console.print()
grid = Table(box=box.SIMPLE_HEAVY, show_header=False, border_style="bright_magenta", padding=(0, 2))
grid.add_column(justify="center", min_width=22)
grid.add_column(justify="center", min_width=22)
grid.add_column(justify="center", min_width=22)
grid.add_row(
f"[bold bright_green]Files Deleted[/bold bright_green]\n[bold white]{stats.files_deleted:,}[/bold white]",
f"[bold bright_cyan]Folders Deleted[/bold bright_cyan]\n[bold white]{stats.folders_deleted:,}[/bold white]",
f"[bold bright_magenta]Registry Keys[/bold bright_magenta]\n[bold white]{stats.registry_keys_deleted:,}[/bold white]",
)
console.print(grid, justify="center")
console.print()
grid2 = Table(box=box.SIMPLE_HEAVY, show_header=False, border_style="bright_magenta", padding=(0, 2))
grid2.add_column(justify="center", min_width=22)
grid2.add_column(justify="center", min_width=22)
grid2.add_column(justify="center", min_width=22)
dns_label = "Yes" if stats.dns_flushed else "No"
wipe_label = f"{wipe_passes}x" if wipe_passes > 1 else "1x"
grid2.add_row(
f"[bold bright_green]Space Freed[/bold bright_green]\n[bold white]{stats.format_bytes(stats.bytes_freed)}[/bold white]",
f"[bold bright_yellow]Errors / Wipe[/bold bright_yellow]\n[bold white]{stats.errors:,} / {wipe_label}[/bold white]",
f"[dim]Duration / DNS[/dim]\n[bold white]{elapsed:.1f}s / {dns_label}[/bold white]",
)
console.print(grid2, justify="center")
if stats.errors > 0 and stats.error_details:
console.print()
console.print(Rule("[bold bright_yellow]Error Details (max 10)[/bold bright_yellow]"))
for detail in stats.error_details[:10]:
console.print(f" [bright_red]x[/bright_red] [dim]{detail}[/dim]")
console.print()
mode_label = "[DRY RUN] " if dry_run else ""
console.print(
f"[bold bright_green]>> {mode_label}Cleaning complete -- {stats.total_actions:,} actions performed[/bold bright_green]",
justify="center",
)
console.print()
# ─── Log File Writer ────────────────────────────────────────────────
def save_log(stats: CleanStats, tool_folder: str, elapsed: float, dry_run: bool):
"""Save a detailed log file of the cleaning session."""
try:
log_dir = os.path.join(tool_folder, "Logs")
os.makedirs(log_dir, exist_ok=True)
ts = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_file = os.path.join(log_dir, f"nulltrace_{ts}.log")
with open(log_file, "w", encoding="utf-8") as f:
f.write(f"NullTrace v{VERSION} — Cleaning Log\n")
f.write(f"Date: {datetime.datetime.now().isoformat()}\n")
f.write(f"Mode: {'DRY RUN' if dry_run else 'LIVE'}\n")
f.write(f"Duration: {elapsed:.1f}s\n")
f.write(f"Files deleted: {stats.files_deleted}\n")
f.write(f"Folders deleted: {stats.folders_deleted}\n")
f.write(f"Registry keys deleted: {stats.registry_keys_deleted}\n")
f.write(f"Space freed: {stats.format_bytes(stats.bytes_freed)}\n")
f.write(f"DNS flushed: {stats.dns_flushed}\n")
f.write(f"Errors: {stats.errors}\n")
f.write(f"\n{'='*60}\n\n")
for line in stats.log_lines:
f.write(line + "\n")
if stats.error_details:
f.write(f"\n{'='*60}\nERRORS:\n")
for err in stats.error_details:
f.write(f" {err}\n")
console.print(f" [dim]Log saved: {log_file}[/dim]")
except Exception:
pass
# ─── Main Cleaning Orchestrator ─────────────────────────────────────
def run_cleaning(
engine: CleaningEngine,
categories: dict,
selected: set,
env_paths: dict,
tool_folder: str,
):
"""Execute the cleaning across all selected categories with a progress bar."""
os_name = detect_os()
# Count total tasks
total = 0
for name in selected:
data = categories.get(name, {})
total += len(data.get("files", []))
total += len(data.get("folders", []))
total += len(data.get("registry", []))
if "Firefox" in selected:
total += 1
if "Trash" in selected:
total += 1
if "DNS Cache" in selected:
total += 1
with Progress(
SpinnerColumn("dots", style="bold bright_magenta"),
TextColumn("[bold]{task.description}[/bold]", style="white"),
BarColumn(bar_width=40, style="dim", complete_style="bright_magenta", finished_style="bright_green"),
MofNCompleteColumn(),
TimeElapsedColumn(),
console=console,
transient=False,
) as progress:
task = progress.add_task("Cleaning system traces...", total=max(total, 1))
# 1. Trash
if "Trash" in selected:
progress.update(task, description="[Trash] Emptying Recycle Bin...")
engine.delete_disk_trash()
progress.advance(task)
# 2. DNS Cache
if "DNS Cache" in selected:
progress.update(task, description="[DNS] Flushing DNS cache...")
engine.flush_dns()
engine.flush_arp()
progress.advance(task)
# 3. Firefox
if "Firefox" in selected:
progress.update(task, description="[Firefox] Cleaning profiles...")
for fp in get_firefox_file_paths(env_paths):
if os.path.isfile(fp):
engine.delete_file("Firefox", fp)
elif os.path.isdir(fp):
engine.delete_folder("Firefox", fp)
progress.advance(task)
# 4. Category-based cleaning
for cat_name in sorted(selected):
if cat_name in ("Trash", "Firefox", "DNS Cache"):
continue
data = categories.get(cat_name, {})
# Files
for path_parts in data.get("files", []):
progress.update(task, description=f"[{cat_name}] Deleting files...")
try:
full_path = build_full_path(path_parts, env_paths)
engine.delete_file(cat_name, full_path)
except Exception:
engine.stats.add_error(f"Path build failed: {path_parts}")
progress.advance(task)
# Folders
for path_parts in data.get("folders", []):
progress.update(task, description=f"[{cat_name}] Cleaning folders...")
try:
full_path = build_full_path(path_parts, env_paths)
engine.delete_all_from_folder(cat_name, full_path)
except Exception:
engine.stats.add_error(f"Path build failed: {path_parts}")
progress.advance(task)
# Registry (Windows only)
if os_name == "Windows":
for reg_key in data.get("registry", []):
progress.update(task, description=f"[{cat_name}] Cleaning registry...")
engine.delete_registry_key(cat_name, reg_key)
progress.advance(task)
# ─── Interactive Category Selector ──────────────────────────────────
def interactive_select(categories: dict) -> set:
"""Let the user toggle categories on/off interactively."""
sorted_cats = sorted(categories.keys())
selected = set(sorted_cats) # All on by default
while True:
console.clear()
render_banner()
if is_admin():
console.print("[bold bright_green] [+] Running as Administrator[/bold bright_green]")
else:
console.print("[bold bright_yellow] [!] Not running as Administrator -- some operations may fail[/bold bright_yellow]")
console.print()
console.print(render_category_table(categories, selected))
console.print()
console.print(
"[dim]Commands:[/dim] "
"[white]<number>[/white] toggle | "
"[white]all[/white] select all | "
"[white]none[/white] deselect all | "
"[white]start[/white] begin | "
"[white]quit[/white] exit",
justify="center",
)
console.print()
choice = Prompt.ask("[bold bright_magenta]>[/bold bright_magenta]", default="start")
choice = choice.strip().lower()
if choice in ("start", "s", "go", "run"):
if not selected:
console.print("[bright_yellow] [!] No categories selected![/bright_yellow]")
time.sleep(1)
continue
return selected
elif choice in ("quit", "q", "exit"):
console.print("[dim]Goodbye![/dim]")
sys.exit(0)
elif choice in ("all", "a"):
selected = set(sorted_cats)
elif choice in ("none", "n"):
selected = set()
elif choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(sorted_cats):
name = sorted_cats[idx]
if name in selected:
selected.discard(name)
else:
selected.add(name)
# ─── CLI Argument Parser ────────────────────────────────────────────
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="nulltrace",
description=f"NullTrace v{VERSION} -- Modern System Trace Removal Tool",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=f"""
Examples:
python nulltrace.py Interactive mode
python nulltrace.py --all Clean everything
python nulltrace.py --dry-run Preview what would be deleted
python nulltrace.py --category Firefox Clean only Firefox
python nulltrace.py --list List available categories
python nulltrace.py --all --wipe 3 DoD 5220.22-M 3-pass wipe
python nulltrace.py --all --log Save detailed log file
By {AUTHOR} | {GITHUB}
""",
)
parser.add_argument("--all", "-a", action="store_true",
help="Clean all categories without prompts")
parser.add_argument("--dry-run", "-d", action="store_true",