Skip to content

Commit 6232110

Browse files
Incorporated most CodeRabbit [suggestions](#225 (review))
Removed 2 commands from bluetooth_logger.py to fix the bug where is just fails due to the event log not actually existing Fully remade packet_sniffer.py to remove the already buggy code and deprecation warnings Signed-off-by: Shahm Najeeb <Nirt_12023@outlook.com>
1 parent ab79f86 commit 6232110

19 files changed

Lines changed: 183 additions & 464 deletions

CODE/Logicytics.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import psutil
1313
from prettytable import PrettyTable
1414

15-
from logicytics import Log, Execute, Check, Get, FileManagement, Flag, DEBUG, DELETE_LOGS, config
15+
from logicytics import Log, execute, check, get, file_management, flag, DEBUG, DELETE_LOGS, config
1616

1717
# Initialization
1818
log = Log({"log_level": DEBUG, "delete_log": DELETE_LOGS})
@@ -66,7 +66,7 @@ def __generate_execution_list(self) -> list[str]:
6666
- Logs the final execution list for debugging purposes
6767
- Warns users about potential long execution times for certain actions
6868
"""
69-
execution_list = Get.list_of_files(".", only_extensions=(".py", ".exe", ".ps1", ".bat"),
69+
execution_list = get.list_of_files(".", only_extensions=(".py", ".exe", ".ps1", ".bat"),
7070
exclude_files=["Logicytics.py"],
7171
exclude_dirs=["logicytics", "SysInternal_Suite"])
7272
files_to_remove = {
@@ -101,7 +101,7 @@ def __generate_execution_list(self) -> list[str]:
101101

102102
elif ACTION == "modded":
103103
# Add all files in MODS to execution list
104-
execution_list = Get.list_of_files("../MODS", only_extensions=(".py", ".exe", ".ps1", ".bat"),
104+
execution_list = get.list_of_files("../MODS", only_extensions=(".py", ".exe", ".ps1", ".bat"),
105105
append_file_list=execution_list, exclude_files=["Logicytics.py"],
106106
exclude_dirs=["logicytics", "SysInternal_Suite"])
107107

@@ -144,7 +144,7 @@ def __script_handler(script: str) -> tuple[str, Exception | None]:
144144
"""
145145
log.debug(f"Executing {script}")
146146
try:
147-
log.execution(Execute.script(script))
147+
log.execution(execute.script(script))
148148
log.info(f"{script} executed successfully")
149149
return script, None
150150
except Exception as err:
@@ -207,7 +207,7 @@ def __performance(self):
207207
gc.collect()
208208
start_time = datetime.now()
209209
start_memory = process.memory_full_info().uss / 1024 / 1024 # MB
210-
log.execution(Execute.script(self.execution_list[file]))
210+
log.execution(execute.script(self.execution_list[file]))
211211
end_time = datetime.now()
212212
end_memory = process.memory_full_info().uss / 1024 / 1024 # MB
213213
elapsed_time = end_time - start_time
@@ -352,7 +352,7 @@ def get_flags():
352352
"""
353353
global ACTION, SUB_ACTION
354354
# Get flags_list
355-
ACTION, SUB_ACTION = Flag.data()
355+
ACTION, SUB_ACTION = flag.data()
356356
log.debug(f"Action: {ACTION}")
357357
log.debug(f"Sub-Action: {SUB_ACTION}")
358358

@@ -382,7 +382,7 @@ def handle_special_actions():
382382
log.info("Opening debug menu...")
383383
SpecialAction.execute_new_window("_debug.py")
384384

385-
messages = Check.sys_internal_zip()
385+
messages = check.sys_internal_zip()
386386
if messages:
387387
# If there are messages, log them with debug
388388
log.debug(messages)
@@ -407,7 +407,7 @@ def handle_special_actions():
407407
"Sorry, this feature is yet to be implemented. You can manually Restore your backups, We will open "
408408
"the location for you"
409409
)
410-
FileManagement.open_file("../ACCESS/BACKUP/")
410+
file_management.open_file("../ACCESS/BACKUP/")
411411
input("Press Enter to exit...")
412412
exit(1)
413413

@@ -438,7 +438,7 @@ def check_privileges():
438438
- Depends on global `DEBUG` configuration variable
439439
- Logs warnings or critical messages based on privilege and UAC status
440440
"""
441-
if not Check.admin():
441+
if not check.admin():
442442
if DEBUG == "DEBUG":
443443
log.warning("Running in debug mode, continuing without admin privileges - This may cause issues")
444444
else:
@@ -447,7 +447,7 @@ def check_privileges():
447447
input("Press Enter to exit...")
448448
exit(1)
449449

450-
if Check.uac():
450+
if check.uac():
451451
log.warning("UAC is enabled, this may cause issues - Please disable UAC if possible")
452452

453453

@@ -462,7 +462,7 @@ def files(cls):
462462
@staticmethod
463463
def __and_log(directory: str, name: str):
464464
log.debug(f"Zipping directory '{directory}' with name '{name}' under action '{ACTION}'")
465-
zip_values = FileManagement.Zip.and_hash(
465+
zip_values = file_management.Zip.and_hash(
466466
directory,
467467
name,
468468
ACTION if ACTION is not None else f"ERROR_NO_ACTION_SPECIFIED_{datetime.now().isoformat()}"
@@ -531,8 +531,8 @@ def Logicytics():
531531
Logicytics()
532532
except KeyboardInterrupt:
533533
log.warning("Force shutdown detected! Some temporary files might be left behind.")
534-
log.warning("Pro tip: Next time, let the program finish naturally.")
535-
# Attempt cleanup -> Zip generated files
534+
log.warning("Next time, let the program finish naturally for complete cleanup.")
535+
# Emergency cleanup - zip generated files
536536
ZIP.files()
537537
exit(0)
538538
else:

CODE/_debug.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import psutil
1010
import requests
1111

12-
from logicytics import Log, DEBUG, VERSION, Check, config
12+
from logicytics import Log, DEBUG, VERSION, check, config
1313

1414
log_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "ACCESS\\LOGS\\DEBUG\\DEBUG.log")
1515
log = Log({"log_level": DEBUG, "filename": log_path, "truncate_message": False, "delete_log": True})
@@ -206,15 +206,15 @@ def debug():
206206
SysInternalManager.check_binaries("SysInternal_Suite")
207207

208208
# System Checks
209-
log.info("Admin privileges found" if Check.admin() else "Admin privileges not found")
210-
log.info("UAC enabled" if Check.uac() else "UAC disabled")
209+
log.info("Admin privileges found" if check.admin() else "Admin privileges not found")
210+
log.info("UAC enabled" if check.uac() else "UAC disabled")
211211
log.info(f"Execution path: {psutil.__file__}")
212212
log.info(f"Global execution path: {sys.executable}")
213213
log.info(f"Local execution path: {sys.prefix}")
214214
log.info(
215215
"Running in a virtual environment" if sys.prefix != sys.base_prefix else "Not running in a virtual environment")
216216
log.info(
217-
"Execution policy is unrestricted" if Check.execution_policy() else "Execution policy is restricted")
217+
"Execution policy is unrestricted" if check.execution_policy() else "Execution policy is restricted")
218218

219219
# Python Version Check
220220
SystemInfoManager.python_version()

CODE/_dev.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import configobj
88

9-
from logicytics import log, Get, FileManagement, CURRENT_FILES, VERSION
9+
from logicytics import log, get, file_management, CURRENT_FILES, VERSION
1010

1111

1212
def color_print(text, color="reset", is_input=False) -> None | str:
@@ -21,9 +21,8 @@ def color_print(text, color="reset", is_input=False) -> None | str:
2121
color_code = colors.get(color.lower(), colors["reset"])
2222
if is_input:
2323
return input(f"{color_code}{text}{colors['reset']}")
24-
else:
25-
print(f"{color_code}{text}{colors['reset']}")
26-
return None
24+
print(f"{color_code}{text}{colors['reset']}")
25+
return None
2726

2827

2928
def _update_ini_file(filename: str, new_data: list | str, key: str) -> None:
@@ -118,7 +117,7 @@ def _handle_file_operations() -> None:
118117
Handles file operations and logging for added, removed, and normal files.
119118
"""
120119
EXCLUDE_FILES = ["logicytics\\User_History.json.gz", "logicytics\\User_History.json"]
121-
files = Get.list_of_files(".", exclude_files=EXCLUDE_FILES, exclude_dirs=["SysInternal_Suite"],
120+
files = get.list_of_files(".", exclude_files=EXCLUDE_FILES, exclude_dirs=["SysInternal_Suite"],
122121
exclude_extensions=[".pyc"])
123122
added_files, removed_files, normal_files = [], [], []
124123
clean_files_list = [file.replace('"', '') for file in CURRENT_FILES]
@@ -190,7 +189,7 @@ def dev_checks() -> None:
190189
- Updates configuration file with current files and version
191190
- Logs warnings or errors during the process
192191
"""
193-
FileManagement.mkdir()
192+
file_management.mkdir()
194193
if not _perform_checks():
195194
return
196195
_handle_file_operations()

CODE/bluetooth_details.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ def _write_device_info_to_file(devices: list[dict[str, str]], filename: str):
106106
with open(filename, "w", encoding="UTF-8") as file:
107107
for device_info in devices:
108108
_write_single_device_info(file, device_info)
109+
log.info(f"Successfully wrote device details to '{filename}'")
109110
except Exception as e:
110111
log.error(f"Failed to write device information to file: {e}")
111112

CODE/bluetooth_logger.py

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -169,41 +169,6 @@ def log_bluetooth():
169169
save_to_file(filename, section_title, paired_devices or ["No paired Bluetooth devices found."])
170170
log.debug(f"{section_title}: {paired_devices}")
171171

172-
# Collect and log event logs
173-
def collect_logs(title: str, command: str):
174-
"""
175-
Collects and logs event logs by executing a PowerShell command and saving the results.
176-
177-
Args:
178-
title (str): The title or description of the log section being collected.
179-
command (str): The PowerShell command to execute for retrieving event logs.
180-
181-
Behavior:
182-
- Runs the specified PowerShell command using `run_powershell_command()`
183-
- Saves the log results to a file using `save_to_file()`
184-
- Logs an informational message about the log collection
185-
- If no logs are found, saves a default "No logs found." message
186-
- Uses the global `filename` variable for log file destination
187-
188-
Raises:
189-
Potential exceptions from `run_powershell_command()` and `save_to_file()` which are handled internally
190-
"""
191-
logs = run_powershell_command(command)
192-
save_to_file(filename, title, logs or ["No logs found."])
193-
log.info(f"Getting {title}...")
194-
195-
collect_logs(
196-
"Bluetooth Connection/Disconnection Logs",
197-
'Get-WinEvent -LogName "Microsoft-Windows-Bluetooth-BthLEServices/Operational" '
198-
'| Select-Object TimeCreated, Id, Message | Format-Table -AutoSize'
199-
)
200-
201-
collect_logs(
202-
"Bluetooth File Transfer Logs",
203-
'Get-WinEvent -LogName "Microsoft-Windows-Bluetooth-BthLEServices/Operational" '
204-
'| Select-String -Pattern "file.*transferred" | Format-Table -AutoSize'
205-
)
206-
207172
log.info("Finished Bluetooth data logging.")
208173

209174

CODE/cmd_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from logicytics import log, Execute
1+
from logicytics import log, execute
22

33

44
@log.function
@@ -17,7 +17,7 @@ def command(file: str, commands: str, message: str, encoding: str = "UTF-8") ->
1717
"""
1818
log.info(f"Executing {message}")
1919
try:
20-
output = Execute.command(commands)
20+
output = execute.command(commands)
2121
with open(file, "w", encoding=encoding) as f:
2222
f.write(output)
2323
log.info(f"{message} Successful - {file}")

CODE/config.ini

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ save_preferences = true
2828
# Dev Mode allows a safe way to modify these settings!!
2929
version = 3.4.2
3030
files = "bluetooth_details.py, bluetooth_logger.py, browser_miner.ps1, cmd_commands.py, config.ini, dir_list.py, dump_memory.py, event_log.py, Logicytics.py, log_miner.py, media_backup.py, netadapter.ps1, network_psutil.py, packet_sniffer.py, property_scraper.ps1, registry.py, sensitive_data_miner.py, ssh_miner.py, sys_internal.py, tasklist.py, tree.ps1, vulnscan.py, wifi_stealer.py, window_feature_miner.ps1, wmic.py, logicytics\Checks.py, logicytics\Config.py, logicytics\Execute.py, logicytics\FileManagement.py, logicytics\Flag.py, logicytics\Get.py, logicytics\Logger.py, logicytics\User_History.json.gz, VulnScan\Model SenseMini .3n3.pth, VulnScan\README.md, VulnScan\Vectorizer .3n3.pkl"
31+
# If you forked the project, change the USERNAME to your own to use your own fork as update material,
32+
# I dont advise doing this however
3133
config_url = https://raw.githubusercontent.com/DefinetlyNotAI/Logicytics/main/CODE/config.ini
3234

3335
########################################################
@@ -100,6 +102,7 @@ max_retry_time = 30
100102
###################################################
101103
[VulnScan Settings]
102104
# Following extensions to be skipped by the model
105+
# Format: comma-separated list with dots (e.g., .exe, .dll)
103106
unreadable_extensions = .exe, .dll, .so, .zip, .tar, .gz, .7z, .rar, .jpg, .jpeg, .png, .gif, .bmp, .tiff, .webp, .mp3, .wav, .flac, .aac, .ogg, .mp4, .mkv, .avi, .mov, .wmv, .flv, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .odt, .ods, .odp, .bin, .dat, .iso, .class, .pyc, .o, .obj, .sqlite, .db, .ttf, .otf, .woff, .woff2, .lnk, .url
104107
# In MB, max file size that the model is allowed to scan, if commented out disables the limit, you can also just say None
105108
max_file_size_mb = None

CODE/dir_list.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
22
from concurrent.futures import ThreadPoolExecutor
33

4-
from logicytics import log, Execute
4+
from logicytics import log, execute
55

66

77
def run_command_threaded(directory: str, file: str, message: str, encoding: str = "UTF-8") -> None:
@@ -26,7 +26,7 @@ def run_command_threaded(directory: str, file: str, message: str, encoding: str
2626
try:
2727
safe_directory = directory.replace('"', '`"') # Escape quotes
2828
command = f'powershell -NoProfile -Command "Get-ChildItem \\""{safe_directory}\\"" -Recurse"'
29-
output = Execute.command(command)
29+
output = execute.command(command)
3030
open(file, "a", encoding=encoding).write(output)
3131
log.info(f"{message} Successful for {directory} - {file}")
3232
except Exception as e:

CODE/dump_memory.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,18 @@
44
from datetime import datetime
55

66
import psutil
7-
from psutil._common import sswap
87

98
from logicytics import log, config
109

1110
# Constants from config with validation
1211
LIMIT_FILE_SIZE = config.getint("DumpMemory Settings", "file_size_limit") # MiB
1312
SAFETY_MARGIN = config.getfloat("DumpMemory Settings", "file_size_safety") # MiB
13+
DUMP_DIR = config.get("DumpMemory Settings", "dump_directory", fallback="memory_dumps")
1414

1515
if SAFETY_MARGIN < 1:
1616
log.critical("Invalid Safety Margin Inputted - Cannot proceed with dump memory")
1717
exit(1)
1818

19-
DUMP_DIR = config.get("DumpMemory Settings", "dump_directory", fallback="memory_dumps")
20-
os.makedirs(DUMP_DIR, exist_ok=True)
21-
2219

2320
def capture_ram_snapshot():
2421
"""
@@ -41,7 +38,7 @@ def capture_ram_snapshot():
4138
Exception: For any unexpected errors during memory snapshot capture
4239
"""
4340

44-
def memory_helper(mem_var: psutil.svmem | sswap, flavor_text: str, use_free_rather_than_available: bool = False):
41+
def memory_helper(mem_var, flavor_text: str, use_free_rather_than_available: bool = False):
4542
file.write(f"Total {flavor_text}: {mem_var.total / (1024 ** 3):.2f} GB\n")
4643
file.write(f"Used {flavor_text}: {mem_var.used / (1024 ** 3):.2f} GB\n")
4744
if use_free_rather_than_available:
@@ -54,7 +51,7 @@ def memory_helper(mem_var: psutil.svmem | sswap, flavor_text: str, use_free_rath
5451
try:
5552
memory = psutil.virtual_memory()
5653
swap = psutil.swap_memory()
57-
with open(os.path.join(DUMP_DIR, "Ram_Snapshot.txt"), "w") as file:
54+
with open(os.path.join(DUMP_DIR, "Ram_Snapshot.txt"), "w", encoding="utf-8") as file:
5855
memory_helper(memory, "RAM")
5956
memory_helper(swap, "Swap Memory", use_free_rather_than_available=True)
6057
except Exception as e:

CODE/logicytics/Config.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ def _config_path() -> str:
2626

2727
if os.path.exists(configs_path):
2828
return configs_path
29-
else:
30-
exit("The config.ini file is not found in the expected location.")
29+
exit("The config.ini file is not found in the expected location.")
3130

3231
config_local = configparser.ConfigParser()
3332
path = _config_path()

0 commit comments

Comments
 (0)