Skip to content

Commit

Permalink
Codefactor vuln fixes (#111)
Browse files Browse the repository at this point in the history
## Pull Request Template

### Prerequisites

<!-- Take a couple of minutes to help our maintainers work faster by
checking of the pre-requisites. -->
<!-- To tick the checkboxes replace the space with an 'x', so [ ]
becomes [x] . -->

- [x] I have
[searched](https://github.com/DefinetlyNotAI/Logicytics/pulls) for
duplicate or closed issues.
- [x] I have read the [contributing
guidelines](https://github.com/DefinetlyNotAI/Logicytics/blob/main/CONTRIBUTING.md).
- [x] I have followed the instructions in the
[wiki](https://github.com/DefinetlyNotAI/Logicytics/wiki) about
contributions.
- [x] I have updated the documentation accordingly, if required.
- [x] I have added tests to cover my changes, and they have passed, if
required.
- [x] I have tested my code with the `--dev` flag, if required.

### PR Type

<!-- Take a couple of minutes to help our maintainers work faster by
telling us what is the PR guided on. -->
<!-- To tick the checkboxes replace the space with an 'x', so [ ]
becomes [x] . -->

- [x] Bug fix <!-- Non-Breaking Bug Fix - Usually relates to fixing an
issue -->
- [x] New feature <!-- Non-Breaking Change that adds a new feature -->
- [x] Refactoring <!-- Non-Breaking Change that modifies existing code
to refactor it to become more organised -->
- [x] Documentation
update <!-- Non-Breaking Change that modifies existing documentation to
refactor it or add extra comments - either wiki, md files or code is
included here -->
- [x] ⚠️ Breaking change ⚠️ <!-- Breaking Bug Fix / New Addition that
changes how Logicytics works -->

### Description

HUGE update for 2.3.0 -> Added 1 feature, fixed and tracked 12+ bugs AND
made development easier,

### Motivation and Context

Why not, I was bored lol

### Binaries

Not now, I will later attach

### Issues Fixed

#107
  • Loading branch information
DefinetlyNotAI committed Sep 21, 2024
2 parents 89d4bfa + 23cf375 commit 81b6214
Show file tree
Hide file tree
Showing 27 changed files with 151 additions and 288 deletions.
1 change: 1 addition & 0 deletions .github/workflows/powershell.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ permissions:

jobs:
build:
# noinspection GrazieInspection
permissions:
contents: read # for actions/checkout to fetch code
security-events: write # for github/codeql-action/upload-sarif to upload SARIF results
Expand Down
32 changes: 10 additions & 22 deletions CODE/Logicytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,6 @@
from __lib_class import *

log = Log(debug=DEBUG)
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


"""
Expand Down Expand Up @@ -61,8 +54,10 @@
check_status.sys_internal_zip()

if action == "dev":
Execute().execute_script("_dev.py")
input("Press Enter to exit...")
current_dir = os.path.dirname(os.path.abspath(__file__))
script_path = os.path.join(current_dir, "_dev.py")
process = subprocess.Popen(["cmd.exe", "/c", "start", "python", script_path])
process.wait()
exit(0)

if action == "extra":
Expand Down Expand Up @@ -114,7 +109,7 @@

# Check for privileges and errors
if not check_status.admin():
log.critical("Please run this script with admin privileges", "_L", "P", "BA")
log.critical("Please run this script with admin privileges")
if not DEBUG:
input("Press Enter to exit...")
exit(1)
Expand Down Expand Up @@ -195,8 +190,7 @@

# Zip generated files
if action == "modded":

zip_loc_mod, hash_loc, deleted_files_zip, deleted_files_hash = zip_and_hash("..\\MODS", "MODS", action)
zip_loc_mod, hash_loc = Zip().and_hash("..\\MODS", "MODS", action)
log.info(zip_loc_mod)
zip_values = Zip().and_hash("..\\MODS", "MODS", action)
if isinstance(zip_values, str):
Expand All @@ -214,29 +208,23 @@
zip_loc, hash_loc = zip_values
log.info(zip_loc)
log.debug(hash_loc)
log.debug(deleted_files_zip)
log.debug(deleted_files_hash)

zip_loc, hash_loc, deleted_files_zip, deleted_files_hash = zip_and_hash("..\\CODE", "CODE", action)
log.info(zip_loc)
log.debug(hash_loc)
log.debug(deleted_files_zip)
log.debug(deleted_files_hash)

# Attempt event log deletion
attempt_hide()

# Finish with sub actions
log.info("Completed successfully")
if sub_action == "shutdown":
log.info("Shutting down...")
log.info("Shutting down in 3 seconds...")
subprocess.call("shutdown /s /t 3", shell=False)
if sub_action == "reboot":
log.info("Rebooting...")
log.info("Rebooting in 3 seconds...")
subprocess.call("shutdown /r /t 3", shell=False)
if sub_action == "webhook":
# Implement this in future
log.warning("This feature is not fully implemented yet! Sorry")

log.info("Exiting...")
input("Press Enter to exit...")
# Special feature that allows to create a `-` line only
log.debug("*-*")
35 changes: 16 additions & 19 deletions CODE/__lib_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,21 @@

class Actions:
@staticmethod
def open_file(file: str):
def open_file(file: str, use_full_path=False):
"""
Opens a specified file using its default application in a cross-platform manner.
Args:
file (str): The path to the file to be opened.
use_full_path (bool): Whether to use the full path of the file or not.
Returns:
None
"""
if not file == "":
file_path = os.path.realpath(file)
if use_full_path:
current_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_dir, file)
else:
file_path = os.path.realpath(file)
try:
subprocess.call(file_path, shell=False)
except Exception as e:
Expand Down Expand Up @@ -348,7 +353,7 @@ def sys_internal_zip():
zip_ref.extractall("SysInternal_Suite")

elif ignore_file:
print(
Log(debug=DEBUG).debug(
"Found .sys.ignore file, skipping SysInternal_Suite zip extraction"
)

Expand Down Expand Up @@ -420,7 +425,7 @@ def __unblock_ps1_script(script: str):
subprocess.run(unblock_command, shell=False, check=True)
Log().info("PS1 Script unblocked.")
except Exception as err:
Log().critical(f"Failed to unblock script: {err}", "_L", "G", "E")
Log().critical(f"Failed to unblock script: {err}")

@staticmethod
def __run_python_script(script: str):
Expand All @@ -445,22 +450,14 @@ def __run_other_script(script: str):
Returns:
None
"""
result = subprocess.Popen(
["powershell.exe", ".\\" + script], stdout=subprocess.PIPE
).communicate()[0]
lines = result.decode().splitlines()
ID = next((line.split(":")[0].strip() for line in lines if ":" in line), None)

log_funcs = {
"INFO": Log().info,
"WARNING": Log().warning,
"ERROR": Log().error,
"CRITICAL": Log().critical,
None: Log().debug,
}

log_func = log_funcs.get(ID, Log().debug)
log_func("\n".join(lines).removeprefix(ID or ""))
result = subprocess.run(
["powershell.exe", ".\\" + script], capture_output=True, text=True
)
lines = result.stdout.splitlines()
ID = next((line.split(":")[0].strip() for line in lines if ":" in line), None)
if ID:
Log().string(str(lines), ID)


WEBHOOK, DEBUG, VERSION, API_KEY, CURRENT_FILES = Actions.read_config()
35 changes: 27 additions & 8 deletions CODE/__lib_log.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
import pathlib
from datetime import datetime
Expand Down Expand Up @@ -153,8 +155,11 @@ def debug(self, message):
Returns:
None
"""
if self.level:
colorlog.debug(message)
if message == "*-*":
self.__only("|" + "-" * 19 + "|" + "-" * 13 + "|" + "-" * 152 + "|")
else:
if self.level:
colorlog.debug(message)

def info(self, message):
"""
Expand Down Expand Up @@ -207,23 +212,37 @@ def error(self, message):
f"[{self.__timestamp()}] > ERROR: | {self.__pad_message(str(message))}\n"
)

def critical(self, message, FILECODE: str, ERRCODE: str, FUNCODE: str):
def critical(self, message):
"""
Logs a critical message to the error log File.
Args:
message: The critical message to be logged.
FILECODE: The File code associated with the critical message.
ERRCODE: The error code associated with the critical message.
FUNCODE: The function code associated with the critical message.
Returns:
None
"""
if self.color:
colorlog.critical(message)
with open(self.err_filename, "a") as f:
code = str(FILECODE) + ":" + str(ERRCODE) + ":" + str(FUNCODE)
f.write(
f"[{self.__timestamp()}] > CRITICAL: | {self.__pad_message(str(message) + ' --> ' + code)}\n"
f"[{self.__timestamp()}] > CRITICAL: | {self.__pad_message(str(message))}\n"
)

def string(self, Message: str, Type="Debug"):
"""
Uses the string given to log the message using the correspondent log type,
defaults to 'log.debug' if no log type is given.
Args:
Type: The string message to be used to replace XXX in 'log.XXX'.
Message: The message to be logged.
Returns:
None
"""
try:
getattr(self, Type.lower())(Message)
except AttributeError as AE:
self.warning(f"A wrong Log Type was called: {Type} not found. -> {AE}")
getattr(self, "Debug".lower())(Message)
30 changes: 12 additions & 18 deletions CODE/_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,11 @@

if __name__ == "__main__":
log_debug = Log(debug=DEBUG, filename="../ACCESS/LOGS/DEBUG/DEBUG.LOG")
log_debug_funcs = {
"INFO": log_debug.info,
"WARNING": log_debug.warning,
"ERROR": log_debug.error,
"CRITICAL": log_debug.critical,
None: log_debug.debug,
}


class HealthCheck:
def get_online_config(
self,
self,
) -> bool | tuple[tuple[str, str, str], tuple[str, str, str]]:
"""
Retrieves configuration data from a remote repository and compares it with the local configuration.
Expand All @@ -41,7 +34,7 @@ def get_online_config(

@staticmethod
def __compare_versions(
local_version: str, remote_version: str
local_version: str, remote_version: str
) -> tuple[str, str, str]:
"""
Compares the local version with the remote version and returns a tuple containing a comparison result message,
Expand Down Expand Up @@ -121,11 +114,11 @@ def SysInternal_Binaries(path: str) -> tuple[str, str]:
if any(file.endswith(".ignore") for file in contents):
return "A `.sys.ignore` file was found - Ignoring", "WARNING"
if any(file.endswith(".zip") for file in contents) and not any(
file.endswith(".exe") for file in contents
file.endswith(".exe") for file in contents
):
return "Only zip files - Missing EXE's due to no `ignore` file", "ERROR"
elif any(file.endswith(".zip") for file in contents) and any(
file.endswith(".exe") for file in contents
file.endswith(".exe") for file in contents
):
return "Both zip and exe files - All good", "INFO"
else:
Expand Down Expand Up @@ -199,14 +192,12 @@ def debug():
# Check File integrity (Online)
if HealthCheck().get_online_config():
version_tuple, file_tuple = HealthCheck().get_online_config()
log_debug_funcs.get(version_tuple[2], log_debug.debug)(
"\n".join(version_tuple[0]).replace("\n", "")
)
log_debug_funcs.get(file_tuple[2], log_debug.debug)(
"\n".join(file_tuple[0]).replace("\n", "")
log_debug.string(
"\n".join(version_tuple[0]).replace("\n", ""), version_tuple[2]
)
log_debug.string("\n".join(file_tuple[0]).replace("\n", ""), file_tuple[2])
message, type = DebugCheck.SysInternal_Binaries("SysInternal_Suite")
log_debug_funcs.get(type, log_debug.debug)("\n".join(message).replace("\n", ""))
log_debug.string("\n".join(message).replace("\n", ""), type)

# Check Admin
if Check().admin():
Expand Down Expand Up @@ -252,4 +243,7 @@ def debug():
log_debug.info(cpuModel)

# Get config data
log_debug.info("Debug: " + DEBUG)
log_debug.info(f"Debug: {DEBUG}")


debug()
3 changes: 2 additions & 1 deletion CODE/_dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def __update_json_file(filename: str, new_data: list | str, key: str) -> None:
data = json.load(f)
data[key] = new_data
f.seek(0)
# noinspection PyTypeChecker
json.dump(data, f, indent=4)
f.truncate()
except FileNotFoundError:
Expand All @@ -42,7 +43,7 @@ def __prompt_user(question: str, file_to_open: str = None) -> bool:
answer = input(question + " (yes or no):- ")
if answer.lower() != "yes":
if file_to_open:
Actions().open_file(file_to_open)
subprocess.run(["start", file_to_open], shell=True)
print(
"Please ensure you fix the issues/problem and try again with the checklist."
)
Expand Down
7 changes: 0 additions & 7 deletions CODE/_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,6 @@

if __name__ == "__main__":
log = Log(debug=DEBUG, filename="../ACCESS/LOGS/DEBUG/DEBUG.LOG")
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


def unzip(zip_path: str):
Expand Down
7 changes: 0 additions & 7 deletions CODE/driverquery+sysinfo.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
from __lib_class import *

log = Log(debug=DEBUG)
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


def command(file: str, com: str, message: str):
Expand Down
7 changes: 0 additions & 7 deletions CODE/log_miner.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
from __lib_class import *

log = Log(debug=DEBUG)
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


def backup_windows_logs():
Expand Down
7 changes: 0 additions & 7 deletions CODE/media_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@
from __lib_class import *

log = Log(debug=DEBUG)
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


class Media:
Expand Down
7 changes: 0 additions & 7 deletions CODE/online_ip_scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@
from __lib_class import *

log = Log(debug=DEBUG)
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


class Scrape:
Expand Down
7 changes: 0 additions & 7 deletions CODE/registry.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
from __lib_class import *

log = Log(debug=DEBUG)
log_funcs = {
"INFO": log.info,
"WARNING": log.warning,
"ERROR": log.error,
"CRITICAL": log.critical,
None: log.debug,
}


def backup_registry():
Expand Down
Loading

0 comments on commit 81b6214

Please sign in to comment.