From 7af44900d388653a475d21efeceef6d84d35316d Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Mon, 27 Jun 2022 14:51:52 +0200 Subject: [PATCH] Type hinting followup --- README.md | 8 ++--- discordHelper.py | 4 +-- modules/agnostic_paths.py | 10 +++--- modules/main_runner.py | 72 +++++++++++++++++---------------------- modules/test_spidey.py | 12 +++---- modules/test_template.py | 14 ++++---- 6 files changed, 55 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index 6c59113..313b879 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,13 @@ A python script to detect whether your discord was tempered with in any noticeable way. ## Functionnement -DiscordHelper will provide a fast analysis over known malwares and progress it's analysis toward a complete sha1 checksum comparison against a known good install. +DiscordHelper will provide a fast analysis over known malwares and progress its analysis toward a complete sha1 checksum comparison against a known good installation. If the integrity can't be verified, the helper will propose to upload a new database with all computed data as a new staple to compare to (this functionnality is mostly useful if you have a custom/modded Discord). ### Windows -DiscordHelper is configured to run every tests and save the result in a folder named "DiscordHelper" in the same directory as the script. -This file, named test_results_found.json, contains a snapshot of your current install. If you change it's name to test_results.json, DiscordHelper will use this snapshot instead of the bundled databases. (This feature is mostly useful if you have a custom/modded Discord). +DiscordHelper is configured to run every test and save the result in a folder named "DiscordHelper" in the same directory as the script. +This file, named test_results_found.json, contains a snapshot of your current installation. If you change its name to test_results.json, DiscordHelper will use this snapshot instead of the bundled databases. (This feature is mostly useful if you have a custom/modded Discord). ### What to do if the integrity can't be verified? Open a new issue, upload the test_results_found.json file and any details surrounding the problem. @@ -17,7 +17,7 @@ Open a new issue, upload the test_results_found.json file and any details surrou If this isn't a bug in DiscordHelper, you may want to reinstall Discord, and possibly your whole operating system. # WARNING -Due to the evolutive nature of viruses, only a new, clean install of DiscordHelper will warranty a total detection of all threats, since a virus will always try to temper all methods of detecting it. +Due to the evolutive nature of viruses, only a new, clean installation of DiscordHelper will warranty a total detection of all threats, since a virus will always try to temper all methods of detecting it. # DISCLAMER While this program aims to provide a complete coverage over Discord Threats, there are many ways to temper with discord that cannot be covered in this program, mainly side-dll tempering and all forms of RAT and keyloggers. DiscordHelper cannot and will not try to analyse the rest of your operating system, we leave this intrusive behaviour to other anti-viruses. diff --git a/discordHelper.py b/discordHelper.py index 8858e2e..2297c9c 100644 --- a/discordHelper.py +++ b/discordHelper.py @@ -1,16 +1,16 @@ #!/usr/bin/python3 """ Main program """ +import argparse from modules import main_runner, agnostic_paths, argument_parser import sys -def main(argm): +def main(argm: argparse.Namespace): """ Main program :param argm: List of arguments - :type argm: argparse.Namespace """ agnostic_path = agnostic_paths.AgnosticPaths(argm) main_runner.run_check(argm, agnostic_path) diff --git a/modules/agnostic_paths.py b/modules/agnostic_paths.py index f00e945..eea756a 100644 --- a/modules/agnostic_paths.py +++ b/modules/agnostic_paths.py @@ -57,9 +57,9 @@ class AgnosticPaths: def _get_path(self) -> str: """ - Return the base path of the install, note that the self.main_path is not returned, + Return the base path of the installation, note that the self.main_path is not returned, and this method is meant to be used at init only - :return: Base path of the install (minus the version on Windows) + :return: Base path of the installation (minus the version on Windows) """ if self.force_path is not None: return self.force_path @@ -111,7 +111,7 @@ class AgnosticPaths: else: raise OSError("Can't find for version on your OS.") - def _update_path(self): + def _update_path(self) -> None: """ Update the main path with the version, if needed (windows & mac only) """ @@ -149,7 +149,7 @@ class AgnosticPaths: Tries to open the path /discord_path/args[0]/args[1].../args[n] :param args: The path of the file or directory as a list of parameters __call__("folder1", "folder2", ..., "foldern") :return: The path is it exists - :raises: FileNotFoundError if the path doesn't exists + :raises: FileNotFoundError if the path doesn't exist """ _path = os.path.join(self.main_path, *args) if not os.path.exists(_path): @@ -163,7 +163,7 @@ class AgnosticPaths: """ return self.main_path - def walk_all_files(self, *args : str) -> List[str]: + def walk_all_files(self, *args: str) -> List[str]: """ Walks all files in the given path :param args: The path diff --git a/modules/main_runner.py b/modules/main_runner.py index 08e7fae..0cfcd24 100644 --- a/modules/main_runner.py +++ b/modules/main_runner.py @@ -1,3 +1,4 @@ +import argparse import json import os import subprocess @@ -6,8 +7,10 @@ import importlib import threading import time from collections import deque +from typing import List from modules.internal_io import global_status, thread_parameters +from modules import agnostic_paths, internal_io """ All modules that can be tested @@ -70,15 +73,12 @@ LOGO = colored(r""" class TestRunner: - def __init__(self, args, agnpath, start_time): + def __init__(self, args: argparse.Namespace, agnpath: agnostic_paths.AgnosticPaths, start_time: float): """ Main spidey runner :param args: List of arguments - :type args: argparse.Namespace :param agnpath: The path to the discord folder - :type agnpath: agnostic_path.AgnosticPath :param start_time: The time the test started - :type start_time: float """ self.ptb = args.ptb self.args = args @@ -108,17 +108,17 @@ class TestRunner: self.open_base_data() self.exec_all_tests() - def update_threat(self, threat_level): + def update_threat(self, threat_level: int): """ Updates the threat level :param threat_level: The new threat level - :type threat_level: int """ self.threat_level = max(threat_level, self.threat_level) - def open_base_data(self): + def open_base_data(self) -> dict: """ Opens the base data file + :return: The base data (a json file) """ default_database = resource_path(self.agnostic_path.default_database) @@ -150,9 +150,10 @@ class TestRunner: self.base_data = {} return self.base_data - def check_database(self): # TODO: All of this can be refactored with a function + def check_database(self) -> bool: # TODO: All of this can be refactored with a function """ Check if the database is valid set self.bad_database to True if it is not + :return: True if the database is valid """ if not self.base_data: print(colored(" > The database is empty", "red")) @@ -206,11 +207,10 @@ class TestRunner: print(colored(f" > The database is missing the test {test_name}", "red")) self.bad_database = True - def update_module_list(self): + def update_module_list(self) -> List[str]: """ Gets the list of modules to be loaded (in accordance to the config) :return: List of modules - :rtype: list """ modules = {} classes = {} @@ -229,7 +229,7 @@ class TestRunner: self.loaded_test_modules.update(modules) self.loaded_test_classes.update(classes) - def exec_all_tests(self): + def exec_all_tests(self) -> None: """ Executes all the tests, get their result as they finishes """ @@ -268,7 +268,7 @@ class TestRunner: tc.daemon = True tc.start() - def controller_test(self): + def controller_test(self) -> None: """ Kills the tests if the user press enter """ @@ -289,7 +289,7 @@ class TestRunner: except Exception: sys.exit() - def post_test_runner(self): + def post_test_runner(self) -> None: """ Runs the post test runner if all tests are finished """ @@ -306,10 +306,9 @@ class TestRunner: time.sleep(0.1) return 0 - def test_waiter(self): + def test_waiter(self) -> None: """ Waits for the end of the tests - :return: """ for t in self.list_of_tests: # Can only proceed if all tests are finished t.join() @@ -320,11 +319,10 @@ class TestRunner: global POST_RUN_ALLOWED POST_RUN_ALLOWED = True - def get_exit_code(self): + def get_exit_code(self) -> int: # TODO: Use a NamedTuple """ Gets the exit code of the tests :return: The exit code - :rtype: int """ status = self.get_status() if status.tests_finished == status.tests_total: @@ -345,11 +343,10 @@ class TestRunner: exit_code = -1 # The tests are not finished return exit_code - def get_status(self): + def get_status(self) -> internal_io.global_status: """ Gets the status of the tests :return: The status - :rtype: internal_io.global_status """ queue_lock.acquire(timeout=0.5) nb_tests = len(self.list_of_tests) @@ -391,11 +388,10 @@ class TestRunner: progress=progress ) - def get_test_data(self): + def get_test_data(self) -> dict: """ Gets the test data :return: The test data - :rtype: dict """ data = {} queue_lock.acquire() @@ -409,13 +405,11 @@ class TestRunner: return data -def export_data(test_runner, data): +def export_data(test_runner: TestRunner, data: dict) -> dict: """ - Exports the test data + Exports the test data and returns it :param test_runner: The test runner - :type test_runner: TestRunner :param data: The test data - :type data: dict """ main_data = { "global": @@ -430,13 +424,11 @@ def export_data(test_runner, data): return main_data -def print_status(status, timer_start): +def print_status(status: internal_io.global_status, timer_start: float) -> None: """ Prints the status :param status: The status - :type status: internal_io.global_status :param timer_start: The start time of the tests - :type timer_start: float """ if status.tests_failed != 0: color = "red" @@ -461,7 +453,7 @@ def print_status(status, timer_start): else: mon, sec = divmod(ellapsed_time * 100 / status.progress, 60) hr, mon = divmod(mon, 60) - sec = round(sec, 0) +1 + sec = round(sec, 0) + 1 estimated_time = f"{hr:n}:{mon:02n}:{sec:02.0n}" print(colored( f" > Overall progress: {status.progress}%" @@ -470,12 +462,11 @@ def print_status(status, timer_start): )) -def run_check(args, agnpath): +def run_check(args: argparse.Namespace, agnpath: agnostic_paths.AgnosticPaths) -> None: """ Runs all operations selected in the config :param args: List of arguments :param agnpath: Annostic path to the discord folder - :return: None """ # Initialize the test runner print(LOGO) @@ -509,7 +500,7 @@ def run_check(args, agnpath): sys.exit(tr.get_exit_code()) -def resource_path(relative_path): +def resource_path(relative_path: str) -> str: """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS @@ -519,7 +510,7 @@ def resource_path(relative_path): return os.path.join(base_path, relative_path) -def print_final_status(testrunner, start_time, args): +def print_final_status(testrunner: TestRunner, start_time: float, args: argparse.Namespace) -> None: """ Prints the final status """ @@ -558,14 +549,15 @@ def print_final_status(testrunner, start_time, args): print(colored(f"\nThe program executed {msg_error}, exiting in {args.timeout} seconds...", color)) -def fill_it(size, string1, string2): +def fill_it(size: int, string1: str, string2: str) -> str: """ - Fills a string with a character + Makes a string with the format "string1......string2" + with as many "." as needed to fill the size """ return string1 + max(size - len(string1)-len(string2), 0) * "." + string2 -def at_max_elements(table, msize, fill): +def at_max_elements(table: list, msize: int, fill: str) -> list: """ Display at maximum msize elements, replace last with fill and return the table """ @@ -578,9 +570,9 @@ def at_max_elements(table, msize, fill): return table -def fit_it_under(message, size, start_line=""): +def fit_it_under(message: str, size: int, start_line: str = "") -> list: """ - Fits a message under a size + Fits a message under a size (split lines into multiple lines if needed) and returns the list of lines """ final_message = [] for line in message.split('\n'): @@ -592,9 +584,9 @@ def fit_it_under(message, size, start_line=""): return final_message -def gen_save_data(args, test_runner): +def gen_save_data(args: argparse.Namespace, test_runner: TestRunner) -> None: """ - Generates the save data + Generates the save data and writes it to a file """ print(colored("\n > Generating data...", "blue")) data = test_runner.get_test_data() diff --git a/modules/test_spidey.py b/modules/test_spidey.py index 8bd5799..aa13628 100644 --- a/modules/test_spidey.py +++ b/modules/test_spidey.py @@ -1,21 +1,20 @@ import os -from modules import test_template +from modules import test_template, internal_io class SpideyTest(test_template.TestTemplate): - def __init__(self, thread_parameters): + def __init__(self, thread_parameters: internal_io.thread_parameters): """ Simple test runner, for testing the detection of Spidey viruses. """ super().__init__(thread_parameters) - def run_test(self): + def run_test(self) -> str: """ Counts the number of lines in both index.js files. If it's more than one, it's almost certain your discord is corrupted. - :return: Whether any of the index.js is more than one line - :rtype: bool + :return: The status of the test as a string. """ self.set_status("running") @@ -52,11 +51,10 @@ class SpideyTest(test_template.TestTemplate): self.progress = 100 return self.finish("success", "Your discord is not infected.") - def get_path(self): + def get_path(self) -> str: """ Gets the path of the two folders we need to check :return: Two paths. - :rtype: str """ discord_modules = self.agnostic_path("modules", "discord_modules-1", "discord_modules") discord_desktop_core = self.agnostic_path("modules", "discord_desktop_core-1", "discord_desktop_core") diff --git a/modules/test_template.py b/modules/test_template.py index 75aa47f..b30a884 100644 --- a/modules/test_template.py +++ b/modules/test_template.py @@ -59,7 +59,7 @@ class TestTemplate: self.dict_process_lock.release() self.init_test_data() - def run(self): + def run(self) -> None: """ Runs the test. """ @@ -69,7 +69,7 @@ class TestTemplate: self.add_failure("problem", "DISCORD HELPER:"+str(e)) return self.finish("problem", str(e)) - def run_test(self): + def run_test(self) -> None: """ The main runner function, must be implemented by the child class. During the execution of the test, the status code and status MUST be updated. @@ -155,7 +155,7 @@ class TestTemplate: """ self.failure_dict[path] = message - def __del__(self): + def __del__(self) -> None: """ Destructor. """ @@ -195,7 +195,6 @@ class TestTemplate: :return: The value of the entry """ if self.test_data: - path = self.agnostic_path.get_short_path(entry) if "tests" in self.test_data: if entry in self.test_data["tests"]: if testname in self.test_data["tests"][entry]: @@ -211,7 +210,7 @@ class TestWalkTemplate(TestTemplate): super().__init__(thread_parameters) self.to_skip = [] - def run_test(self): + def run_test(self) -> str: """ The main runner function, must be implemented by the child class. Here is an example of how to use the add_test_result function. @@ -242,7 +241,7 @@ class TestWalkTemplate(TestTemplate): """ return self.agnostic_path.all_files - def add_test_result(self, path: str, testname: str, result: any) -> None: + def add_test_result(self, path: str, testname: str, result: any) -> any: """ Adds a test result to the data dictionary. :param path: Path to the file being tested @@ -271,7 +270,8 @@ class TestWalkTemplate(TestTemplate): return self.get_from_database(self.agnostic_path.get_short_path(path), testname) return None - def compare(self, path: agnostic_paths.AgnosticPaths, entry_name: str, function: Callable, args: list, kwargs: dict, cmp_function: Callable = None): + def compare(self, path: agnostic_paths.AgnosticPaths, entry_name: str, function: Callable, + args: list, kwargs: dict, cmp_function: Callable = None): """ Use the function on the given path, with given arguments and compare it with the entry in the test data. :param path: Path to the file or directory