Merge pull request #29 from idle-org/features/middleground
Features/middleground
This commit is contained in:
commit
724a054f14
|
|
@ -13,7 +13,7 @@ def main(argm):
|
|||
:type argm: argparse.Namespace
|
||||
"""
|
||||
agnostic_path = agnostic_paths.AgnosticPaths(argm)
|
||||
test_runner = main_runner.run_check(argm, agnostic_path)
|
||||
main_runner.run_check(argm, agnostic_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import discordHelper
|
|||
import time
|
||||
|
||||
# All modules must be loaded before the main program is run.
|
||||
from modules import spidey_test, test_template
|
||||
from modules import spidey_test, test_template # noqa # Set for pyinstaller
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
|
|
@ -26,7 +26,7 @@ if __name__ == "__main__":
|
|||
|
||||
# Will always try to load discordHelper/discordHelper.json
|
||||
run_db = os.path.join(directory_path, "test_results_found.json")
|
||||
argv = rf"--all --autodetect --launch --continue --timeout 10 {db_path}--gen-data {run_db} --db discordHelper/test_results.json".split(" ")
|
||||
argv = rf"--all --autodetect --launch --continue --timeout 25 {db_path}--gen-data {run_db} --db discordHelper/test_results.json".split(" ") # noqa E501
|
||||
# print(" > Starting the discordHelper with the following arguments:")
|
||||
# print(" > " + " ".join(argv))
|
||||
|
||||
|
|
@ -34,7 +34,7 @@ if __name__ == "__main__":
|
|||
|
||||
discordHelper.main(args)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print("Error: " + str(e))
|
||||
print(" > An error occured, please check the console for more information...")
|
||||
time.sleep(5)
|
||||
raise SystemExit
|
||||
|
|
|
|||
|
|
@ -20,11 +20,11 @@ def apply_adler(path):
|
|||
|
||||
|
||||
class AdlerTest(test_template.TestWalkTemplateNoLogs):
|
||||
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
|
||||
def __init__(self, thread_parameters):
|
||||
"""
|
||||
Simple test runner, compare adler32 to known good values.
|
||||
"""
|
||||
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
|
||||
super().__init__(thread_parameters)
|
||||
|
||||
def run_test(self):
|
||||
self.set_status("running")
|
||||
|
|
@ -39,9 +39,22 @@ class AdlerTest(test_template.TestWalkTemplateNoLogs):
|
|||
self.add_failure(path, f"Test {self.name()} failed on {short_path}")
|
||||
error_msg += f"{short_path} is " \
|
||||
f"({res}) not ({self.get_expected_result(path, 'adler32')} b).\n"
|
||||
self.is_infected = True
|
||||
if not self.args.continue_on_error:
|
||||
return self.finish("failure", f"{short_path} is supposed to be {self.get_expected_result(path, 'adler32')} bytes, but it is {adler32(open(path, 'rb').read())} bytes.")
|
||||
if not self.bad_database:
|
||||
self.is_infected = True
|
||||
if not self.args.continue_on_error:
|
||||
return self.finish(
|
||||
"failure",
|
||||
f"{short_path} is supposed to be {self.get_expected_result(path, 'adler32')} "
|
||||
f"bytes, but it is {adler32(open(path, 'rb').read())} bytes."
|
||||
)
|
||||
else:
|
||||
self.is_unknown = True
|
||||
if not self.args.continue_on_error:
|
||||
return self.finish(
|
||||
"problem",
|
||||
f"{short_path} is supposed to be {self.get_expected_result(path, 'adler32')} "
|
||||
f"bytes, but it is {adler32(open(path, 'rb').read())} bytes."
|
||||
)
|
||||
|
||||
self.progress = 100
|
||||
if self.is_infected:
|
||||
|
|
@ -49,4 +62,9 @@ class AdlerTest(test_template.TestWalkTemplateNoLogs):
|
|||
"failure",
|
||||
error_msg
|
||||
)
|
||||
return self.finish("success", "Your discord is not infected.")
|
||||
elif self.is_unknown:
|
||||
return self.finish(
|
||||
"problem",
|
||||
error_msg
|
||||
)
|
||||
return self.finish("success", "Your discord is not infected.")
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ The agnostic path handler, gives all methods to access all paths of the discord
|
|||
import os
|
||||
import re
|
||||
import sys
|
||||
import random
|
||||
|
||||
|
||||
class AgnosticPaths:
|
||||
"""
|
||||
An agnostic path object, containing all methods to access the files and folders in a standard discord install
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, args):
|
||||
"""
|
||||
:param args: The arguments passed to the script
|
||||
|
|
@ -27,6 +28,9 @@ class AgnosticPaths:
|
|||
self.main_path = self._get_path()
|
||||
self.version = self.get_version()
|
||||
self._update_path()
|
||||
self.all_files = self.walk_all_files()
|
||||
random.shuffle(self.all_files)
|
||||
self.size = len(self.all_files)
|
||||
|
||||
def get_os(self):
|
||||
"""
|
||||
|
|
@ -36,7 +40,6 @@ class AgnosticPaths:
|
|||
:return: ("windows", "linux", "mac")
|
||||
:rtype: str
|
||||
"""
|
||||
|
||||
platform = sys.platform
|
||||
if platform.startswith('win'):
|
||||
self.os = 'windows'
|
||||
|
|
@ -61,7 +64,7 @@ class AgnosticPaths:
|
|||
if self.force_path is not None:
|
||||
return self.force_path
|
||||
if self.os == 'windows':
|
||||
base_path = os.path.join(os.path.expanduser('~'), "AppData", "Local", f"Discord")
|
||||
base_path = os.path.join(os.path.expanduser('~'), "AppData", "Local", "Discord")
|
||||
ptb_path = base_path+"PTB"
|
||||
if self.args.autodetect:
|
||||
if os.path.exists(ptb_path):
|
||||
|
|
@ -87,7 +90,7 @@ class AgnosticPaths:
|
|||
|
||||
def get_version(self):
|
||||
"""
|
||||
Looks for the version file in the discord folder
|
||||
Looks for the version file in the discord folder
|
||||
and return the latest version of the discord build
|
||||
:return: The version build
|
||||
:rtype: str
|
||||
|
|
@ -121,7 +124,7 @@ class AgnosticPaths:
|
|||
Lists all files in the path /discord_path/args[0]/args[1].../args[n]
|
||||
:param args: The path as a list of parameters list("folder1", "folder2", ..., "foldern")
|
||||
:type args: str
|
||||
:return: The list of all files and folders in the given path
|
||||
:return: The list of all files and folders in the given path
|
||||
:rtype: list[str]
|
||||
"""
|
||||
return os.listdir(self(*args))
|
||||
|
|
@ -155,7 +158,7 @@ class AgnosticPaths:
|
|||
if not os.path.exists(_path):
|
||||
raise FileNotFoundError(f"Could not find {_path}")
|
||||
return _path
|
||||
|
||||
|
||||
def get_path(self):
|
||||
"""
|
||||
The main path of the discord install
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ def parse(_args):
|
|||
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
|
||||
parser.add_argument('-d', '--debug', action='store_true', help='Debug mode')
|
||||
parser.add_argument('-s', '--silent', action='store_true', help='Silent mode')
|
||||
parser.add_argument("--continue_on_error", "--continue", action="store_true", help="Continue the analysis in case of failure")
|
||||
parser.add_argument("--continue_on_error", "--continue",
|
||||
action="store_true", help="Continue the analysis in case of failure")
|
||||
parser.add_argument("--timeout", default=1, type=int, help="Timeout for the tests")
|
||||
|
||||
# Post actions
|
||||
|
|
@ -40,10 +41,12 @@ def parse(_args):
|
|||
parser.add_argument('--file-name', action='store_true', help="Test the name of the files in the discord folder")
|
||||
parser.add_argument('--file-extension', action='store_true', help="Test the extension of the files in the discord folder")
|
||||
parser.add_argument('--file-date', action='store_true', help="Test the date of the files in the discord folder")
|
||||
parser.add_argument('--analyze', action='store_true', help="Analyze the files in the discord folder for known js obfuscators")
|
||||
parser.add_argument('--analyze', action='store_true',
|
||||
help="Analyze the files in the discord folder for known js obfuscators")
|
||||
parser.add_argument('--all', action='store_true', help="Run all tests in parallel, and wait for a potential interupt")
|
||||
parser.add_argument("--no-eval", action="store_true", help="Check for the eval function wich is a HUGE red flag")
|
||||
parser.add_argument("--const-abuse", "--no-const", action="store_true", help="Check for the abuse of the const: keyword, wich is massively used for obfucation")
|
||||
parser.add_argument("--const-abuse", "--no-const", action="store_true",
|
||||
help="Check for the abuse of the const: keyword, wich is massively used for obfucation")
|
||||
parser.add_argument("--test-walk", action="store_true", help="Test walk function")
|
||||
parser.add_argument("--max-errors", default=5, type=int, help="Maximum number of errors before the analysis is stopped")
|
||||
|
||||
|
|
|
|||
|
|
@ -22,3 +22,9 @@ return_code_dict = {
|
|||
"problems": "Test found problems",
|
||||
"idle": "Test is idle",
|
||||
}
|
||||
|
||||
thread_parameters = namedtuple(
|
||||
'thread_parameters',
|
||||
'args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock, bad_database',
|
||||
defaults=(None, None, None, None, None, None, None, None)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import threading
|
|||
import time
|
||||
from collections import deque
|
||||
|
||||
from modules.internal_io import global_status
|
||||
from modules.internal_io import global_status, thread_parameters
|
||||
from modules import size_test, adler_test # noqa # Used to force import of modules by pyinstaller
|
||||
|
||||
"""
|
||||
|
|
@ -34,16 +34,16 @@ queue_lock = threading.Lock()
|
|||
processes_lock = threading.Lock()
|
||||
|
||||
CLEAR_CODE = colored(r"""
|
||||
_______ _
|
||||
(_______) |
|
||||
_ | | _____ _____ ____
|
||||
_______ _
|
||||
(_______) |
|
||||
_ | | _____ _____ ____
|
||||
| | | || ___ (____ |/ ___)
|
||||
| |_____| || ____/ ___ | |
|
||||
| |_____| || ____/ ___ | |
|
||||
\______)\_)_____)_____|_|
|
||||
""", 'green')
|
||||
|
||||
INFECTED_CODE = colored(r"""
|
||||
_ ___ _
|
||||
_ ___ _
|
||||
| | / __) _ | |
|
||||
| |____ _| |__ _____ ____ _| |_ _____ __| |
|
||||
| | _ (_ __) ___ |/ ___|_ _) ___ |/ _ |
|
||||
|
|
@ -51,12 +51,21 @@ INFECTED_CODE = colored(r"""
|
|||
|_|_| |_||_| |_____)\____) \__)_____)\____|
|
||||
""", 'red')
|
||||
|
||||
UNKNOWN_CODE = colored(r"""
|
||||
_ _ _
|
||||
(_) (_) | |
|
||||
_ _ ____ | | _ ____ ___ _ _ _ ____
|
||||
| | | | _ \| |_/ ) _ \ / _ \| | | | _ \
|
||||
| |___| | | | | _ (| | | | |_| | | | | | | |
|
||||
\_____/|_| |_|_| \_)_| |_|\___/ \___/|_| |_|
|
||||
""", 'yellow')
|
||||
|
||||
LOGO = colored(r"""
|
||||
__ \ _) | | | |
|
||||
| | | __| __| _ \ __| _` | | | _ \ | __ \ _ \ __|
|
||||
| | | \__ \ ( ( | | ( | ___ | __/ | | | __/ |
|
||||
____/ _| ____/ \___| \___/ _| \__,_| _| _| \___| _| .__/ \___| _|
|
||||
_|
|
||||
__ \ _) | | | |
|
||||
| | | __| __| _ \ __| _` | | | _ \ | __ \ _ \ __|
|
||||
| | | \__ \ ( ( | | ( | ___ | __/ | | | __/ |
|
||||
____/ _| ____/ \___| \___/ _| \__,_| _| _| \___| _| .__/ \___| _|
|
||||
_|
|
||||
""", "cyan")
|
||||
|
||||
|
||||
|
|
@ -79,8 +88,11 @@ class TestRunner:
|
|||
self.version = agnpath.version
|
||||
self.start_time = start_time
|
||||
|
||||
self.is_infected = 0
|
||||
self.detections = 0
|
||||
self.is_infected = 0 # Only set to 1 if the certainty is high enough
|
||||
self.is_unknown = 0 # Unknown if the file is infected or not
|
||||
self.threat_level = 0 # The threat level of the infection, 0 is the lowest, can only be increased
|
||||
self.errors = 0
|
||||
self.bad_database = False # Set to true if the database is not valid
|
||||
self.test_run = {}
|
||||
|
||||
self.loaded_test_modules = {}
|
||||
|
|
@ -95,6 +107,14 @@ class TestRunner:
|
|||
self.open_base_data()
|
||||
self.exec_all_tests()
|
||||
|
||||
def update_threat(self, threat_level):
|
||||
"""
|
||||
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):
|
||||
"""
|
||||
Opens the base data file
|
||||
|
|
@ -108,6 +128,7 @@ class TestRunner:
|
|||
print(colored(f" > Opening specified database {self.args.database}", "green")) # TODO : Only if verbose
|
||||
with open(self.args.database, "r") as f:
|
||||
self.base_data = json.load(f)
|
||||
self.check_database()
|
||||
return self.base_data
|
||||
elif os.path.exists(resource_path(default_database)): # Try opening the default database
|
||||
print(colored(
|
||||
|
|
@ -116,6 +137,7 @@ class TestRunner:
|
|||
))
|
||||
with open(resource_path(default_database), "r") as f:
|
||||
self.base_data = json.load(f)
|
||||
self.check_database()
|
||||
return self.base_data
|
||||
|
||||
else:
|
||||
|
|
@ -123,9 +145,56 @@ class TestRunner:
|
|||
"\n > The database file does not exist, and the default "
|
||||
"one for your os does not exist either.\n", "red"
|
||||
))
|
||||
self.bad_database = True
|
||||
self.base_data = {}
|
||||
return self.base_data
|
||||
|
||||
def check_database(self):
|
||||
"""
|
||||
Check if the database is valid set self.bad_database to True if it is not
|
||||
"""
|
||||
if not self.base_data:
|
||||
print(colored(" > The database is empty", "red"))
|
||||
self.bad_database = True
|
||||
return False
|
||||
|
||||
if "global" not in self.base_data:
|
||||
print(colored(" > The database is missing the global section", "red"))
|
||||
self.bad_database = True
|
||||
else:
|
||||
if "discord_version" not in self.base_data["global"]:
|
||||
print(colored(" > The database is missing a version field", "red"))
|
||||
self.bad_database = True
|
||||
else:
|
||||
if self.base_data["global"]["discord_version"] != self.version:
|
||||
print(colored(
|
||||
f" > The database is from a different version ({self.base_data['global']['discord_version']}),"
|
||||
f" you are using {self.version}", "red"
|
||||
))
|
||||
self.bad_database = True
|
||||
if "ptb" not in self.base_data["global"]:
|
||||
print(colored(" > The database is missing a ptb field", "red"))
|
||||
self.bad_database = True
|
||||
else:
|
||||
if self.base_data["global"]["ptb"] != self.ptb:
|
||||
print(colored(
|
||||
f' > The database is for Discord {self.base_data["global"]["ptb"]} '
|
||||
f'you are using Discord{self.ptb}', "red"
|
||||
))
|
||||
self.bad_database = True
|
||||
if "os" not in self.base_data["global"]:
|
||||
print(colored(" > The database is missing an os field", "red"))
|
||||
self.bad_database = True
|
||||
else:
|
||||
if self.base_data["global"]["os"] != self.os_name:
|
||||
print(colored(
|
||||
f" > The database is for {self.base_data['global']['os']}, you are using {self.os_name}", "red"
|
||||
))
|
||||
self.bad_database = True
|
||||
if "tests" not in self.base_data:
|
||||
print(colored(" > The database is missing the test results", "red"))
|
||||
self.bad_database = True
|
||||
|
||||
def update_module_list(self):
|
||||
"""
|
||||
Gets the list of modules to be loaded (in accordance to the config)
|
||||
|
|
@ -155,16 +224,17 @@ class TestRunner:
|
|||
self.list_of_tests = []
|
||||
for module_name, test_class in self.loaded_test_classes.items():
|
||||
print(colored(f" > Starting test {module_name}...", "blue"))
|
||||
tc = test_class(
|
||||
self.args,
|
||||
self.agnostic_path,
|
||||
self.base_data,
|
||||
self.finished_tests,
|
||||
queue_lock,
|
||||
self.dict_of_processes,
|
||||
processes_lock
|
||||
)
|
||||
tc = threading.Thread(target=tc.run_test, args=())
|
||||
tc = test_class(thread_parameters(
|
||||
args=self.args,
|
||||
agnpath=self.agnostic_path,
|
||||
test_data=self.base_data,
|
||||
queue=self.finished_tests,
|
||||
queue_lock=queue_lock,
|
||||
dict_process=self.dict_of_processes,
|
||||
dict_process_lock=processes_lock,
|
||||
bad_database=self.bad_database,
|
||||
))
|
||||
tc = threading.Thread(target=tc.run, args=())
|
||||
tc.name = str(module_name)
|
||||
tc.daemon = True
|
||||
self.list_of_tests.append(tc)
|
||||
|
|
@ -204,7 +274,7 @@ class TestRunner:
|
|||
except KeyboardInterrupt:
|
||||
RUN_OVER = True
|
||||
return
|
||||
except:
|
||||
except Exception:
|
||||
sys.exit()
|
||||
|
||||
def post_test_runner(self):
|
||||
|
|
@ -274,6 +344,7 @@ class TestRunner:
|
|||
nb_tests_success = 0
|
||||
nb_tests_failure = 0
|
||||
nb_tests_skipped = 0
|
||||
nb_tests_error = 0
|
||||
progress = 0
|
||||
for test in self.finished_tests:
|
||||
if test.status == "success":
|
||||
|
|
@ -284,7 +355,7 @@ class TestRunner:
|
|||
elif test.status == "skipped":
|
||||
nb_tests_skipped += 1
|
||||
elif test.status == "problem":
|
||||
nb_tests_failure += 1
|
||||
nb_tests_error += 1
|
||||
# progress += test.progress
|
||||
queue_lock.release()
|
||||
|
||||
|
|
@ -292,7 +363,7 @@ class TestRunner:
|
|||
progress += test.progress
|
||||
progress = int(progress / nb_tests)
|
||||
|
||||
nb_tests_ran = nb_tests_success + nb_tests_failure + nb_tests_skipped
|
||||
nb_tests_ran = nb_tests_success + nb_tests_failure + nb_tests_skipped + nb_tests_error
|
||||
nb_test_running = nb_tests - nb_tests_ran
|
||||
return global_status(
|
||||
tests_total=nb_tests,
|
||||
|
|
@ -301,7 +372,7 @@ class TestRunner:
|
|||
tests_failed=nb_tests_failure,
|
||||
tests_running=nb_test_running,
|
||||
tests_skipped=nb_tests_skipped,
|
||||
tests_error=nb_tests_failure,
|
||||
tests_error=nb_tests_error,
|
||||
progress=progress
|
||||
)
|
||||
|
||||
|
|
@ -426,7 +497,7 @@ def resource_path(relative_path):
|
|||
""" Get absolute path to resource, works for dev and for PyInstaller """
|
||||
try:
|
||||
# PyInstaller creates a temp folder and stores path in _MEIPASS
|
||||
base_path = sys._MEIPASS # noqa
|
||||
base_path = sys._MEIPASS # noqa # TODO: Detect if archive, likely with a ugly global check
|
||||
except Exception:
|
||||
base_path = os.path.abspath(".")
|
||||
return os.path.join(base_path, relative_path)
|
||||
|
|
@ -437,25 +508,34 @@ def print_final_status(testrunner, start_time, args):
|
|||
Prints the final status
|
||||
"""
|
||||
status = testrunner.get_status()
|
||||
if status.tests_failed == 0:
|
||||
if status.tests_failed == 0 and status.tests_error == 0:
|
||||
color = "green"
|
||||
print(CLEAR_CODE)
|
||||
else:
|
||||
elif status.tests_failed > 0:
|
||||
color = "red"
|
||||
print(INFECTED_CODE)
|
||||
print(colored(f"\nThe test sequence is now finished, DiscordHelper ran for {round(time.time() - start_time,2)} seconds", color))
|
||||
else:
|
||||
color = "yellow"
|
||||
print(UNKNOWN_CODE)
|
||||
|
||||
print(colored(
|
||||
f"\nThe test sequence is now finished, DiscordHelper ran for "
|
||||
f"{round(time.time() - start_time,2)} seconds", color
|
||||
))
|
||||
SIZE = args.size
|
||||
for test, test_object in testrunner.dict_of_processes.items():
|
||||
if test_object.status_code == "success":
|
||||
print(colored(f" > {fill_it(SIZE,test,'SUCCESS')}", "green"))
|
||||
elif test_object.status_code == "failure":
|
||||
print(colored(f" > {fill_it(SIZE,test,'FAILURE')}", "red"))
|
||||
error_message = fit_it_under(test_object.status, SIZE-3, ' > ')
|
||||
if args.max_shown != -1: # TODO : Correct this abomination
|
||||
table = error_message.split("\n")
|
||||
extra = [f" > ... {len(table) - args.max_shown} more lines"] if len(table) > args.max_shown else []
|
||||
error_message = "\n".join(table[:args.max_shown] + extra)
|
||||
error_message = "\n".join(at_max_elements(
|
||||
fit_it_under(test_object.status, SIZE-3, ' > '), args.max_shown, " > ... "))
|
||||
print(colored(f"{error_message}", "red"))
|
||||
elif test_object.status_code == "problem":
|
||||
print(colored(f" > {fill_it(SIZE,test,'PROBLEM')}", "yellow"))
|
||||
error_message = "\n".join(at_max_elements(
|
||||
fit_it_under(test_object.status, SIZE-3, ' > '), args.max_shown, " > ... "))
|
||||
print(colored(f"{error_message}", "yellow"))
|
||||
else:
|
||||
print(colored(f" > {fill_it(SIZE,test,test_object.status_code.upper())}", "yellow"))
|
||||
msg_error = "sucessfully" if status.tests_failed == 0 else f"with {status.tests_error} errors"
|
||||
|
|
@ -469,20 +549,30 @@ def fill_it(size, string1, string2):
|
|||
return string1 + max(size - len(string1)-len(string2), 0) * "." + string2
|
||||
|
||||
|
||||
def at_max_elements(table, msize, fill):
|
||||
"""
|
||||
Display at maximum msize elements, replace last with fill and return the table
|
||||
"""
|
||||
if msize == -1:
|
||||
return table
|
||||
|
||||
# if en(table) > lmsize:
|
||||
table = table[:msize] + [
|
||||
fill+"..."+str(len(table)-msize)+" more lines" if len(table) > msize else ""]
|
||||
return table
|
||||
|
||||
|
||||
def fit_it_under(message, size, start_line=""):
|
||||
"""
|
||||
Fits a message under a size
|
||||
"""
|
||||
final_message = ""
|
||||
final_message = []
|
||||
for line in message.split('\n'):
|
||||
if len(line) > size:
|
||||
final_message += start_line + line[:size] + "\n"
|
||||
final_message += [start_line + line[:size]]
|
||||
final_message += fit_it_under(line[size:], size, start_line)
|
||||
else:
|
||||
final_message += start_line + line + "\n"
|
||||
# final_message += start_line + line + '\n'
|
||||
# if len(message) > size:
|
||||
# return message[:size-3] + "..."
|
||||
final_message += [start_line + line]
|
||||
return final_message
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,16 +1,15 @@
|
|||
import asyncio
|
||||
import os
|
||||
import time
|
||||
|
||||
from modules import test_template
|
||||
|
||||
|
||||
class SizeTest(test_template.TestWalkTemplateNoLogs):
|
||||
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
|
||||
def __init__(self, thread_parameters):
|
||||
"""
|
||||
Simple test runner, compare file size to known good values.
|
||||
"""
|
||||
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
|
||||
super().__init__(thread_parameters)
|
||||
self.is_unknown = False
|
||||
|
||||
def run_test(self):
|
||||
"""
|
||||
|
|
@ -19,7 +18,8 @@ class SizeTest(test_template.TestWalkTemplateNoLogs):
|
|||
:rtype: bool
|
||||
"""
|
||||
self.set_status("running")
|
||||
size = len(self.walk())
|
||||
size = self.agnostic_path.size
|
||||
|
||||
error_msg = ""
|
||||
for i, path in enumerate(self.walk()):
|
||||
self.progress = int(100*i/size)
|
||||
|
|
@ -30,9 +30,21 @@ class SizeTest(test_template.TestWalkTemplateNoLogs):
|
|||
self.add_failure(path, f"Test {self.name()} failed on {short_path}")
|
||||
error_msg += f"{short_path} is " \
|
||||
f"({res} b) not ({self.get_expected_result(path, 'size')} b).\n"
|
||||
self.is_infected = True
|
||||
if not self.args.continue_on_error:
|
||||
return self.finish("failure", f"{short_path} is supposed to be {self.get_expected_result(path, 'size')} bytes, but it is {os.path.getsize(path)} bytes.")
|
||||
# print(self.bad_database)
|
||||
if not self.bad_database:
|
||||
self.is_infected = True
|
||||
if not self.args.continue_on_error:
|
||||
return self.finish(
|
||||
"failure",
|
||||
f"{short_path} is supposed to be {self.get_expected_result(path, 'size')}"
|
||||
f" bytes, but it is {os.path.getsize(path)} bytes.")
|
||||
else:
|
||||
self.is_unknown = True
|
||||
if not self.args.continue_on_error:
|
||||
return self.finish(
|
||||
"problem",
|
||||
f"{short_path} is supposed to be {self.get_expected_result(path, 'size')}"
|
||||
f" bytes, but it is {os.path.getsize(path)} bytes.")
|
||||
|
||||
self.progress = 100
|
||||
if self.is_infected:
|
||||
|
|
@ -40,5 +52,9 @@ class SizeTest(test_template.TestWalkTemplateNoLogs):
|
|||
"failure",
|
||||
error_msg
|
||||
)
|
||||
elif self.is_unknown:
|
||||
return self.finish(
|
||||
"problem",
|
||||
error_msg
|
||||
)
|
||||
return self.finish("success", "Your discord is not infected.")
|
||||
|
||||
|
|
|
|||
|
|
@ -1,16 +1,14 @@
|
|||
import asyncio
|
||||
import os
|
||||
import time
|
||||
|
||||
from modules import test_template
|
||||
|
||||
|
||||
class SpideyTest(test_template.TestTemplate):
|
||||
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
|
||||
def __init__(self, thread_parameters):
|
||||
"""
|
||||
Simple test runner, for testing the detection of Spidey viruses.
|
||||
"""
|
||||
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
|
||||
super().__init__(thread_parameters)
|
||||
|
||||
def run_test(self):
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -13,46 +13,60 @@ class TestDataError(Exception):
|
|||
|
||||
|
||||
class TestTemplate:
|
||||
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
|
||||
def __init__(self, thread_parameters: internal_io.thread_parameters):
|
||||
"""
|
||||
Simple test template.
|
||||
:param args: List of arguments
|
||||
:type args: argparse.Namespace
|
||||
:param agnpath: The path to the discord folder
|
||||
:type agnpath: agnostic_path.AgnosticPath
|
||||
:param test_data: The data to be tested
|
||||
:type test_data: dict
|
||||
:param queue: The queue to put the test status in
|
||||
:type queue: queue.deque
|
||||
:param queue_lock: The lock to use when putting the test status in the queue
|
||||
:type queue_lock: threading.Lock
|
||||
:param dict_process: The dictionary of processes
|
||||
:type dict_process: dict
|
||||
:param dict_process_lock: The lock to use when putting the process in the dictionary
|
||||
:type dict_process_lock: threading.Lock
|
||||
:param thread_parameters.args: List of arguments
|
||||
:type thread_parameters.args: argparse.Namespace
|
||||
:param thread_parameters.agnpath: The path to the discord folder
|
||||
:type thread_parameters.agnpath: agnostic_path.AgnosticPath
|
||||
:param thread_parameters.test_data: The data to be tested
|
||||
:type thread_parameters.test_data: dict
|
||||
:param thread_parameters.queue: The queue to put the test status in
|
||||
:type thread_parameters.queue: queue.deque
|
||||
:param thread_parameters.queue_lock: The lock to use when putting the test status in the queue
|
||||
:type thread_parameters.queue_lock: threading.Lock
|
||||
:param thread_parameters.dict_process: The dictionary of processes
|
||||
:type thread_parameters.dict_process: dict
|
||||
:param thread_parameters.dict_process_lock: The lock to use when putting the process in the dictionary
|
||||
:type thread_parameters.dict_process_lock: threading.Lock
|
||||
:param thread_parameters.bad_database: Whether the database was sucessfully loaded and contains valid data
|
||||
:type thread_parameters.bad_database: bool
|
||||
"""
|
||||
self.args = args
|
||||
self.ptb = args.ptb
|
||||
self.agnostic_path = agnpath
|
||||
self.os_name = agnpath.os
|
||||
self.main_path = agnpath.main_path
|
||||
self.test_data = test_data
|
||||
self.args = thread_parameters.args
|
||||
self.ptb = thread_parameters.args.ptb
|
||||
self.agnostic_path = thread_parameters.agnpath
|
||||
self.os_name = thread_parameters.agnpath.os
|
||||
self.main_path = thread_parameters.agnpath.main_path
|
||||
self.test_data = thread_parameters.test_data
|
||||
self.is_infected = False
|
||||
self.status_code = "idle"
|
||||
self.status = "Test not yet initialized."
|
||||
self.queue = queue
|
||||
self.queue = thread_parameters.queue
|
||||
self.set_status("idle")
|
||||
self.queue_lock = queue_lock
|
||||
self.queue_lock = thread_parameters.queue_lock
|
||||
self.failure_dict = {}
|
||||
self.new_data = {}
|
||||
self.progress = 0
|
||||
self.dict_process = dict_process
|
||||
self.dict_process_lock = dict_process_lock
|
||||
self.is_unknown = False
|
||||
self.dict_process = thread_parameters.dict_process
|
||||
self.dict_process_lock = thread_parameters.dict_process_lock
|
||||
self.bad_database = thread_parameters.bad_database
|
||||
self.dict_process_lock.acquire()
|
||||
self.dict_process[self.name()] = self
|
||||
self.dict_process_lock.release()
|
||||
self.init_test_data()
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Runs the test.
|
||||
"""
|
||||
try:
|
||||
self.run_test()
|
||||
except Exception as e:
|
||||
self.add_failure("problem", "DISCORD HELPER:"+str(e))
|
||||
return self.finish("problem", str(e))
|
||||
|
||||
def run_test(self):
|
||||
"""
|
||||
The main runner function, must be implemented by the child class.
|
||||
|
|
@ -154,17 +168,11 @@ class TestTemplate:
|
|||
|
||||
|
||||
class TestWalkTemplate(TestTemplate):
|
||||
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
|
||||
def __init__(self, thread_parameters):
|
||||
"""
|
||||
Simple test template.
|
||||
:param args: List of arguments
|
||||
:type args: argparse.Namespace
|
||||
:param agnpath: The path to the discord folder
|
||||
:type agnpath: agnostic_path.AgnosticPath
|
||||
:param test_data: The data to be tested
|
||||
:type test_data: str
|
||||
"""
|
||||
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
|
||||
super().__init__(thread_parameters)
|
||||
self.to_skip = []
|
||||
|
||||
def add_test_result(self, path, testname, result):
|
||||
|
|
@ -234,7 +242,10 @@ class TestWalkTemplate(TestTemplate):
|
|||
return self.finish()
|
||||
|
||||
if len(self.failure_dict) > 0:
|
||||
self.set_status("failure", f"Test {self.name()} failed on {len(self.failure_dict)} files.")
|
||||
if self.bad_database:
|
||||
self.set_status("unknown", f"Test {self.name()} failed on {len(self.failure_dict)} files")
|
||||
else:
|
||||
self.set_status("failure", f"Test {self.name()} failed on {len(self.failure_dict)} files.")
|
||||
else:
|
||||
self.set_status("success", f"Test {self.name()} passed.")
|
||||
|
||||
|
|
@ -243,10 +254,10 @@ class TestWalkTemplate(TestTemplate):
|
|||
def walk(self):
|
||||
"""
|
||||
Walks the given path and returns a list of all files and directories.
|
||||
:return: List of all files and directories
|
||||
:return: List of all files
|
||||
:return:
|
||||
"""
|
||||
return self.agnostic_path.walk_all_files(self.agnostic_path())
|
||||
return self.agnostic_path.all_files
|
||||
|
||||
def compare(self, path, entry_name, function, args, kwargs, cmp_function=None):
|
||||
"""
|
||||
|
|
@ -286,15 +297,9 @@ class TestWalkTemplate(TestTemplate):
|
|||
|
||||
|
||||
class TestWalkTemplateNoLogs(TestWalkTemplate):
|
||||
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
|
||||
def __init__(self, thread_parameters):
|
||||
"""
|
||||
Simple test template.
|
||||
:param args: List of arguments
|
||||
:type args: argparse.Namespace
|
||||
:param agnpath: The path to the discord folder
|
||||
:type agnpath: agnostic_path.AgnosticPath
|
||||
:param test_data: The data to be tested
|
||||
:type test_data: str
|
||||
"""
|
||||
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
|
||||
super().__init__(thread_parameters)
|
||||
self.to_skip = [r"modules\discord_dispatch-1\discord_dispatch\dispatch.log"]
|
||||
|
|
|
|||
Reference in New Issue