Repository navigation
Expand file tree
/
Copy pathconditional_startup.py
More file actions
1878 lines (1688 loc) · 96.9 KB
/
Copy pathconditional_startup.py
File metadata and controls
1878 lines (1688 loc) · 96.9 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
import importlib.util
import os
import sys
import io
import json
import getpass
import logging
import threading
import subprocess
import tempfile
# --- Windows subprocess window suppression ---
if sys.platform == 'win32':
CREATE_NO_WINDOW = 0x08000000
else:
CREATE_NO_WINDOW = 0
import requests
import time
import webbrowser
from concurrent.futures import ThreadPoolExecutor
import warnings
# Ensure the base directory is in sys.path for package imports
basedir = os.path.dirname(os.path.abspath(__file__))
if basedir not in sys.path:
sys.path.insert(0, basedir)
# Dynamically import a module from a given path
def import_module_from_path(module_name, path):
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# Locks for concurrent process + file scanning
results_lock = threading.RLock()
scanner_lock = threading.RLock()
# Cooperative stop signal used by the dashboard "Break the cycle" button.
STOP_EVENT = threading.Event()
def _resolve_critical_directories():
"""Resolve critical system directories, auto-detecting the Windows drive
when SYSTEMROOT/USERPROFILE/PROGRAMDATA environment variables are missing."""
import string
system_root = os.environ.get('SYSTEMROOT')
if not system_root or not os.path.isdir(system_root):
for d in string.ascii_uppercase:
candidate = f"{d}:\\Windows"
if os.path.isdir(candidate):
system_root = candidate
break
else:
system_root = 'C:\\Windows'
user_profile = os.environ.get('USERPROFILE')
if not user_profile or not os.path.isdir(user_profile):
username = getpass.getuser()
for d in string.ascii_uppercase:
candidate = os.path.join(f"{d}:\\", 'Users', username)
if os.path.isdir(candidate):
user_profile = candidate
break
else:
user_profile = 'C:\\Users\\Default'
program_data = os.environ.get('PROGRAMDATA')
if not program_data or not os.path.isdir(program_data):
drive, _ = os.path.splitdrive(system_root)
candidate = os.path.join(drive + '\\', 'ProgramData')
if os.path.isdir(candidate):
program_data = candidate
else:
program_data = 'C:\\ProgramData'
dirs = [
os.path.join(system_root, 'Temp'),
os.path.join(user_profile, 'Downloads'),
os.path.join(user_profile, 'AppData\\Local\\Temp'),
os.path.join(user_profile, 'Desktop'),
os.path.join(program_data, 'Microsoft\\Windows\\Start Menu\\Programs\\Startup')
]
return [d for d in dirs if os.path.isdir(d)]
def load_module(module_name, path, output):
"""Helper to dynamically load a module from the given path."""
try:
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
output.write(f"[conditional_startup] Successfully loaded {module_name}.\n")
return module
except Exception as e:
output.write(f"[ERROR] Failed to load {module_name}: {e}\n")
return None
# Get the absolute path to a resource, handling both normal and frozen environments (e.g., PyInstaller)
def get_resource_path(relative_path):
"""
Returns the absolute path to a resource, handling both normal and frozen environments (e.g., PyInstaller).
"""
if getattr(sys, 'frozen', False):
# PyInstaller onedir: resources live next to the executable.
base_path = os.path.dirname(sys.executable)
else:
# If running as a script
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
def routine_maintenance_and_system_recovery():
"""Perform comprehensive routine maintenance and system recovery using multiple scanning methods."""
output = io.StringIO()
output.write("[ROUTINE MAINTENANCE] Starting comprehensive system recovery and maintenance...\n")
basedir = os.path.dirname(os.path.abspath(__file__))
recovery_results = {
"yara_scans": [],
"ml_scans": [],
"heuristic_scans": [],
"signature_scans": [],
"behavioral_scans": [],
"registry_scans": [],
"memory_scans": [],
"network_scans": [],
"rootkit_scans": [],
"integrity_checks": [],
"game_malware_scans": [],
"ransomware_scans": [],
"spyware_scans": [],
"trojan_scans": [],
"worm_scans": [],
"adware_scans": [],
"crypto_miner_scans": [],
"entropy_scans": [],
"import_scans": [],
"hash_scans": [],
"cleaned_files": [],
"recovered_systems": [],
"errors": []
}
try:
# 1. YARA-based scanning
output.write("[ROUTINE MAINTENANCE] Performing YARA-based scanning...\n")
try:
yara_scanner_path = os.path.join(basedir, 'security', 'yara_scanner.py')
yara_scanner = import_module_from_path('yara_scanner', yara_scanner_path)
from scan_pipeline import scan_file_yara
# Scan critical system directories (or use provided override)
critical_dirs = critical_dirs if critical_dirs else _resolve_critical_directories()
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
time.sleep(0) # yield so the Flask server stays responsive
try:
yara_result = scan_file_yara(filepath, yara_scanner.scan_file_with_yara)[0]
if yara_result:
recovery_results["yara_scans"].append({
"file": filepath,
"threat": yara_result,
"action": "detected"
})
output.write(f"[YARA] Threat detected in {filepath}: {yara_result}\n")
except Exception as e:
output.write(f"[YARA ERROR] Error scanning {filepath}: {e}\n")
except Exception as e:
output.write(f"[ERROR] YARA scanning failed: {e}\n")
recovery_results["errors"].append(f"YARA scanning: {str(e)}")
# 2. Machine Learning-based scanning
output.write("[ROUTINE MAINTENANCE] Performing ML-based anomaly detection...\n")
try:
from security.detector import detector, ember_detector, bodmas_cnn_detector
# Both classifiers were trained on PE-executable samples; running
# them against arbitrary files (photos, videos, documents) floods
# results with false positives, since compressed non-executable
# formats share the "high entropy + no imports/sections" signature
# the models associate with packed malware.
ml_extensions = {'.exe', '.dll', '.sys', '.scr', '.ocx', '.cpl', '.com', '.drv'}
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
if os.path.splitext(file)[1].lower() not in ml_extensions:
continue
filepath = os.path.join(root, file)
time.sleep(0) # yield so the Flask server stays responsive
try:
# Prefer the EMBER-trained classifier (real malware/
# benign data) when available; otherwise fall back to
# the synthetic-data classifier. is_malicious() on the
# fallback handles both the trained classifier (0/1
# labels) and the untrained IsolationForest fallback
# (+1/-1 outlier labels) correctly.
if bodmas_cnn_detector.available:
score = bodmas_cnn_detector.score(filepath)
if score is not None and score >= 0.60:
recovery_results["ml_scans"].append({
"file": filepath,
"prediction": "malicious",
"anomaly_score": score,
"model": "bodmas_cnn",
"action": "detected"
})
output.write(f"[ML/BODMAS-CNN] Malicious file detected: {filepath} (score: {score:.3f})\n")
elif ember_detector.available:
score = ember_detector.score(filepath)
if score is not None and score >= 0.60:
recovery_results["ml_scans"].append({
"file": filepath,
"prediction": "malicious",
"anomaly_score": score,
"model": "ember",
"action": "detected"
})
output.write(f"[ML/EMBER] Malicious file detected: {filepath} (score: {score:.3f})\n")
elif detector.is_malicious(filepath):
anomaly_score = detector.get_anomaly_score(filepath)
recovery_results["ml_scans"].append({
"file": filepath,
"prediction": "malicious",
"anomaly_score": float(anomaly_score),
"model": "synthetic",
"action": "detected"
})
output.write(f"[ML] Malicious file detected: {filepath} (anomaly score: {anomaly_score})\n")
except Exception as e:
output.write(f"[ML ERROR] Error analyzing {filepath}: {e}\n")
except Exception as e:
output.write(f"[ERROR] ML scanning failed: {e}\n")
recovery_results["errors"].append(f"ML scanning: {str(e)}")
# 3. Heuristic-based scanning
output.write("[ROUTINE MAINTENANCE] Performing heuristic analysis...\n")
try:
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
time.sleep(0) # yield so the Flask server stays responsive
try:
# Heuristic checks
file_size = os.path.getsize(filepath)
file_ext = os.path.splitext(filepath)[1].lower()
mod_time = os.path.getmtime(filepath)
# Suspicious characteristics
is_suspicious = False
reasons = []
if file_ext in ['.exe', '.dll', '.sys', '.bat', '.cmd', '.scr', '.vbs']:
is_suspicious = True
reasons.append("suspicious_extension")
if file_size < 1024 or file_size > 100 * 1024 * 1024: # Very small or very large
is_suspicious = True
reasons.append("unusual_size")
if time.time() - mod_time < 3600: # Modified in last hour
is_suspicious = True
reasons.append("recently_modified")
if is_suspicious:
recovery_results["heuristic_scans"].append({
"file": filepath,
"reasons": reasons,
"action": "flagged"
})
output.write(f"[HEURISTIC] Suspicious file flagged: {filepath} - {reasons}\n")
except Exception as e:
output.write(f"[HEURISTIC ERROR] Error analyzing {filepath}: {e}\n")
except Exception as e:
output.write(f"[ERROR] Heuristic scanning failed: {e}\n")
recovery_results["errors"].append(f"Heuristic scanning: {str(e)}")
# 4. Signature-based scanning
output.write("[ROUTINE MAINTENANCE] Performing signature-based scanning...\n")
try:
scan_utils_path = os.path.join(basedir, 'scan_utils.py')
scan_utils = import_module_from_path('scan_utils', scan_utils_path)
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
time.sleep(0) # yield so the Flask server stays responsive
try:
scan_success, malware_found, msg = scan_utils.scan_file_for_viruses(filepath, stop_event=STOP_EVENT)
if malware_found:
recovery_results["signature_scans"].append({
"file": filepath,
"message": msg,
"action": "detected"
})
output.write(f"[SIGNATURE] Malware signature detected: {filepath}\n")
except Exception as e:
output.write(f"[SIGNATURE ERROR] Error scanning {filepath}: {e}\n")
except Exception as e:
output.write(f"[ERROR] Signature scanning failed: {e}\n")
recovery_results["errors"].append(f"Signature scanning: {str(e)}")
# 5. Behavioral analysis scanning
output.write("[ROUTINE MAINTENANCE] Performing behavioral analysis...\n")
try:
process_monitor_path = os.path.join(basedir, 'security', 'process_monitor.py')
process_monitor = import_module_from_path('process_monitor', process_monitor_path)
# Monitor for suspicious process behavior
suspicious_processes = process_monitor.scan_suspicious_processes()
for proc in suspicious_processes:
recovery_results["behavioral_scans"].append({
"process": proc.get('name', 'unknown'),
"pid": proc.get('pid', 0),
"behavior": proc.get('behavior', 'unknown'),
"action": "flagged"
})
output.write(f"[BEHAVIORAL] Suspicious process detected: {proc}\n")
except Exception as e:
output.write(f"[ERROR] Behavioral analysis failed: {e}\n")
recovery_results["errors"].append(f"Behavioral analysis: {str(e)}")
# 6. Registry scanning
output.write("[ROUTINE MAINTENANCE] Performing registry scanning...\n")
try:
import winreg
# Check common persistence locations
registry_keys = [
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"),
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"),
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"),
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"),
]
for hkey, key_path in registry_keys:
try:
with winreg.OpenKey(hkey, key_path) as key:
i = 0
while True:
try:
name, value, type = winreg.EnumValue(key, i)
# Check for suspicious values
if isinstance(value, str) and any(suspicious in value.lower() for suspicious in ['temp', 'appdata', 'downloads', 'hidden']):
recovery_results["registry_scans"].append({
"key": key_path,
"value_name": name,
"value": value,
"action": "flagged"
})
output.write(f"[REGISTRY] Suspicious registry entry: {name} = {value}\n")
i += 1
except WindowsError:
break
except Exception as e:
output.write(f"[REGISTRY ERROR] Error accessing {key_path}: {e}\n")
except Exception as e:
output.write(f"[ERROR] Registry scanning failed: {e}\n")
recovery_results["errors"].append(f"Registry scanning: {str(e)}")
# 7. Memory scanning
output.write("[ROUTINE MAINTENANCE] Performing memory scanning...\n")
try:
import psutil
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
# Check for suspicious memory patterns
mem_info = proc.info['memory_info']
if mem_info and mem_info.rss > 500 * 1024 * 1024: # > 500MB
recovery_results["memory_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"memory_usage": mem_info.rss,
"action": "flagged"
})
output.write(f"[MEMORY] High memory usage: {proc.info['name']} (PID: {proc.info['pid']})\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception as e:
output.write(f"[ERROR] Memory scanning failed: {e}\n")
recovery_results["errors"].append(f"Memory scanning: {str(e)}")
# 8. Network scanning
output.write("[ROUTINE MAINTENANCE] Performing network scanning...\n")
try:
import psutil
# Check for suspicious network connections
for conn in psutil.net_connections(kind='inet'):
if conn.raddr:
# Check for connections to suspicious ports
if conn.raddr.port in [666, 1337, 31337, 12345]: # Common backdoor ports
recovery_results["network_scans"].append({
"remote_ip": conn.raddr.ip,
"remote_port": conn.raddr.port,
"pid": conn.pid,
"action": "flagged"
})
output.write(f"[NETWORK] Suspicious connection: {conn.raddr.ip}:{conn.raddr.port} (PID: {conn.pid})\n")
except Exception as e:
output.write(f"[ERROR] Network scanning failed: {e}\n")
recovery_results["errors"].append(f"Network scanning: {str(e)}")
# 9. Rootkit detection
# NOTE: this used to run `attrib +h <System32>`, which does not check
# for hidden files -- it *sets* the hidden attribute on the directory
# itself (a destructive bug, not a detector). A hidden *executable*
# sitting directly in System32 (not a normal Windows pattern) is a
# weak but real static signal, checked here via os.stat's
# st_file_attributes directly rather than parsing `attrib` text
# output, whose hidden-flag column isn't at a fixed offset and is
# easy to misparse.
output.write("[ROUTINE MAINTENANCE] Performing rootkit detection...\n")
try:
import stat as stat_module
system32 = os.path.join(os.environ.get('SYSTEMROOT', 'C:\\Windows'), 'System32')
hidden_exes = []
if os.path.exists(system32):
for entry in os.listdir(system32):
if not entry.lower().endswith(('.exe', '.dll', '.sys')):
continue
full_path = os.path.join(system32, entry)
try:
attrs = os.stat(full_path).st_file_attributes
if attrs & stat_module.FILE_ATTRIBUTE_HIDDEN:
hidden_exes.append(full_path)
except OSError:
continue
if hidden_exes:
for path in hidden_exes[:50]:
recovery_results["rootkit_scans"].append({"file": path, "indicator": "hidden_executable"})
output.write(f"[ROOTKIT] {len(hidden_exes)} hidden executable(s) found directly in {system32}\n")
else:
output.write(f"[ROOTKIT] No hidden executables found directly in {system32}\n")
except Exception as e:
output.write(f"[ERROR] Rootkit detection failed: {e}\n")
recovery_results["errors"].append(f"Rootkit detection: {str(e)}")
# 10. System integrity checks
output.write("[ROUTINE MAINTENANCE] Performing system integrity checks...\n")
try:
# Check critical system files
critical_files = [
os.path.join(os.environ.get('SYSTEMROOT', 'C:\\Windows'), 'System32\\kernel32.dll'),
os.path.join(os.environ.get('SYSTEMROOT', 'C:\\Windows'), 'System32\\ntdll.dll'),
os.path.join(os.environ.get('SYSTEMROOT', 'C:\\Windows'), 'System32\\user32.dll'),
]
for critical_file in critical_files:
if os.path.exists(critical_file):
try:
# Check file size and modification time
file_size = os.path.getsize(critical_file)
mod_time = os.path.getmtime(critical_file)
recovery_results["integrity_checks"].append({
"file": critical_file,
"size": file_size,
"modified": mod_time,
"status": "checked"
})
output.write(f"[INTEGRITY] Checked {critical_file}\n")
except Exception as e:
output.write(f"[INTEGRITY ERROR] Error checking {critical_file}: {e}\n")
except Exception as e:
output.write(f"[ERROR] System integrity checks failed: {e}\n")
recovery_results["errors"].append(f"System integrity checks: {str(e)}")
# 11. Video game malware scanning
output.write("[ROUTINE MAINTENANCE] Performing video game malware scanning...\n")
try:
# Common game directories
game_dirs = [
os.path.join(os.environ.get('PROGRAMFILES', 'C:\\Program Files'), 'Steam'),
os.path.join(os.environ.get('PROGRAMFILES(X86)', 'C:\\Program Files (x86)'), 'Steam'),
os.path.join(os.environ.get('PROGRAMDATA', 'C:\\ProgramData'), 'EpicGamesLauncher'),
os.path.join(os.environ.get('PROGRAMFILES', 'C:\\Program Files'), 'Epic Games'),
os.path.join(os.environ.get('PROGRAMFILES(X86)', 'C:\\Program Files (x86)'), 'Origin Games'),
os.path.join(os.environ.get('PROGRAMFILES', 'C:\\Program Files'), 'Ubisoft'),
os.path.join(os.environ.get('USERPROFILE', ''), 'AppData\\LocalLow'), # Many games store data here
os.path.join(os.environ.get('USERPROFILE', ''), 'Documents'), # Game save files
]
# Game-specific file extensions and patterns
game_extensions = ['.exe', '.dll', '.pak', '.dat', '.sav', '.bak', '.tmp']
game_suspicious_names = ['cheat', 'hack', 'trainer', 'inject', 'bypass', 'crack', 'patch', 'mod', 'hook']
for game_dir in game_dirs:
if os.path.exists(game_dir):
for root, dirs, files in os.walk(game_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
file_ext = os.path.splitext(filepath)[1].lower()
file_lower = file.lower()
try:
# Check for suspicious game-related files
is_suspicious = False
reasons = []
# Check file extension
if file_ext in game_extensions:
is_suspicious = True
reasons.append("game_executable")
# Check for suspicious names
if any(suspicious in file_lower for suspicious in game_suspicious_names):
is_suspicious = True
reasons.append("suspicious_gaming_name")
# Check for recently modified files in game directories
mod_time = os.path.getmtime(filepath)
if time.time() - mod_time < 86400: # Modified in last 24 hours
is_suspicious = True
reasons.append("recently_modified_game_file")
# Check for unsigned executables in game directories
if file_ext == '.exe':
try:
# Try to get file signature info
import win32api
try:
win32api.GetFileVersionInfo(filepath, '\\')
except:
is_suspicious = True
reasons.append("unsigned_game_executable")
except:
pass
if is_suspicious:
# Perform YARA scan on suspicious game files
try:
yara_result = scan_file_yara(filepath, yara_scanner.scan_file_with_yara)[0]
if yara_result:
recovery_results["game_malware_scans"].append({
"file": filepath,
"threat": yara_result,
"reasons": reasons,
"action": "detected"
})
output.write(f"[GAME MALWARE] Threat detected in game file {filepath}: {yara_result}\n")
else:
recovery_results["game_malware_scans"].append({
"file": filepath,
"reasons": reasons,
"action": "flagged"
})
output.write(f"[GAME MALWARE] Suspicious game file flagged: {filepath} - {reasons}\n")
except Exception as yara_error:
recovery_results["game_malware_scans"].append({
"file": filepath,
"reasons": reasons,
"action": "flagged"
})
output.write(f"[GAME MALWARE] Suspicious game file flagged: {filepath} - {reasons}\n")
except Exception as e:
output.write(f"[GAME MALWARE ERROR] Error analyzing {filepath}: {e}\n")
except Exception as e:
output.write(f"[ERROR] Video game malware scanning failed: {e}\n")
recovery_results["errors"].append(f"Video game malware scanning: {str(e)}")
# 12. Ransomware scanning
output.write("[ROUTINE MAINTENANCE] Performing ransomware detection...\n")
try:
# Ransomware indicators
ransomware_extensions = ['.encrypted', '.locked', '.crypt', '.crypto', '.locky', '.zepto', '.cerber', '.dharma']
ransomware_processes = ['crypt', 'lock', 'encrypt', 'decrypt', 'ransom', 'bitcrypt', 'cryptolocker']
ransomware_patterns = ['HELP_DECRYPT', 'HELP_YOUR_FILES', 'RECOVER_FILES', 'DECRYPT_INSTRUCTIONS']
# Scan for ransomware file patterns
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
file_ext = os.path.splitext(filepath)[1].lower()
file_lower = file.lower()
try:
# Check for ransomware file extensions
if file_ext in ransomware_extensions:
recovery_results["ransomware_scans"].append({
"file": filepath,
"indicator": "ransomware_extension",
"action": "detected"
})
output.write(f"[RANSOMWARE] Ransomware file detected: {filepath}\n")
# Check for ransomware instruction files
if any(pattern in file_lower for pattern in ransomware_patterns):
recovery_results["ransomware_scans"].append({
"file": filepath,
"indicator": "ransomware_instruction",
"action": "detected"
})
output.write(f"[RANSOMWARE] Ransomware instruction file detected: {filepath}\n")
except Exception as e:
output.write(f"[RANSOMWARE ERROR] Error checking {filepath}: {e}\n")
# Check for ransomware processes
import psutil
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
proc_name = proc.info['name'].lower()
if any(ransom_proc in proc_name for ransom_proc in ransomware_processes):
recovery_results["ransomware_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"indicator": "ransomware_process",
"action": "detected"
})
output.write(f"[RANSOMWARE] Suspicious process detected: {proc.info['name']} (PID: {proc.info['pid']})\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception as e:
output.write(f"[ERROR] Ransomware scanning failed: {e}\n")
recovery_results["errors"].append(f"Ransomware scanning: {str(e)}")
# 13. Spyware scanning
output.write("[ROUTINE MAINTENANCE] Performing spyware detection...\n")
try:
# Spyware indicators
spyware_processes = ['keylogger', 'spy', 'monitor', 'track', 'steal', 'log', 'capture', 'screen', 'webcam']
spyware_files = ['keylog', 'spyware', 'monitor', 'tracker', 'stealer', 'logger', 'capture']
# Check for spyware processes
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
proc_name = proc.info['name'].lower()
if any(spy_proc in proc_name for spy_proc in spyware_processes):
recovery_results["spyware_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"indicator": "spyware_process",
"action": "detected"
})
output.write(f"[SPYWARE] Suspicious spyware process detected: {proc.info['name']} (PID: {proc.info['pid']})\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
# Check for spyware files
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
file_lower = file.lower()
try:
if any(spy_file in file_lower for spy_file in spyware_files):
recovery_results["spyware_scans"].append({
"file": filepath,
"indicator": "spyware_file",
"action": "detected"
})
output.write(f"[SPYWARE] Spyware-related file detected: {filepath}\n")
except Exception as e:
output.write(f"[SPYWARE ERROR] Error checking {filepath}: {e}\n")
except Exception as e:
output.write(f"[ERROR] Spyware scanning failed: {e}\n")
recovery_results["errors"].append(f"Spyware scanning: {str(e)}")
# 14. Trojan scanning
output.write("[ROUTINE MAINTENANCE] Performing trojan detection...\n")
try:
# Trojan indicators
trojan_extensions = ['.bat', '.cmd', '.vbs', '.js', '.jar', '.ps1']
trojan_processes = ['trojan', 'backdoor', 'remote', 'access', 'rat', 'reverse', 'shell', 'bind']
trojan_registry_keys = [
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",
]
# Check for trojan file extensions in suspicious locations
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
file_ext = os.path.splitext(filepath)[1].lower()
try:
if file_ext in trojan_extensions:
# Check if file is in startup location
if 'startup' in root.lower() or 'run' in root.lower():
recovery_results["trojan_scans"].append({
"file": filepath,
"indicator": "trojan_startup",
"action": "detected"
})
output.write(f"[TROJAN] Suspicious trojan file in startup: {filepath}\n")
except Exception as e:
output.write(f"[TROJAN ERROR] Error checking {filepath}: {e}\n")
# Check for trojan processes
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
proc_name = proc.info['name'].lower()
if any(trojan_proc in proc_name for trojan_proc in trojan_processes):
recovery_results["trojan_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"indicator": "trojan_process",
"action": "detected"
})
output.write(f"[TROJAN] Suspicious trojan process detected: {proc.info['name']} (PID: {proc.info['pid']})\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception as e:
output.write(f"[ERROR] Trojan scanning failed: {e}\n")
recovery_results["errors"].append(f"Trojan scanning: {str(e)}")
# 15. Worm scanning
output.write("[ROUTINE MAINTENANCE] Performing worm detection...\n")
try:
# Worm indicators
worm_processes = ['worm', 'autorun', 'spread', 'replicate', 'infect', 'propagate']
worm_files = ['autorun.inf', 'autorun.exe']
# Check for worm files
for scan_dir in critical_dirs:
if os.path.exists(scan_dir):
for root, dirs, files in os.walk(scan_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
file_lower = file.lower()
try:
if file_lower in worm_files:
recovery_results["worm_scans"].append({
"file": filepath,
"indicator": "worm_file",
"action": "detected"
})
output.write(f"[WORM] Worm-related file detected: {filepath}\n")
except Exception as e:
output.write(f"[WORM ERROR] Error checking {filepath}: {e}\n")
# Check for worm processes
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
proc_name = proc.info['name'].lower()
if any(worm_proc in proc_name for worm_proc in worm_processes):
recovery_results["worm_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"indicator": "worm_process",
"action": "detected"
})
output.write(f"[WORM] Suspicious worm process detected: {proc.info['name']} (PID: {proc.info['pid']})\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception as e:
output.write(f"[ERROR] Worm scanning failed: {e}\n")
recovery_results["errors"].append(f"Worm scanning: {str(e)}")
# 16. Adware scanning
output.write("[ROUTINE MAINTENANCE] Performing adware detection...\n")
try:
# Adware indicators
adware_processes = ['adware', 'popup', 'banner', 'ad', 'toolbar', 'coupon', 'deal', 'offer']
adware_registry_keys = [
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
r"SOFTWARE\Microsoft\Internet Explorer\Toolbar",
]
# Check for adware processes
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
proc_name = proc.info['name'].lower()
if any(ad_proc in proc_name for ad_proc in adware_processes):
recovery_results["adware_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"indicator": "adware_process",
"action": "detected"
})
output.write(f"[ADWARE] Suspicious adware process detected: {proc.info['name']} (PID: {proc.info['pid']})\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
# Check for adware in browser extensions directories
browser_dirs = [
os.path.join(os.environ.get('USERPROFILE', ''), 'AppData\\Local\\Google\\Chrome\\User Data'),
os.path.join(os.environ.get('USERPROFILE', ''), 'AppData\\Local\\Mozilla\\Firefox'),
os.path.join(os.environ.get('USERPROFILE', ''), 'AppData\\Local\\Microsoft\\Edge'),
]
for browser_dir in browser_dirs:
if os.path.exists(browser_dir):
try:
for root, dirs, files in os.walk(browser_dir):
for file in files:
time.sleep(0)
filepath = os.path.join(root, file)
file_lower = file.lower()
if any(ad_term in file_lower for ad_term in ['ad', 'popup', 'banner', 'coupon']):
recovery_results["adware_scans"].append({
"file": filepath,
"indicator": "adware_browser_extension",
"action": "flagged"
})
output.write(f"[ADWARE] Suspicious browser extension: {filepath}\n")
except Exception as e:
output.write(f"[ADWARE ERROR] Error scanning browser directory: {e}\n")
except Exception as e:
output.write(f"[ERROR] Adware scanning failed: {e}\n")
recovery_results["errors"].append(f"Adware scanning: {str(e)}")
# 17. Crypto miner scanning
output.write("[ROUTINE MAINTENANCE] Performing crypto miner detection...\n")
try:
# Crypto miner indicators
miner_processes = ['miner', 'xmrig', 'cpuminer', 'claymore', 'ethminer', 'nicehash', 'cryptonight']
miner_ports = [3333, 4444, 14444, 8888] # Common mining pool ports
# Check for crypto mining processes
for proc in psutil.process_iter(['pid', 'name', 'exe', 'cpu_percent']):
try:
proc_name = proc.info['name'].lower()
if any(miner_proc in proc_name for miner_proc in miner_processes):
recovery_results["crypto_miner_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"cpu_usage": proc.info.get('cpu_percent', 0),
"indicator": "crypto_miner_process",
"action": "detected"
})
output.write(f"[CRYPTO MINER] Crypto mining process detected: {proc.info['name']} (PID: {proc.info['pid']})\n")
# Check for high CPU usage that might indicate mining
if proc.info.get('cpu_percent', 0) > 80:
recovery_results["crypto_miner_scans"].append({
"process": proc.info['name'],
"pid": proc.info['pid'],
"cpu_usage": proc.info.get('cpu_percent', 0),
"indicator": "high_cpu_usage",
"action": "flagged"
})
output.write(f"[CRYPTO MINER] High CPU usage flagged: {proc.info['name']} (PID: {proc.info['pid']}) - {proc.info.get('cpu_percent', 0)}%\n")
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
# Check for connections to mining pool ports
for conn in psutil.net_connections(kind='inet'):
if conn.raddr and conn.raddr.port in miner_ports:
recovery_results["crypto_miner_scans"].append({
"remote_ip": conn.raddr.ip,
"remote_port": conn.raddr.port,
"pid": conn.pid,
"indicator": "mining_pool_connection",
"action": "detected"
})
output.write(f"[CRYPTO MINER] Mining pool connection detected: {conn.raddr.ip}:{conn.raddr.port} (PID: {conn.pid})\n")
except Exception as e:
output.write(f"[ERROR] Crypto miner scanning failed: {e}\n")
recovery_results["errors"].append(f"Crypto miner scanning: {str(e)}")
# 19. File entropy analysis for packed/encrypted malware
output.write("[ROUTINE MAINTENANCE] Performing file entropy analysis...\n")
try:
import math
def calculate_entropy(file_path, block_size=4096):
"""Calculate Shannon entropy of a file to detect packed/encrypted malware"""
try:
with open(file_path, 'rb') as f:
data = f.read(block_size)
if not data:
return 0
# Count byte frequencies
freq = [0] * 256
for byte in data:
freq[byte] += 1
# Calculate entropy
entropy = 0
data_len = len(data)
for count in freq:
if count > 0:
probability = count / data_len
entropy -= probability * math.log2(probability)
return entropy
except:
return 0
# Scan game directories for high-entropy files
game_dirs = [
os.path.join(os.environ.get('PROGRAMFILES', 'C:\\Program Files'), 'Steam'),
os.path.join(os.environ.get('PROGRAMFILES(X86)', 'C:\\Program Files (x86)'), 'Steam'),
os.path.join(os.environ.get('PROGRAMFILES', 'C:\\Program Files'), 'Epic Games'),
os.path.join(os.environ.get('USERPROFILE', ''), 'AppData\\Local\\EpicGamesLauncher'),
]
high_entropy_threshold = 7.5 # High entropy indicates packed/encrypted content
for game_dir in game_dirs:
if os.path.exists(game_dir):
for root, dirs, files in os.walk(game_dir):
for file in files:
time.sleep(0)
if file.endswith(('.exe', '.dll')):
filepath = os.path.join(root, file)
try:
entropy = calculate_entropy(filepath)
if entropy > high_entropy_threshold:
output.write(f"[ENTROPY] High entropy file detected: {filepath} (entropy: {entropy:.2f})\n")
recovery_results["entropy_scans"].append({
"file": filepath,
"entropy": entropy,
"status": "suspicious"
})
except Exception as e:
pass
except Exception as e:
output.write(f"[ERROR] Entropy analysis failed: {e}\n")
recovery_results["errors"].append(f"Entropy analysis: {str(e)}")
# 20. Digital signature verification for game executables
output.write("[ROUTINE MAINTENANCE] Performing digital signature verification...\n")
try:
import win32api
import win32con
def verify_signature(file_path):
"""Verify if a file has a valid digital signature"""
try:
info = win32api.GetFileVersionInfo(file_path, "\\")
if info:
return True
return False
except:
return False
# Known trusted publishers for games
trusted_publishers = ['Valve Corporation', 'Epic Games, Inc.', 'Electronic Arts', 'Ubisoft', 'Microsoft Corporation']
for game_dir in game_dirs:
if os.path.exists(game_dir):
for root, dirs, files in os.walk(game_dir):
for file in files:
time.sleep(0)
if file.endswith('.exe'):
filepath = os.path.join(root, file)
try:
has_signature = verify_signature(filepath)
if not has_signature:
output.write(f"[SIGNATURE] Unsigned executable detected: {filepath}\n")
recovery_results["signature_scans"].append({
"file": filepath,
"signed": False,
"status": "suspicious"
})
except Exception as e:
pass
except Exception as e:
output.write(f"[ERROR] Signature verification failed: {e}\n")
recovery_results["errors"].append(f"Signature verification: {str(e)}")
# 21. Import table analysis for suspicious DLL imports
output.write("[ROUTINE MAINTENANCE] Performing import table analysis...\n")
try:
# Suspicious API imports often used by malware
suspicious_apis = [
'CreateRemoteThread', 'WriteProcessMemory', 'VirtualAllocEx',
'ReadProcessMemory', 'OpenProcess', 'SetWindowsHookEx',
'InternetOpen', 'InternetConnect', 'HttpSendRequest',
'RegSetValueEx', 'RegCreateKeyEx', 'RegOpenKeyEx'
]
for game_dir in game_dirs:
if os.path.exists(game_dir):
for root, dirs, files in os.walk(game_dir):
for file in files:
time.sleep(0)
if file.endswith(('.exe', '.dll')):
filepath = os.path.join(root, file)
try:
# Read file as text to check for API names (simplified approach)