Skip to content

Commit aceb9bd

Browse files
Fixed major issues
dump_memory.py: Added failsafe check for disk space Logger.py: Made the @function decorator better, by having more precision in its output vulnscan.py: Added a threadlock as a failsafe to not overload the system Signed-off-by: Shahm Najeeb <Nirt_12023@outlook.com>
1 parent dc4e534 commit aceb9bd

File tree

5 files changed

+40
-18
lines changed

5 files changed

+40
-18
lines changed

CODE/dump_memory.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,20 @@ def gather_system_info():
6262
def memory_dump():
6363
log.info("Creating basic memory dump scan...")
6464
pid = os.getpid()
65+
6566
try:
6667
process = psutil.Process(pid)
6768
with open("Ram_Dump.txt", "wb") as dump_file:
6869
total_size = 0
6970
for mem_region in process.memory_maps(grouped=False):
71+
# Check available disk space
72+
if os.path.exists("Ram_Dump.txt"):
73+
required_space = LIMIT_FILE_SIZE * 1024 * 1024 * 1.5 # 2x safety margin
74+
free_space = psutil.disk_usage(".").free
75+
if free_space < required_space:
76+
log.error(f"Not enough disk space. Need {required_space / 1024 / 1024:.2f}MB")
77+
return
78+
7079
# Check if the memory region is readable ('r' permission)
7180
if 'r' in mem_region.perms:
7281
# Extract start and end addresses from the memory region string
@@ -112,6 +121,7 @@ def memory_dump():
112121
total_size += len(metadata_bytes)
113122
except Exception as e:
114123
log.error(f"Error writing memory region metadata: {str(e)}")
124+
115125
except psutil.Error as e:
116126
log.error(f"Error opening process memory: {str(e)}")
117127
except Exception as e:

CODE/logicytics/Logger.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,8 @@ def function(self, func: callable):
273273
:param func: The function to be decorated.
274274
:return: The wrapper function.
275275
"""
276+
if not callable(func):
277+
self.exception(f"Function {func.__name__} is not callable.", TypeError)
276278

277279
def wrapper(*args, **kwargs):
278280
"""
@@ -283,14 +285,14 @@ def wrapper(*args, **kwargs):
283285
:raises TypeError: If the provided function is not callable.
284286
:return: The result of the decorated function.
285287
"""
286-
if not callable(func):
287-
self.exception(f"Function {func.__name__} is not callable.", TypeError)
288288
start_time = time.perf_counter()
289-
self.debug(f"Running the function {func.__name__}().")
289+
func_args = ", ".join([str(arg) for arg in args] +
290+
[f"{k}={v}" for k, v in kwargs.items()])
291+
self.debug(f"Running the function {func.__name__}({func_args}).")
290292
result = func(*args, **kwargs)
291293
end_time = time.perf_counter()
292294
elapsed_time = end_time - start_time
293-
self.debug(f"Function {func.__name__}() executed in {elapsed_time:.6f} seconds.")
295+
self.debug(f"{func.__name__}({func_args}) executed in {elapsed_time} -> returned {type(result).__name__}")
294296
return result
295297

296298
return wrapper

CODE/packet_sniffer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def save_packet_data_to_csv(file_path: str):
197197
log.warning("No packet data to save.")
198198

199199

200-
# Function to visualize the graph
200+
# Function to visualize the graph of packet connections
201201
def visualize_graph(node_colors: str = None, node_sizes: str = None):
202202
"""
203203
Visualizes the graph of packet connections with customizable node colors and sizes.

CODE/sensitive_data_miner.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def __search_and_copy_files(cls, keyword: str):
8888
destination.mkdir()
8989

9090
with ThreadPoolExecutor() as executor:
91-
for root, dirs, files in os.walk(drives_root):
91+
for root, dirs, _ in os.walk(drives_root):
9292
future_to_file = {
9393
executor.submit(cls.__search_files_by_keyword, Path(root) / sub_dir, keyword): sub_dir
9494
for sub_dir in dirs
@@ -107,7 +107,8 @@ def passwords(cls):
107107
Returns:
108108
None
109109
"""
110-
keywords = ["password", "secret", "code", "login", "api", "key"]
110+
keywords = ["password", "secret", "code", "login", "api", "key",
111+
"token", "auth", "credentials", "private", ]
111112

112113
# Ensure the destination directory is clean
113114
destination = Path("Password_Files")

CODE/vulnscan.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import threading
66
import warnings
7+
from concurrent.futures import ThreadPoolExecutor
78

89
import joblib
910
import numpy as np
@@ -67,8 +68,8 @@ def scan_path(model_path: str, scan_paths: str, vectorizer_path: str):
6768
log.info(f"Loading vectorizer from {vectorizer_path}")
6869
vectorizer_to_use = joblib.load(vectorizer_path)
6970
vulnscan(model_to_use, scan_paths, vectorizer_to_use)
70-
except Exception as e:
71-
log.error(f"Error scanning path {scan_paths}: {e}")
71+
except Exception as err:
72+
log.error(f"Error scanning path {scan_paths}: {err}")
7273

7374

7475
def is_sensitive(model: torch.nn.Module, vectorizer: TfidfVectorizer, file_content: str) -> tuple[bool, float, str]:
@@ -177,12 +178,20 @@ def vulnscan(model, SCAN_PATH, vectorizer):
177178
# Start scanning
178179
log.warning("Starting scan - This may take hours and consume memory!!")
179180

180-
for path in paths:
181-
thread = threading.Thread(target=scan_path,
182-
args=("VulnScan/Model SenseMini .3n3.pth",
183-
path, "VulnScan/Vectorizer .3n3.pkl"))
184-
threads.append(thread)
185-
thread.start()
186-
187-
for thread in threads:
188-
thread.join()
181+
# Use max_workers based on CPU count but cap it at a reasonable number
182+
max_workers = min(32, os.cpu_count() * 2)
183+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
184+
futures = [
185+
executor.submit(
186+
scan_path,
187+
"VulnScan/Model SenseMini .3n3.pth",
188+
path,
189+
"VulnScan/Vectorizer .3n3.pkl"
190+
)
191+
for path in paths
192+
]
193+
for future in futures:
194+
try:
195+
future.result()
196+
except Exception as e:
197+
log.error(f"Scan failed: {e}")

0 commit comments

Comments
 (0)