Skip to content

Commit ccb9668

Browse files
Merge branch 'bug-fixes-and-v3.3.0' into coderabbitai/docstrings/a11ce93
2 parents 990efc4 + 940c015 commit ccb9668

File tree

6 files changed

+85
-43
lines changed

6 files changed

+85
-43
lines changed

.idea/csv-editor.xml

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

CODE/dump_memory.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,20 @@ def memory_dump():
122122
"""
123123
log.info("Creating basic memory dump scan...")
124124
pid = os.getpid()
125+
125126
try:
126127
process = psutil.Process(pid)
127128
with open("Ram_Dump.txt", "wb") as dump_file:
128129
total_size = 0
129130
for mem_region in process.memory_maps(grouped=False):
131+
# Check available disk space
132+
if os.path.exists("Ram_Dump.txt"):
133+
required_space = LIMIT_FILE_SIZE * 1024 * 1024 * 1.5 # 2x safety margin
134+
free_space = psutil.disk_usage(".").free
135+
if free_space < required_space:
136+
log.error(f"Not enough disk space. Need {required_space / 1024 / 1024:.2f}MB")
137+
return
138+
130139
# Check if the memory region is readable ('r' permission)
131140
if 'r' in mem_region.perms:
132141
# Extract start and end addresses from the memory region string
@@ -172,6 +181,7 @@ def memory_dump():
172181
total_size += len(metadata_bytes)
173182
except Exception as e:
174183
log.error(f"Error writing memory region metadata: {str(e)}")
184+
175185
except psutil.Error as e:
176186
log.error(f"Error opening process memory: {str(e)}")
177187
except Exception as e:

CODE/logicytics/Logger.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,8 @@ def example_function():
349349
# Function implementation
350350
pass
351351
"""
352+
if not callable(func):
353+
self.exception(f"Function {func.__name__} is not callable.", TypeError)
352354

353355
def wrapper(*args, **kwargs):
354356
"""
@@ -371,14 +373,14 @@ def wrapper(*args, **kwargs):
371373
- Measures and logs the total execution time with microsecond precision
372374
- Preserves the original function's return value
373375
"""
374-
if not callable(func):
375-
self.exception(f"Function {func.__name__} is not callable.", TypeError)
376376
start_time = time.perf_counter()
377-
self.debug(f"Running the function {func.__name__}().")
377+
func_args = ", ".join([str(arg) for arg in args] +
378+
[f"{k}={v}" for k, v in kwargs.items()])
379+
self.debug(f"Running the function {func.__name__}({func_args}).")
378380
result = func(*args, **kwargs)
379381
end_time = time.perf_counter()
380382
elapsed_time = end_time - start_time
381-
self.debug(f"Function {func.__name__}() executed in {elapsed_time:.6f} seconds.")
383+
self.debug(f"{func.__name__}({func_args}) executed in {elapsed_time} -> returned {type(result).__name__}")
382384
return result
383385

384386
return wrapper

CODE/packet_sniffer.py

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,15 @@
1313
if __name__ == "__main__":
1414
log = Log({"log_level": DEBUG})
1515

16-
try:
17-
# Read configuration from config.ini
18-
config = ConfigParser()
19-
config.read('config.ini')
20-
config = config['PacketSniffer Settings']
16+
# Read configuration from config.ini
17+
config = ConfigParser()
18+
config.read('config.ini')
19+
config = config['PacketSniffer Settings']
2120

22-
# Global configuration
23-
conf.verb = 0 # Turn off verbosity for clean output
24-
packet_data = [] # List to store packet information
25-
G = nx.Graph() # Initialize a graph
26-
except Exception as e:
27-
log.error(f"Error reading configuration: {e}")
28-
exit(1)
21+
# Global configuration
22+
conf.verb = 0 # Turn off verbosity for clean output
23+
packet_data = [] # List to store packet information
24+
G = nx.Graph() # Initialize a graph
2925

3026

3127
# Function to process and log packet details
@@ -274,7 +270,7 @@ def save_packet_data_to_csv(file_path: str):
274270
log.warning("No packet data to save.")
275271

276272

277-
# Function to visualize the graph
273+
# Function to visualize the graph of packet connections
278274
def visualize_graph(node_colors: str = None, node_sizes: str = None):
279275
"""
280276
Visualizes the graph of packet connections with customizable node colors and sizes.
@@ -345,6 +341,14 @@ def packet_sniffer():
345341
- Calls start_sniffing() to capture network packets
346342
- Exits the program if critical configuration errors are encountered
347343
"""
344+
345+
def correct_interface_name(interface_name: str) -> str:
346+
corrections = {
347+
"WiFi": "Wi-Fi",
348+
"Wi-Fi": "WiFi"
349+
}
350+
return corrections.get(interface_name, interface_name)
351+
348352
interface = config['interface']
349353
packet_count = int(config['packet_count'])
350354
timeout = int(config['timeout'])
@@ -360,18 +364,16 @@ def packet_sniffer():
360364
log.error("Error reading configuration: Improper values for packet count or timeout")
361365
exit(1)
362366

363-
try:
364-
start_sniffing(interface, packet_count, timeout)
365-
except Exception as err:
366-
log.error(f"Invalid interface '{interface}'. Please check the configuration: {err}")
367-
if interface == "WiFi" or interface == "Wi-Fi":
368-
log.warning("Attempting to correct the interface name...")
369-
interface = "Wi-Fi" if interface == "WiFi" else "WiFi"
370-
log.info(f"Interface name auto-corrected to '{interface}', retrying packet sniffing...")
371-
try:
372-
start_sniffing(interface, packet_count, timeout)
373-
except Exception as err:
374-
log.error(f"Error sniffing packets on auto-corrected interface '{interface}': {err}")
367+
for attempt in range(2): # Try original and corrected name
368+
try:
369+
start_sniffing(interface, packet_count, timeout)
370+
break
371+
except Exception as err:
372+
if attempt == 0 and interface in ("WiFi", "Wi-Fi"):
373+
log.warning(f"Retrying with corrected interface name...")
374+
interface = correct_interface_name(interface)
375+
else:
376+
log.error(f"Failed to sniff packets: {err}")
375377

376378

377379
# Entry point of the script
@@ -380,4 +382,6 @@ def packet_sniffer():
380382
packet_sniffer()
381383
except Exception as e:
382384
log.error(e)
383-
exit(1)
385+
finally:
386+
if G:
387+
plt.close()

CODE/sensitive_data_miner.py

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

122122
with ThreadPoolExecutor() as executor:
123-
for root, dirs, files in os.walk(drives_root):
123+
for root, dirs, _ in os.walk(drives_root):
124124
future_to_file = {
125125
executor.submit(cls.__search_files_by_keyword, Path(root) / sub_dir, keyword): sub_dir
126126
for sub_dir in dirs
@@ -159,7 +159,8 @@ def passwords(cls):
159159
Logging:
160160
- Logs an informational message upon completion of the search and copy process
161161
"""
162-
keywords = ["password", "secret", "code", "login", "api", "key"]
162+
keywords = ["password", "secret", "code", "login", "api", "key",
163+
"token", "auth", "credentials", "private", ]
163164

164165
# Ensure the destination directory is clean
165166
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
@@ -82,8 +83,8 @@ def scan_path(model_path: str, scan_paths: str, vectorizer_path: str):
8283
log.info(f"Loading vectorizer from {vectorizer_path}")
8384
vectorizer_to_use = joblib.load(vectorizer_path)
8485
vulnscan(model_to_use, scan_paths, vectorizer_to_use)
85-
except Exception as e:
86-
log.error(f"Error scanning path {scan_paths}: {e}")
86+
except Exception as err:
87+
log.error(f"Error scanning path {scan_paths}: {err}")
8788

8889

8990
def is_sensitive(model: torch.nn.Module, vectorizer: TfidfVectorizer, file_content: str) -> tuple[bool, float, str]:
@@ -203,12 +204,20 @@ def vulnscan(model, SCAN_PATH, vectorizer):
203204
# Start scanning
204205
log.warning("Starting scan - This may take hours and consume memory!!")
205206

206-
for path in paths:
207-
thread = threading.Thread(target=scan_path,
208-
args=("VulnScan/Model SenseMini .3n3.pth",
209-
path, "VulnScan/Vectorizer .3n3.pkl"))
210-
threads.append(thread)
211-
thread.start()
212-
213-
for thread in threads:
214-
thread.join()
207+
# Use max_workers based on CPU count but cap it at a reasonable number
208+
max_workers = min(32, os.cpu_count() * 2)
209+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
210+
futures = [
211+
executor.submit(
212+
scan_path,
213+
"VulnScan/Model SenseMini .3n3.pth",
214+
path,
215+
"VulnScan/Vectorizer .3n3.pkl"
216+
)
217+
for path in paths
218+
]
219+
for future in futures:
220+
try:
221+
future.result()
222+
except Exception as e:
223+
log.error(f"Scan failed: {e}")

0 commit comments

Comments
 (0)