-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
666 lines (568 loc) · 24.9 KB
/
main.py
File metadata and controls
666 lines (568 loc) · 24.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
__author__ = "https://github.com/password123456/"
__version__ = "1.0.8.prod20250511"
import argparse
import hashlib
import os
import platform
import re
import subprocess
import sys
import time
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone, timedelta
# Define SHA256 hashes for BPFDoor malware
RAW_SHA256_HASHES = {
"c7f693f7f85b01a8c0e561bd369845f40bff423b0743c7aa0f4c323d9133b5d4",
"3f6f108db37d18519f47c5e4182e5e33cc795564f286ae770aa03372133d15c4",
"95fd8a70c4b18a9a669fec6eb82dac0ba6a9236ac42a5ecde270330b66f51595",
"aa779e83ff5271d3f2d270eaed16751a109eb722fca61465d86317e03bbf49e4",
"925ec4e617adc81d6fcee60876f6b878e0313a11f25526179716a90c3b743173",
"29564c19a15b06dd5be2a73d7543288f5b4e9e6668bbd5e48d3093fb6ddf1fdb",
"be7d952d37812b7482c1d770433a499372fde7254981ce2e8e974a67f6a088b5",
"027b1fed1b8213b86d8faebf51879ccc9b1afec7176e31354fbac695e8daf416",
"a2ea82b3f5be30916c4a00a7759aa6ec1ae6ddadc4d82b3481640d8f6a325d59",
"e04586672874685b019e9120fcd1509d68af6f9bc513e739575fc73edefd511d",
"adfdd11d69f4e971c87ca5b2073682d90118c0b3a3a9f5fbbda872ab1fb335c6",
"7c39f3c3120e35b8ab89181f191f01e2556ca558475a2803cb1f02c05c830423",
"ccd0a0914597e39042725f8588bf1ef5744c9c5f4bb2ac6af8857416b77ec8b0",
"d2604c1aac79371108af426aa426e975cea582eb7e9a1d6890ae8a8896cf0cc5",
"dc8346bf443b7b453f062740d8ae8d8d7ce879672810f4296158f90359dcae3a",
"e09efb3fb74728011ee52ec83b7f9764c899761432ba3e6b576b1b74605209bc",
"e764842d309d9465b8b27ad60fa4037708a06709205076124719d7dcfbbcc433",
"fa0defdabd9fd43fe2ef1ec33574ea1af1290bd3d763fdb2bed443f2bd996d73",
"fc7224ce94b5e02fd42f227e972d434f0eaf7dd3ed1540b43e986bdd6af44da0",
"fe9f3b7451913f184e1f53b52a03a981dcea5564633cfcb70d01bd0aec8f30a7",
"ff2a4e32c25b391bfe30f3761c692cf1bed6a4b568cdac93e6ffd621aa6b13de",
"f47de978da1dbfc5e0f195745e3368d3ceef034e964817c66ba01396a1953d72",
"f8a5e735d6e79eb587954a371515a82a15883cf2eda9d7ddb8938b86e714ea27",
"fd1b20ee5bd429046d3c04e9c675c41e9095bea70e0329bd32d7edd17ebaf68a",
"2e0aa3da45a0360d051359e1a038beff8551b957698f21756cfc6ed5539e4bdb",
"cca78516c62e1b7cf3c56b665a3537dca6beb54d335c633454b325fd44c4f760",
"d68948964905af7259bca015bd1d1ab0bb54334a6f08a87a40ed9d8cc966b291",
"d97625f7ad46e24fc958b1ab1c2de9591bad0127b204f99d7110fe1c401a9df4",
"a9884ba3ebf25dcb1b9b3319d5e9e3706832bfa0f1fc4248f22a065f7ef15f79",
"28bfb3f2067c77b83898ef4e41c9fc573e6aaa8581da9b59bddb782205a0b091",
"7906a1f358687ca1be8d9f531f066d6a5219857d37c13310c3239f10836007a8",
"b759020cbef57d96a5c978af3ae41bc1d9ffb7f3d521210a20b0d8d7540a13d4",
"afa8a32ec29a31f152ba20a30eb483520fe50f2dce6c9aa9135d88f7c9c511d7",
"86b15b16ffd63bf9261d864f6a748caa2456b16efb5cf91a145e779457225104",
"144526d30ae747982079d5d340d1ff116a7963aba2e3ed589e7ebc297ba0c1b3",
"14b1dea80394fb413fff084b0becd1904fd6077189d1ff73208d8d749529e00b",
"17ddd405e4ed78129808dcf5a3381568d8f74878ca0535249cfb31340950ea85",
"23320f05f929f6d587d86454c70f34c9ed3df38d32ae246a7636e6b6dc14a0c7",
"28ec71fe071a2a2126726277a34b25a77e0178005c860c5fb6308606831bbba3",
"340fec891eff2bbeccbef054a6b7e7e04fc09cf3b3b5fdf06accbd193a03b453",
"34dbc85ed0386e024c724c7969e8d0ff0ff0b1882508ea259c458d59657a1971",
"39d8d80a727ffab6e08ae2b9551f7251a652f4d4edfe5df21d0e2684d042268f",
"3a1b174f0c19c28f71e1babde01982c56d38d3672ea14d47c35ae3062e49b155",
"3fd677dccec69ce4f0ed20dded252e8ad132ac82e8eede0b8fbe1c1bec587acd",
"4713ac314e0fc64df3599b79331e867e1d3742e21cc4ca563e374868967efca5",
"48296c65770daca66bb644f54287772e80ad52ce8ca83cd50dceaa6902dd4e44",
"5cc90496eac10e79c149fd6208934d8a2c61edd8f89e5a1a0bea5ff5e3920d27",
"63d5390d4cd15fa700595b7273e2a834f11588f94066b71d9062212e97543b48",
"74b221ebd28924d5a4aab9f6d25afca982341013e6ce82cd89b71874775045b6",
"74ef6cc38f5a1a80148752b63c117e6846984debd2af806c65887195a8eccc56",
"79932f5a306ef08e27e0edc038f7449b0003bead5a3099f1f31917c399b09ed3",
"7c7db2ff3f428167aa8b59917fb1cde7e9244cb2240c0e24bddea5e0f0a26ff4",
"93f4262fce8c6b4f8e239c35a0679fbbbb722141b95a5f2af53a2bcafe4edd1c",
"9ea0645d862bc0604b47e9424bd27419f648ebc28ed6cd180b63fece7f3f4511",
"a002f27f1abb599f24e727c811efa36d2d523e586a82134e9b3e8454dde6a089",
"a0a3a45adf5258414344214c3d2c661a570f54609b7d87d5ac24eb37fd30c3e6",
"af1911d5ad4653e5c972dcfe912fe2e2c928dc16d306609ffbb446ee11fca174",
"b83127fbde5074247b81012553de69604365f7c4c378d8bcb54552c81ea85414",
"b8d775e2c9a18504aff01d8464fab1c470a8a37b501451fd9af6b4a848b42051",
"bd353a28886815f43fe71c561a027fdeff5cd83e17e2055c0e52bea344ae51d3",
"cc61091ac6c8a8219b54f8f07976a2ab915e7675f715a00b8488ba180a5b3a07",
"07ecb1f2d9ffbd20a46cd36cd06b022db3cc8e45b1ecab62cd11f9ca7a26ab6d",
"3631f806f84643aead8c4995e7bf6177d889d610cd9bdb13354aea1fc7d3a2b5",
"3743821d55513c52a9f06d3f6603afd167105a871e410c35a3b94e34c51089e6",
"4c5cf8f977fc7c368a8e095700a44be36c8332462c0b1e41bff03238b2bf2a2d",
"599ae527f10ddb4625687748b7d3734ee51673b664f2e5d0346e64f85e185683",
"5b2a079690efb5f4e0944353dd883303ffd6bab4aad1f0c88b49a76ddcb28ee9",
"5faab159397964e630c4156f8852bcc6ee46df1cdd8be2a8d3f3d8e5980f3bb3",
"6fbdb38a85a416557d292566db8662d70461c8c8d0c51a0f78130c5c3646e93f",
"76bf736b25d5c9aaf6a84edd4e615796fffc338a893b49c120c0b4941ce37925",
"7f5b419ea75b2c1fb4a7000c8d9ea2918d9a3423000506b718f8de8b4a25f157",
"8a602fb9b7c407a13f6e0af4cae702018a7d6bcf36aadb2478ce17a0b668c6d2",
"8b84336e73c6a6d154e685d3729dfa4e08e4a3f136f0b2e7c6e5970df9145e95",
"96e906128095dead57fdc9ce8688bb889166b67c9a1b8fdb93d7cff7f3836bb9",
"97a546c7d08ad34dfab74c9c8a96986c54768c592a8dae521ddcf612a84fb8cc",
"a907e1e8145f46274943fb7451c62d83f5e5e683f57a69ddb7dbb520e04e04ce",
"ac06771774538f33b0e95a92ae1a3e8aaf27e188b51700a03c14ca097af09cac",
"c796fc66b655f6107eacbe78a37f0e8a2926f01fecebd9e68a66f0e261f91276",
"c80bd1c4a796b4d3944a097e96f384c85687daeedcdcf05cc885c8c9b279b09c",
"dfdabe9013e783535a76407b61b63e97db283daab202218077cc0b846b3caa42",
"be7d952d37812b7482c1d770433a499372fde7254981ce2e8e974a67f6a088b5",
"a960aa060dfa3aeedfe8b37725839130e1906ade716c9b5405e80dc27f57a4cb",
"925ec4e617adc81d6fcee60876f6b878e0313a11f25526179716a90c3b743173",
"29564c19a15b06dd5be2a73d7543288f5b4e9e6668bbd5e48d3093fb6ddf1fdb",
"027b1fed1b8213b86d8faebf51879ccc9b1afec7176e31354fbac695e8daf416",
"a2ea82b3f5be30916c4a00a7759aa6ec1ae6ddadc4d82b3481640d8f6a325d59",
"e04586672874685b019e9120fcd1509d68af6f9bc513e739575fc73edefd511d",
"591198c234416c6ccbcea6967963ca2ca0f17050be7eed1602198308d9127c78",
"1925e3cd8a1b0bba0d297830636cdb9ebf002698c8fa71e0063581204f4e8345",
}
def initialize_hashes(hash_list):
"""Initialize SHA256 hash list, removing duplicates and validating format."""
valid_hashes = set()
sha256_pattern = re.compile(r"^[0-9a-fA-F]{64}$") # SHA256: 64-character hex
for hash_value in hash_list:
hash_value = hash_value.strip().lower()
if not sha256_pattern.match(hash_value):
print(
f"{Bcolors.Yellow}[Warning] Invalid SHA256 hash skipped: {hash_value}{Bcolors.Endc}"
)
continue
valid_hashes.add(hash_value)
if len(valid_hashes) < len(hash_list):
print(
f"{Bcolors.Yellow}[Info] Removed {len(hash_list) - len(valid_hashes)} duplicate or invalid hashes{Bcolors.Endc}"
)
return valid_hashes
# Initialize hash set for BPFDoor detection, removing duplicates and invalid entries
STATIC_SHA256_HASHES = initialize_hashes(RAW_SHA256_HASHES)
# File extensions to scan (empty list scans all files)
# SCAN_EXTENSIONS = ['.exe', '.dll', '.sys', '.doc'] # exe, dll, sys, doc
SCAN_EXTENSIONS = []
# Directories to exclude from scanning (empty list scans all directories
EXCLUDE_DIRS = [
"/proc",
"/sys",
"/dev",
]
# Maximum file size to scan (default: 2MB)
MAX_SCAN_FILE_SIZE = "2MB"
# Number of files per thread for parallel processing
CHUNK_SIZE_MULTIPLIER = 100
# Log file path for scan results
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
SCAN_RESULT_LOG = f'{BASE_PATH}/{datetime.today().strftime("%Y%m%d")}_malscan.log'
class Bcolors:
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
White = "\033[37m"
RedBg = "\033[41m"
WhiteBg = "\033[47m"
YellowBg = "\033[43m"
BlueBg = "\033[44m"
GreenBg = "\033[42m"
Black = "\033[30m"
Bold = "\033[1m"
Underline = "\033[4m"
Endc = "\033[0m"
def display_header():
tool_name = "Linux BPFDoor Malware Scanner"
ascii_art_left = "▌║█║▌│║▌│║▌║▌█║"
ascii_art_right = "▌│║▌║▌│║║▌█║▌║█"
print(
f"\n{Bcolors.Green}{Bcolors.Bold}{ascii_art_left} "
f"{Bcolors.Yellow}{tool_name} "
f"{Bcolors.Green}{ascii_art_right}{Bcolors.Endc}\n"
)
print(f"{Bcolors.White}[-] By {__author__} / {__version__}{Bcolors.Endc}")
# Convert size string (e.g., '2MB') to bytes
def parse_size(size_str):
try:
size_str = size_str.upper()
if size_str.endswith("MB"):
size_mb = float(size_str[:-2])
return int(size_mb * 1024 * 1024)
else:
raise ValueError("Size must be specified in MB (e.g., '2MB')")
except (ValueError, TypeError) as e:
print(
f"{Bcolors.Red}[Error] Invalid MAX_FILE_SIZE format: {size_str}. Using default 2MB{Bcolors.Endc}"
)
return 2048000 # Default 2MB
def hash_exists_in_db(check_hash):
return check_hash in STATIC_SHA256_HASHES
def is_excluded_dir(path):
return any(path.startswith(os.path.abspath(excluded)) for excluded in EXCLUDE_DIRS)
def scan_result_logs(log_entry):
mode = "a" if os.path.exists(SCAN_RESULT_LOG) else "w"
with open(SCAN_RESULT_LOG, mode, encoding="utf-8") as fa:
fa.write(log_entry)
def compute_sha256(file_path):
try:
if os.path.isfile(file_path):
with open(file_path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
except Exception:
return None
def verify_file_extension(file_path):
if SCAN_EXTENSIONS:
ext = os.path.splitext(file_path)[1].lower()
return ext in [e.lower() for e in SCAN_EXTENSIONS]
return True
def check_file_size(file_path, max_size):
try:
return os.path.getsize(file_path) <= max_size
except Exception:
return False
def is_root_privileges():
if platform.system() == "Windows":
return True
return "SUDO_UID" in os.environ or os.geteuid() == 0
def get_create_date(file_path):
try:
if platform.system() == "Windows":
timestamp = os.path.getctime(file_path)
else:
timestamp = os.path.getmtime(file_path)
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return None
def get_modify_date(file_path):
try:
timestamp = os.path.getmtime(file_path)
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return None
def get_hostname():
return platform.node()
def get_os_info():
os_info = {"version_id": "Unknown", "id": "Unknown", "display_name": "Unknown"}
system = platform.system()
if system == "Linux":
if os.path.isfile("/etc/os-release"):
with open("/etc/os-release", "r", encoding="utf-8") as file:
for line in file:
line = line.strip()
if line.lower().startswith("version_id="):
os_info["version_id"] = line.split("=")[1].strip('"')
elif line.lower().startswith("id="):
os_info["id"] = line.split("=")[1].strip('"')
elif line.lower().startswith("pretty_name="):
os_info["display_name"] = line.split("=")[1].strip('"')
elif system == "Windows":
version = platform.version()
release = platform.release()
os_info["version_id"] = version
os_info["id"] = "windows"
os_info["display_name"] = f"Microsoft Windows {release} (Version {version})"
elif system == "Darwin":
mac_version, _, _ = platform.mac_ver()
os_info["version_id"] = mac_version
os_info["id"] = "macos"
os_info["display_name"] = f"macOS {mac_version}"
return os_info["version_id"], os_info["id"], os_info["display_name"]
def get_os_arch():
return platform.machine()
def get_ip_addrs():
system = platform.system()
ip_set = set()
try:
if system == "Linux":
result = subprocess.run(
["ip", "-4", "addr"], capture_output=True, text=True
)
for line in result.stdout.splitlines():
if "inet" in line and "inet6" not in line:
ip = line.split()[1].split("/")[0]
if ip != "127.0.0.1":
ip_set.add(ip)
elif system == "Windows":
result = subprocess.run(["ipconfig"], capture_output=True, text=True)
ip_pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
for line in result.stdout.splitlines():
if "IPv4" in line:
matches = re.findall(ip_pattern, line)
for ip in matches:
if ip != "127.0.0.1":
ip_set.add(ip)
elif system == "Darwin": # macOS
result = subprocess.run(["ifconfig"], capture_output=True, text=True)
for line in result.stdout.splitlines():
if "inet " in line and "inet6" not in line:
ip = line.split()[1]
if ip != "127.0.0.1":
ip_set.add(ip)
return ", ".join(ip_set) if ip_set else "[none]"
except Exception as e:
return f"[error] Could not retrieve IPs: {str(e)}"
def get_mac_addr():
system = platform.system()
mac_set = set()
try:
if system == "Linux":
result = subprocess.run(["ip", "link"], capture_output=True, text=True)
for line in result.stdout.splitlines():
if "link/ether" in line:
mac = line.split()[1]
if mac != "00:00:00:00:00:00":
mac_set.add(mac)
elif system == "Windows":
result = subprocess.run(
["getmac", "/fo", "list"], capture_output=True, text=True
)
mac_pattern = r"[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}-[0-9A-Fa-f]{2}"
for line in result.stdout.splitlines():
matches = re.findall(mac_pattern, line)
for mac in matches:
mac = mac.replace("-", ":")
if mac != "00:00:00:00:00:00":
mac_set.add(mac.lower())
elif system == "Darwin":
result = subprocess.run(["ifconfig"], capture_output=True, text=True)
for line in result.stdout.splitlines():
if "ether" in line and "status" not in line:
mac = line.split()[1]
if mac != "00:00:00:00:00:00":
mac_set.add(mac)
return ", ".join(mac_set) if mac_set else "[none]"
except Exception as e:
return f"[error] Could not retrieve MAC addresses: {str(e)}"
def create_scan_job_id():
return uuid.uuid4()
def yield_file_chunks(_scan_path, chunk_size=None):
if chunk_size is None:
max_workers = min(os.cpu_count() or 4, 8)
chunk_size = max_workers * CHUNK_SIZE_MULTIPLIER
chunk = []
try:
for subdir, dirs, files in os.walk(_scan_path, onerror=lambda err: None):
if EXCLUDE_DIRS:
dirs[:] = [
d for d in dirs if not is_excluded_dir(os.path.join(subdir, d))
]
for file in files:
_f_file_name = os.path.realpath(os.path.join(subdir, file))
chunk.append(_f_file_name)
if len(chunk) >= chunk_size:
yield chunk
chunk = []
if chunk:
yield chunk
except Exception as e:
print(f"[!] Skipping scan: pass exception {e} during directory traversal")
pass
def scan_file(file_path):
try:
if not (os.path.exists(file_path) and os.access(file_path, os.R_OK)):
print(f"[!] Skipping {file_path}: File Not found OR Failed to read")
return ""
max_size_bytes = parse_size(MAX_SCAN_FILE_SIZE)
if not check_file_size(file_path, max_size_bytes):
print(f"[!] Skipping {file_path}: Scan file size exceeded")
return ""
if not verify_file_extension(file_path):
print(f"[!] Skipping {file_path}: Extension not in {SCAN_EXTENSIONS}")
return ""
file_hash = compute_sha256(file_path)
if not file_hash:
return ""
return (
f"{file_path}|{file_hash}|"
f"{get_create_date(file_path)}|{get_modify_date(file_path)}"
)
except Exception:
return ""
def scan_directory(
scan_path,
system_hostname,
system_ips,
system_mac_addr,
system_os_arch,
system_os_displayname,
verbose=False,
):
scan_path = os.path.abspath(scan_path)
if is_excluded_dir(scan_path):
if verbose:
print(f"[!] Skipping scan: {scan_path} is in EXCLUDE_DIRS")
return
# Initialize scan metadata
scan_job_id = create_scan_job_id()
scanned_file_count = 0
infected_file_count = 0
total_file_count = 0
scan_start_time = time.perf_counter()
# Set number of threads for parallel scanning
max_workers = min(os.cpu_count() or 4, 8)
chunk_size = max_workers * CHUNK_SIZE_MULTIPLIER
# Process files in parallel using ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=max_workers) as executor:
for chunk in yield_file_chunks(scan_path, chunk_size=chunk_size):
futures = []
for _f_file_name in chunk:
total_file_count += 1
future = executor.submit(scan_file, _f_file_name)
future.arg = _f_file_name
futures.append(future)
# Process scan results
for future in as_completed(futures):
result = future.result()
if not result:
if verbose:
print(
f'[!] Skipping scan: {getattr(future, "arg", "unknown")} '
f"(file extension, size exceed, read error)"
)
continue
scanned_file_count += 1
# Calculate scan duration
scan_duration_time = time.perf_counter() - scan_start_time
duration = timedelta(seconds=scan_duration_time)
scan_duration_formatted = (
datetime(1970, 1, 1, tzinfo=timezone.utc) + duration
).strftime("%H:%M:%S.%f")[:-3]
file_path, sha256, created, modified = result.split("|")
infected = sha256 and hash_exists_in_db(sha256)
if infected:
infected_file_count += 1
# Log infected file details
log_contents = (
f'datetime="{datetime.today().strftime("%Y-%m-%d %H:%M:%S")}",'
f'scan_id="{scan_job_id}",'
f'hostname="{system_hostname}",'
f'ip="{system_ips}",'
f'mac="{system_mac_addr}",'
f'arch="{system_os_arch}",'
f'os="{system_os_displayname}",'
f'infected_file="{file_path}",'
f'sha256="{sha256}",'
f'created_at="{created}",'
f'modified_at="{modified}"\n'
)
scan_result_logs(log_contents)
# Display scan status
status_text = (
f"{Bcolors.Red}(Infected){Bcolors.Endc}"
if infected
else f"{Bcolors.Green}(Clean){Bcolors.Endc}"
)
infected_summary = (
f"{infected_file_count} files infected"
if infected_file_count > 0
else "0 Infected"
)
print(
f"[{scan_duration_formatted}] ({scanned_file_count} scanned / {infected_summary}) "
f"{status_text} {file_path}"
)
# Display scan summary
print("\n")
print(
f"[Summary]\n"
f"[-] Total files found: {total_file_count}\n"
f"[-] Scanned: {scanned_file_count}, Infected: {infected_file_count}"
)
if infected_file_count >= 1:
print(
f"{Bcolors.RedBg}{Bcolors.White} Scan Completed! {Bcolors.Endc}\n"
f"- O.M.G... {Bcolors.YellowBg}{Bcolors.Black}[{infected_file_count}] file(s) infected.{Bcolors.Endc}\n"
f'- See "{SCAN_RESULT_LOG}" {Bcolors.Yellow}'
)
else:
scan_result_logs(
f'datetime="{datetime.today().strftime("%Y-%m-%d %H:%M:%S")}",'
f'scan_id="{scan_job_id}",'
f'hostname="{system_hostname}",'
f'ip="{system_ips}",'
f'mac="{system_mac_addr}",'
f'arch="{system_os_arch}",'
f'os="{system_os_displayname}",'
f'infected_file="None"\n'
)
print(
f"{Bcolors.GreenBg}{Bcolors.Black} Scan Completed! {Bcolors.Endc}\n"
f"- No infected files found. Happy happy :)\n"
)
def main():
display_header()
if sys.version_info < (3, 8, 10):
print("[-] This tool requires Python 3.8.10 or higher.")
print(
f"[-] Current Python version: "
f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
)
sys.exit(1)
if not is_root_privileges():
print(
"[-] This tool requires sudo privileges. "
'Please run with sudo privileges or "root" user'
)
sys.exit(1)
system_hostname = get_hostname()
system_ips = get_ip_addrs()
system_mac_addr = get_mac_addr()
system_os_arch = get_os_arch()
system_os_ver, system_os_id, system_os_displayname = get_os_info()
opt = argparse.ArgumentParser()
opt.add_argument(
"-mode",
choices=["full", "normal", "custom"],
help="Scan mode: full, normal, or custom",
)
opt.add_argument(
"paths",
nargs="*",
help="Paths to scan (required for custom mode, e.g., /home /opt)",
)
opt.add_argument("--verbose", action="store_true", help="Enable debug messages")
options = opt.parse_args()
print(f'[-] {datetime.today().strftime("%Y-%m-%d %H:%M:%S")}\n')
if not options.mode:
opt.print_help()
sys.exit(1)
scan_paths = []
if options.mode == "full":
scan_paths = ["/"]
if os.path.abspath("/") in [os.path.abspath(p) for p in scan_paths]:
print(
f"{Bcolors.Yellow}[Warning] Scanning the root directory (/) can take a long time. "
f"We recommend specifying a directory (for example, /home){Bcolors.Endc}"
)
elif options.mode == "normal":
scan_paths = [
"/bin",
"/sbin",
"/usr/bin",
"/usr/sbin",
"/lib",
"/usr/lib",
"/etc",
"/lib64",
"/tmp",
"/var",
"/dev/shm",
"/opt",
"/home",
]
elif options.mode == "custom":
if not options.paths:
print(
f"{Bcolors.Red}[Error] Custom mode requires at least one path (e.g., -mode custom /home /opt){Bcolors.Endc}"
)
opt.print_help()
sys.exit(1)
scan_paths = [os.path.abspath(p) for p in options.paths]
for path in scan_paths:
if not os.path.exists(path):
print(f"{Bcolors.Red}[Error] Path {path} does not exist{Bcolors.Endc}")
sys.exit(1)
print(f"[*]{Bcolors.Green} O.K Here We go!{Bcolors.Endc}")
print(f"[*] {system_hostname} / {system_ips} / {system_os_displayname}")
print(f'[*] Scanning paths: {", ".join(scan_paths)}\n')
for path in scan_paths:
print(f"\nScanning: {path}\n")
scan_directory(
path,
system_hostname,
system_ips,
system_mac_addr,
system_os_arch,
system_os_displayname,
verbose=options.verbose,
)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
print(
f"{Bcolors.Yellow}[Exception] Line:[{sys.exc_info()[-1].tb_lineno}] [{type(e).__name__}] {e}{Bcolors.Endc}"
)