anti-abuse/utils/Scanner.py

44 lines
1.2 KiB
Python
Raw Normal View History

2025-03-23 19:04:26 +01:00
#region Imports
2025-03-24 20:07:14 +00:00
import os, yara, tomllib
from utils.Logger import Log
2025-03-23 19:04:26 +01:00
#endregion
#region Variables
scanned_files_map = set()
ignored_files = {}
ignored_directories = {}
with open("./config.toml", "rb") as f:
data = tomllib.load(f)
#endregion
#region scanfile
2025-03-24 18:03:56 +00:00
def scan(src):
2025-03-23 19:04:26 +01:00
"""
Scan a file with YARA rules and return the matches.
Args:
file_path (str): The path to the file to be scanned.
Returns:
matches[filename], error_message
"""
matches = {}
error_messages = {}
for filename in os.listdir(data['DETECTION']['SignaturePath']):
2025-03-24 20:07:14 +00:00
if filename.endswith(".yara") or filename.endswith(".yar"): # both are yara extensions ok
2025-03-23 19:04:26 +01:00
rule_path = os.path.join(data['DETECTION']['SignaturePath'], filename)
try:
rules = yara.compile(filepath=rule_path)
2025-03-24 18:03:56 +00:00
file_matches = rules.match(data=src)
2025-03-23 19:04:26 +01:00
if file_matches:
matches[filename] = file_matches
2025-03-24 20:07:14 +00:00
#for match in file_matches:
# Log.v(f" - Rule: {match.rule}")
2025-03-23 19:04:26 +01:00
except yara.Error as e:
2025-03-24 20:07:14 +00:00
Log.e(e)
2025-03-23 19:04:26 +01:00
error_messages[filename] = e
return matches, error_messages
#endregion