Compare commits

...

41 Commits
v1.0.5 ... main

Author SHA1 Message Date
Maximilien Rigaut 03a49e049b
Merge pull request #36 from idle-org/develop
Develop
2022-06-27 18:44:53 +02:00
Maximilien Rigaut 9f00fd8b7e
Merge pull request #35 from idle-org/features/fast_access
Features/fast access
2022-06-27 18:35:58 +02:00
Maximilien Rigaut c8772e0f9b
Actually activated the cache 2022-06-27 18:34:50 +02:00
Maximilien Rigaut ee77507bc9
Implementation of file caching 2022-06-27 18:10:46 +02:00
Maximilien Rigaut 0df5970a41
Skipped the first message 2022-06-27 17:22:45 +02:00
Maximilien Rigaut 854ce93430
Merge pull request #34 from idle-org/features/ptb
Updated with ptb data
2022-06-27 17:06:20 +02:00
Maximilien Rigaut 87bcc47af1
Updated with ptb data 2022-06-27 17:04:09 +02:00
Maximilien Rigaut 53d751e3bb
Merge pull request #33 from idle-org/features/typehunts
Features/typehunts
2022-06-27 14:54:31 +02:00
Maximilien Rigaut 7af44900d3
Type hinting followup 2022-06-27 14:51:52 +02:00
Maximilien Rigaut 079a5e69be
More type hinting 2022-06-27 04:40:41 +02:00
Maximilien Rigaut cfe76ca497
Type hinting 2022-06-27 04:24:41 +02:00
Maximilien Rigaut 22952cd871
Merge pull request #32 from idle-org/features/test_centralisation
Correction of the auto test data generation
2022-06-27 04:13:56 +02:00
Maximilien Rigaut 8333c4daa7
Correction of the auto test data generation 2022-06-27 04:09:00 +02:00
Maximilien Rigaut 1c32e30533
Merge pull request #31 from idle-org/features/test_centralisation
Added spidey test data
2022-06-27 04:06:47 +02:00
Maximilien Rigaut 16ef468fcc
Added spidey test data 2022-06-27 04:06:09 +02:00
Maximilien Rigaut bf09d81afb
Merge pull request #30 from idle-org/features/test_centralisation
Features/test centralisation
2022-06-27 04:04:33 +02:00
Maximilien Rigaut c8292f498b
Cleanup of some tests and base tests methods 2022-06-27 04:01:40 +02:00
Maximilien Rigaut 335d7fc967
Changed some default parameters 2022-06-27 03:01:31 +02:00
Maximilien Rigaut 2741329afc
Changed tests names 2022-06-27 03:00:57 +02:00
Maximilien Rigaut cd38817742
Changed test data 2022-06-27 02:59:36 +02:00
Maximilien Rigaut aa249aad51
Renamed tests and added a fast class for function interaction 2022-06-27 02:59:16 +02:00
Maximilien Rigaut 724a054f14
Merge pull request #29 from idle-org/features/middleground
Features/middleground
2022-06-26 07:54:12 +02:00
Maximilien Rigaut 09ab0f4223
Merge pull request #28 from idle-org/features/todos
Updated README.md
2022-06-26 07:53:31 +02:00
Maximilien Rigaut 6ed629852f
Added a middleground between failure and success 2022-06-26 07:53:06 +02:00
Maximilien Rigaut 34aca29359
Moar linting, cleared roadblocks for the middleground error 2022-06-26 06:44:48 +02:00
Maximilien Rigaut 29b3929b86
Linting 2022-06-26 06:20:53 +02:00
Maximilien Rigaut b4656620ae
Updated README.md 2022-06-26 05:46:21 +02:00
Maximilien Rigaut 3b3cc1309e
Merge pull request #25 from idle-org/features/update_spidey_test
updated spidey test
2022-06-26 05:31:54 +02:00
Maximilien Rigaut c5c9eb50bc
Reverted a space mistake, cleared prints 2022-06-26 05:30:25 +02:00
Maximilien Rigaut 31f68c92b8
Merge remote-tracking branch 'origin/develop' into develop
# Conflicts:
#	discordHelperWin.py
2022-06-26 05:29:38 +02:00
Maximilien Rigaut 776fb96e1a
Reverted a space mistake, cleared prints 2022-06-25 22:53:26 +02:00
Maximilien Rigaut c2c697bbe0
Reverted a space mistake 2022-06-25 22:49:24 +02:00
Maximilien Rigaut 9811a9ab33
Merge pull request #27 from idle-org/features/databases/windows_ptb
added windows_ptb to database
2022-06-25 22:43:48 +02:00
vky 4bc7e89e62 added windows_ptb to database 2022-06-25 22:42:49 +02:00
Maximilien Rigaut 7405f8f7eb
Merge remote-tracking branch 'origin/develop' into develop 2022-06-25 22:39:21 +02:00
Maximilien Rigaut 63bf687f0e
Merge pull request #24 from idle-org/features/launch_discord
implemented discord launch
2022-06-25 22:38:10 +02:00
vky df0e5e6746 added windows verification 2022-06-25 22:34:34 +02:00
vky 6b9d3511b9 updated spidey test 2022-06-25 22:27:43 +02:00
Maximilien Rigaut 544de58745
Corrected the ptb db 2022-06-25 22:24:52 +02:00
vky 8d563d080e implemented discord launch 2022-06-25 22:20:15 +02:00
Maximilien Rigaut 08ca0b1858
Merge pull request #19 from idle-org/develop
Develop
2022-06-25 02:19:13 +02:00
20 changed files with 18248 additions and 6218 deletions

4
.gitignore vendored
View File

@ -131,5 +131,5 @@ dmypy.json
/.idea/*
databases/*
/discordHelper/discordHelper_last_run.json.yaml
/discordHelper/*
/certs/*

View File

@ -3,12 +3,21 @@
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 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.
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.

File diff suppressed because it is too large Load Diff

8845
databases/windows_ptb.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,19 +1,19 @@
#!/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)
test_runner = main_runner.run_check(argm, agnostic_path)
main_runner.run_check(argm, agnostic_path)
if __name__ == "__main__":

View File

@ -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 test_size, test_adler, test_sha, test_spidey, test_line_count # noqa # Set for pyinstaller
if __name__ == "__main__":
try:
@ -24,10 +24,9 @@ if __name__ == "__main__":
db_path = ""
# print(" > No user database was found, the bundled one will be used.")
# Will always try to load discordHelper/discordHelper.json # TODO : Document this feature.
# 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 --printrate 2 --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))
@ -35,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

0
modules/__init__.py Normal file
View File

View File

@ -1,52 +0,0 @@
"""
Fast adler32 checksum implementation.
"""
import os
from modules import test_template
from zlib import adler32
def apply_adler(path):
"""
Apply the adler32 checksum to a file.
:param path: The path to the file.
:type path: str
:return: The adler32 checksum.
:rtype: int
"""
with open(path, "rb") as f:
return hex(adler32(f.read()))
class AdlerTest(test_template.TestWalkTemplateNoLogs):
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
"""
Simple test runner, compare adler32 to known good values.
"""
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
def run_test(self):
self.set_status("running")
size = len(self.walk())
error_msg = ""
for i, path in enumerate(self.walk()):
self.progress = int(100*i/size)
short_path = self.agnostic_path.get_short_path(path)
if os.path.isfile(path):
if not self.compare(path, "adler32", apply_adler, (), {}):
res = self.get_test_data(path, "adler32")
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.")
self.progress = 100
if self.is_infected:
return self.finish(
"failure",
error_msg
)
return self.finish("success", "Your discord is not infected.")

View File

@ -4,17 +4,20 @@ The agnostic path handler, gives all methods to access all paths of the discord
import os
import re
import sys
import random
import argparse
from typing import List, Dict
class AgnosticPaths:
"""
An agnostic path object, containing all methods to access the files and folders in a standard discord install
"""
def __init__(self, args):
def __init__(self, args: argparse.Namespace):
"""
:param args: The arguments passed to the script
:type args: argparse.Namespace
"""
self.args = args
self.ptb = args.ptb
@ -27,16 +30,44 @@ 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)
self.cached_files = {}
self.cached_dirs = {}
self._precache_files()
def get_os(self):
def walk_cached(self) -> Dict[str, bytes]:
"""
Returns the cached files and directories
:return: The list of files and directories
"""
return self.cached_files
def walk_files(self) -> List[str]:
"""
Returns the list of all files in the discord install
:return: The list of all files in the discord install
"""
return self.all_files
def cached_file(self, path: str) -> bytes:
"""
Returns the file at the given path, if it is cached, otherwise it will return None
:param path: The path to the file
:return: The file at the given path, if it is cached, otherwise it will return None
"""
if path in self.cached_files:
return self.cached_files[path]
return None
def get_os(self) -> str:
"""
Get the os string in a short, spydey-detector way.
For now only windows and linux are supported, note that due to the nature of linux builds, strings will likely become
linux-arch-deb, linux-arch-snap etc...
For now only windows and linux are supported, note that due to the nature of linux builds,
strings will likely become linux-arch-deb, linux-arch-snap etc...
:return: ("windows", "linux", "mac")
:rtype: str
"""
platform = sys.platform
if platform.startswith('win'):
self.os = 'windows'
@ -51,18 +82,17 @@ class AgnosticPaths:
raise OSError("This script can only check for Spideys on Windows, Linux and Mac.")
return self.os
def _get_path(self):
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)
:rtype: str
:return: Base path of the installation (minus the version on Windows)
"""
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")
ptb_path = base_path+"PTB"
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):
self.ptb = "PTB"
@ -73,10 +103,10 @@ class AgnosticPaths:
self.default_database = "databases/windows_base.json"
return base_path
if self.ptb == 'PTB':
self.default_database = "databases/windows_bas.jsone"
return base_path+"PTB"
self.default_database = "databases/windows_ptb.jsone"
return base_path + "PTB"
else:
self.default_database = "databases/windows_ptb.json"
self.default_database = "databases/windows_base.json"
return base_path # Try to find the default version
elif self.os == 'linux':
return os.path.join("/", "opt", "discord")
@ -85,12 +115,11 @@ class AgnosticPaths:
return ""
raise OSError("Cannot detect discord PATH")
def get_version(self):
def get_version(self) -> str:
"""
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
"""
versions = []
if self.os == 'windows':
@ -109,24 +138,24 @@ 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)
"""
if self.os == 'windows':
self.main_path = os.path.join(self.main_path, self.version)
def list(self, *args):
def list(self, *args: str) -> List[float]:
"""
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))
def list_dir_files(self, *args):
def list_dir_files(self, *args: str) -> List[str]:
"""
Lists all files and directories in the given path.
:param args: The path
@ -142,58 +171,60 @@ class AgnosticPaths:
files.append(element)
return dirs, files
def __call__(self, *args):
def __call__(self, *args: str) -> str:
"""
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")
:type args: str
:param args: The path of the file or directory as a list of parameters __call__("folder_1", ..., "folder_n")
:return: The path is it exists
:rtype: str
: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):
raise FileNotFoundError(f"Could not find {_path}")
return _path
def get_path(self):
def get_path(self) -> str:
"""
The main path of the discord install
:return: self.main_path
:rtype: str
"""
return self.main_path
def walk_all_files(self, *args):
def walk_all_files(self, *args: str) -> List[str]:
"""
Walks all files in the given path
:param args: The path
:return: A list of all files in the given path
:rtype: list[str]
"""
return [os.path.join(dirpath, filename)
for dirpath, dirnames, filenames in os.walk(self(*args))
for filename in filenames]
def get_short_path(self, path):
def get_short_path(self, path: str) -> str:
"""
Get the short path of the given path
:param path: The path
:return: The short path
:rtype: str
"""
return os.path.relpath(path, self.main_path)
def __repr__(self):
def _precache_files(self) -> None:
"""
Precache all files in the discord folder
"""
self.cached_files = {}
for file in self.all_files:
with open(file, "rb") as f:
self.cached_files[file] = f.read()
def __repr__(self) -> str:
"""
:return: A representation of the AgnosticPath
:rtype: str
"""
return f"AgnosticPaths(ptb={self.ptb}, os={self.os}, main_path={self.main_path}, version={self.version})"
def __str__(self):
def __str__(self) -> str:
"""
:return: The main path of the discord install
:rtype: str
"""
return self.main_path

View File

@ -1,7 +1,7 @@
import argparse
def parse(_args):
def parse(_args: list) -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="Spidey Detector",
description='Checks for corrupt 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
@ -26,25 +27,27 @@ def parse(_args):
parser.add_argument("--gen-data", "--generate-data", "--gen", nargs=1, default="", help="Generate data for the analysis")
parser.add_argument("--database", "--db", type=str, help="Alternative database for the analysis")
parser.add_argument("--pollrate", "--poll", default=0.1, type=float, help="Refresh rate of the status, 0.1 is the default")
parser.add_argument("--printrate", "-refresh", default=5, type=int, help="Print the tests every X seconds")
parser.add_argument("--printrate", "--refresh", default=5, type=float, help="Print the tests every X seconds")
parser.add_argument("--size", "--window-size", default=110, type=int, help="Size of the message window")
parser.add_argument("--max-shown", default=5, type=int, help="Maximum number of errors shown")
# Tests
parser.add_argument('--spidey', action='store_true', help='Runs the spidey test')
parser.add_argument('--adler', "--adler32", action='store_true', help='Runs the adler32 test')
parser.add_argument('--line-count', action='store_true', help='Test all known files for line count')
parser.add_argument('--file-count', action='store_true', help="Test the number of files in the discord folder")
parser.add_argument('--file-size', action='store_true', help="Test the size of the files in the discord folder")
parser.add_argument('--file-hash', action='store_true', help="Test the hash of the files in the discord folder")
parser.add_argument('--file-hash', '--sha', action='store_true', help="Test the hash of the files in the discord folder")
parser.add_argument('--file-path', action='store_true', help="Test the path of the files in the discord folder")
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("--test-walk", action="store_true", help="Test walk function")
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("--max-errors", default=5, type=int, help="Maximum number of errors before the analysis is stopped")
return parser.parse_args(_args)

View File

@ -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)
)

View File

@ -1,13 +1,16 @@
import argparse
import json
import os
import subprocess
import sys
import importlib
import threading
import time
from collections import deque
from typing import List
from modules.internal_io import global_status
from modules import size_test, adler_test # noqa # Used to force import of modules by pyinstaller
from modules.internal_io import global_status, thread_parameters
from modules import agnostic_paths, internal_io
"""
All modules that can be tested
@ -19,10 +22,11 @@ os.system('color')
# red, green, yellow, blue, magenta, cyan, white.
_TEST_MODULES = {
"spidey": ["spidey_test", "SpideyTest"],
# "test_walk": ["test_template", "TestWalkTemplate"],
"size_test": ["size_test", "SizeTest"],
"adler_test": ["adler_test", "AdlerTest"],
"spidey": ["test_spidey", "SpideyTest"],
"file_size": ["test_size", "SizeCheck"],
"adler": ["test_adler", "Adler32"],
"file_hash": ["test_sha", "Sha256"],
"line_count": ["test_line_count", "LineCount"],
}
PROGRAM_VERSION = "1.0.0"
@ -33,16 +37,16 @@ queue_lock = threading.Lock()
processes_lock = threading.Lock()
CLEAR_CODE = colored(r"""
_______ _
(_______) |
_ | | _____ _____ ____
_______ _
(_______) |
_ | | _____ _____ ____
| | | || ___ (____ |/ ___)
| |_____| || ____/ ___ | |
| |_____| || ____/ ___ | |
\______)\_)_____)_____|_|
""", 'green')
INFECTED_CODE = colored(r"""
_ ___ _
_ ___ _
| | / __) _ | |
| |____ _| |__ _____ ____ _| |_ _____ __| |
| | _ (_ __) ___ |/ ___|_ _) ___ |/ _ |
@ -50,25 +54,31 @@ INFECTED_CODE = colored(r"""
|_|_| |_||_| |_____)\____) \__)_____)\____|
""", 'red')
UNKNOWN_CODE = colored(r"""
_ _ _
(_) (_) | |
_ _ ____ | | _ ____ ___ _ _ _ ____
| | | | _ \| |_/ ) _ \ / _ \| | | | _ \
| |___| | | | | _ (| | | | |_| | | | | | | |
\_____/|_| |_|_| \_)_| |_|\___/ \___/|_| |_|
""", 'yellow')
LOGO = colored(r"""
__ \ _) | | | |
| | | __| __| _ \ __| _` | | | _ \ | __ \ _ \ __|
| | | \__ \ ( ( | | ( | ___ | __/ | | | __/ |
____/ _| ____/ \___| \___/ _| \__,_| _| _| \___| _| .__/ \___| _|
_|
__ \ _) | | | |
| | | __| __| _ \ __| _` | | | _ \ | __ \ _ \ __|
| | | \__ \ ( ( | | ( | ___ | __/ | | | __/ |
____/ _| ____/ \___| \___/ _| \__,_| _| _| \___| _| .__/ \___| _|
_|
""", "cyan")
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
@ -77,9 +87,13 @@ class TestRunner:
self.main_path = agnpath.main_path
self.version = agnpath.version
self.start_time = start_time
self.selected_tests = []
self.is_infected = 0
self.detections = 0
self.is_infected = 0 # Only set to 1 if the certainty is high enough
self.is_unknown = 1 # 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 = {}
@ -94,9 +108,17 @@ class TestRunner:
self.open_base_data()
self.exec_all_tests()
def open_base_data(self):
def update_threat(self, threat_level: int):
"""
Updates the threat level
:param threat_level: The new threat level
"""
self.threat_level = max(threat_level, self.threat_level)
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)
@ -107,6 +129,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(
@ -115,6 +138,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:
@ -122,14 +146,71 @@ 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 update_module_list(self):
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"))
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
else:
for test_name in self.selected_tests:
found_one_value = False
for file_name, test_names in self.base_data["tests"].items():
if test_name in test_names:
found_one_value = True
break # At least one test is in the database
if not found_one_value:
print(colored(f" > The database is missing the test {test_name}", "red"))
self.bad_database = True
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 = {}
@ -139,6 +220,7 @@ class TestRunner:
if self.args.all or self.args.__getattribute__(module_name):
modules[values[0]] = importlib.import_module(f"modules.{values[0]}")
classes[values[0]] = getattr(modules[values[0]], values[1])
self.selected_tests.append(values[1])
except AttributeError as e:
print(f"The module {module_name} was not loaded because it was not specified in the config.")
@ -147,23 +229,24 @@ 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
"""
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)
@ -185,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
"""
@ -203,10 +286,10 @@ class TestRunner:
except KeyboardInterrupt:
RUN_OVER = True
return
except:
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
"""
@ -216,15 +299,16 @@ class TestRunner:
if RUN_OVER:
if POST_RUN_ALLOWED and self.is_infected == 0: # Second part is redundant
print(colored("\n > Running post test runner...", "green"))
if self.agnostic_path.os == "windows":
subprocess.Popen([self.agnostic_path.main_path + f"\\Discord{self.agnostic_path.ptb}.exe"])
return 0
return 1
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()
@ -235,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:
@ -260,17 +343,17 @@ 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)
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":
@ -281,15 +364,18 @@ 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()
for test_name, test in self.dict_of_processes.items():
progress += test.progress
progress = int(progress / nb_tests)
if nb_tests == 0:
progress = 100
else:
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,
@ -298,15 +384,14 @@ 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
)
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()
@ -320,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":
@ -341,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"
@ -372,20 +453,20 @@ def print_status(status, timer_start):
else:
mon, sec = divmod(ellapsed_time * 100 / status.progress, 60)
hr, mon = divmod(mon, 60)
estimated_time = "%d:%02d:%02d" % (hr, mon, sec)
sec = round(sec, 0) + 1
estimated_time = f"{hr:n}:{mon:02n}:{sec:02.0n}"
print(colored(
f" > Overall progress: {status.progress}%"
f" in {time.time() - timer_start:.2f} seconds"
f" estimaded time ({estimated_time})", color
f" estimaded total time ({estimated_time})", color
))
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)
@ -393,7 +474,7 @@ def run_check(args, agnpath):
tr = TestRunner(args, agnpath, start_time=start) # All operation are executed in parallel and the user can stop them
# Poll information from the tests
POLLRATE, PRINT_RATE, COUNTER = args.pollrate, args.printrate, 0
POLLRATE, PRINT_RATE, COUNTER = args.pollrate, args.printrate, 1
COUNTER_MAX = int(PRINT_RATE / POLLRATE)
# Main test polling loop
@ -419,73 +500,93 @@ 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
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)
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
"""
status = testrunner.get_status()
if status.tests_failed == 0:
if status.tests_failed == 0 and status.tests_error == 0 and status.tests_total != 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"
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
return string1 + max(size - len(string1) - len(string2), 0) * "." + string2
def fit_it_under(message, size, start_line=""):
def at_max_elements(table: list, msize: int, fill: str) -> list:
"""
Fits a message under a size
Display at maximum msize elements, replace last with fill and return the table
"""
final_message = ""
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: str, size: int, start_line: str = "") -> list:
"""
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'):
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
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()

View File

@ -1,44 +0,0 @@
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):
"""
Simple test runner, compare file size to known good values.
"""
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
def run_test(self):
"""
Walk all files and check their size.
:return: Whether any of the files are larger than the expected size.
:rtype: bool
"""
self.set_status("running")
size = len(self.walk())
error_msg = ""
for i, path in enumerate(self.walk()):
self.progress = int(100*i/size)
short_path = self.agnostic_path.get_short_path(path)
if os.path.isfile(path):
if not self.compare(path, "size", os.path.getsize, (), {}):
res = self.get_test_data(path, "adler32")
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.")
self.progress = 100
if self.is_infected:
return self.finish(
"failure",
error_msg
)
return self.finish("success", "Your discord is not infected.")

28
modules/test_adler.py Normal file
View File

@ -0,0 +1,28 @@
"""
Fast adler32 checksum implementation.
"""
from modules import test_template, internal_io
from zlib import adler32
def apply_adler(path: str, cached_data: bytes = None) -> hex:
"""
Apply the adler32 checksum to a string.
:param path: The path to the file.
:param cached_data: The cached data if it exists.
:return: The adler32 checksum.
"""
if cached_data is None:
with open(path, "rb") as f:
return hex(adler32(f.read()))
return hex(adler32(cached_data))
class Adler32(test_template.TestWalkTemplateSimpleFunction):
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Simple test runner, compare adler32 to known good values.
"""
super().__init__(thread_parameters, apply_adler, "", use_cache=True)

View File

@ -0,0 +1,15 @@
"""
Test against the line count of the files in the discord folder.
"""
from modules import test_template, internal_io
class LineCount(test_template.TestWalkTemplateSimpleFunction):
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Simple test runner, compare line count to known good values.
"""
super().__init__(thread_parameters,
lambda bstr, cached_data: len(open(bstr, "rb").readlines()),
" lines", use_cache=False)

34
modules/test_sha.py Normal file
View File

@ -0,0 +1,34 @@
"""
Sha256 hash function.
"""
from hashlib import sha256
from modules import test_template, internal_io
def sha256_hash(path: str, cached_data: bytes = None) -> hex:
"""
Returns the sha256 hash of the data.
"""
if cached_data is None:
with open(path, "rb") as f:
return sha256(f.read()).hexdigest()
return sha256(cached_data).hexdigest()
def sha256_hash_on_str(io_s: bytes) -> hex:
"""
Returns the sha256 hash of the data.
"""
return sha256(io_s).hexdigest()
class Sha256(test_template.TestWalkTemplateSimpleFunction):
"""
Sha256 hash function.
"""
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Sha256 hash function.
"""
super().__init__(thread_parameters, sha256_hash, "", use_cache=True)

20
modules/test_size.py Normal file
View File

@ -0,0 +1,20 @@
import os
from modules import test_template, internal_io
def get_size(path: str, cached_data: bytes = None) -> int: # noqa: E501
"""
Get the size of a file.
:param path: The path to the file.
:return: The size of the file.
"""
return os.path.getsize(path)
class SizeCheck(test_template.TestWalkTemplateSimpleFunction):
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Simple test runner, compare file size to known good values.
"""
super().__init__(thread_parameters, get_size, " bytes", use_cache=False)

View File

@ -1,23 +1,20 @@
import asyncio
import os
import time
from modules import test_template
from modules import test_template, internal_io
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: internal_io.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):
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")
@ -25,20 +22,22 @@ class SpideyTest(test_template.TestTemplate):
self.is_infected = False
lines = 0
with open(os.path.join(paths[0], "index.js")) as f:
for line in f:
lines += 1 # TODO: you don't actually need to count the lines, you can just check if it's more than 1
if lines > 1:
self.is_infected = True
for _ in f:
lines += 1
if lines > 1:
self.is_infected = True
break
self.progress = 50
# time.sleep(5)
lines = 0
with open(os.path.join(paths[1], "index.js")) as f:
for line in f:
lines += 1 # TODO: you don't actually need to count the lines, you can just check if it's more than 1
if lines > 1:
self.is_infected = True
for _ in f:
lines += 1
if lines > 1:
self.is_infected = True
break
if self.is_infected:
return self.finish(
@ -48,15 +47,14 @@ class SpideyTest(test_template.TestTemplate):
"If you've recently downloaded a .exe directly sent from someone, "
"do also consider a clean windows reinstall."
)
self.add_to_new_data("global_tests", self.name(), "passed")
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")

View File

@ -1,8 +1,10 @@
"""
A global template for all tests.
"""
import os
from typing import Callable, Union
from modules import internal_io
from modules import internal_io, agnostic_paths
class TestDataError(Exception):
@ -13,47 +15,62 @@ 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, use_cache: bool = True) -> None:
"""
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.use_cache = use_cache
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_test(self):
def run(self) -> None:
"""
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) -> 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.
@ -61,29 +78,26 @@ class TestTemplate:
self.set_status("running", "The test will begin shortly, please wait...")
self.set_status("sucess", "The test was a success but kinda not a success.")
def init_test_data(self):
def init_test_data(self) -> Union[str, None]:
if self.test_data is None and not self.args.continue_on_error:
self.set_status("problem", "No test data given.")
return self.finish()
def name(self):
def name(self) -> str:
"""
:return: Name of the test
:rtype: str
"""
return str(self.__class__.__name__)
def get_status_code(self):
def get_status_code(self) -> str:
"""
:return: Status code at the time of call.
:rtype: str
"""
return self.status_code
def get_status(self):
def get_status(self) -> internal_io.test_status:
"""
:return: Status at the time of call.
:rtype: internal_io.test_status
"""
return internal_io.test_status(
name=self.name(),
@ -95,23 +109,19 @@ class TestTemplate:
)
@staticmethod
def get_status_from_code(code):
def get_status_from_code(code: str) -> str:
"""
:param code: The status code to get the status from.
:type code: str
:return: Description of the status code
:rtype: str
"""
return internal_io.return_code_dict[code]
def set_status(self, statuscode: str, message: str = None):
def set_status(self, statuscode: str, message: str = None) -> str:
"""
Sets a new status code.
:param statuscode: Status code to set
:param message: Message to set
:type statuscode: str
:return: new status code
:rtype: str
"""
self.status_code = statuscode
if message is not None:
@ -120,9 +130,12 @@ class TestTemplate:
self.status = self.get_status_from_code(statuscode)
return self.status_code
def finish(self, statuscode: str = None, message: str = None):
def finish(self, statuscode: str = None, message: str = None) -> str:
"""
Finishes the test.
:param statuscode: Status code to set
:param message: Message to set
:type statuscode: str
"""
if message is not None:
self.status = message
@ -135,94 +148,73 @@ class TestTemplate:
self.queue_lock.release()
return self.get_status_code()
def add_failure(self, path, message):
def add_failure(self, path: str, message: str) -> None:
"""
Adds a failure to the failure dictionary.
:param path: Path to the file that failed
:type path: str
:param message: Message to add
:type message: str
"""
self.failure_dict[path] = message
def __del__(self):
def __del__(self) -> None:
"""
Destructor.
"""
if self.status_code == "running":
return self.finish("skipped")
def add_to_new_data(self, entry: str, testname: str, value: str) -> any:
"""
Adds a new entry to the database.
:param entry: The entry to add
:param testname: The name of the test
:param value: The value of the entry
:return: The value of the entry
"""
if entry not in self.new_data:
self.new_data[entry] = {}
self.new_data[entry][testname] = value
return value
class TestWalkTemplate(TestTemplate):
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
def get_from_new_data(self, entry: str, testname: str) -> any:
"""
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
Gets the value of an entry from the database.
:param entry: The entry to get
:param testname: The name of the test
:return: The value of the entry
"""
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
self.to_skip = []
def add_test_result(self, path, testname, result):
"""
Adds a test result to the data dictionary.
:param path: Path to the file that was tested
:type path: str
:param testname: Name of the test
:type testname: str
:param result: Result of the test
:type result: any
"""
path = self.agnostic_path.get_short_path(path)
if path not in self.new_data:
self.new_data[path] = {}
self.new_data[path][testname] = result
return result
def get_test_data(self, path, testname):
"""
Gets the test data from the data dictionary.
:param path: Path to the file that was tested
:type path: str
:param testname: Name of the test
:type testname: str
:return: Test data
:rtype: any
"""
path = self.agnostic_path.get_short_path(path)
if path in self.new_data:
if testname in self.new_data[path]:
return self.new_data[path][testname]
if entry in self.new_data:
if testname in self.new_data[entry]:
return self.new_data[entry][testname]
return None
def get_expected_result(self, path, testname):
def get_from_database(self, entry: str, testname: str) -> any:
"""
Gets the expected result from the data dictionary.
:param path: Path to the file that was tested
:type path: str
:param testname: Name of the test
:type testname: str
:return: Expected result
:rtype: any
Gets the value of an entry from the database.
:param entry: The entry to get
:param testname: The name of the test
:return: The value of the entry
"""
if self.test_data:
path = self.agnostic_path.get_short_path(path)
if "tests" in self.test_data:
if path in self.test_data["tests"]:
if testname in self.test_data["tests"][path]:
return self.test_data["tests"][path][testname]
if entry in self.test_data["tests"]:
if testname in self.test_data["tests"][entry]:
return self.test_data["tests"][entry][testname]
return None
def run_test(self):
class TestWalkTemplate(TestTemplate):
def __init__(self, thread_parameters: internal_io.thread_parameters, use_cache: bool = False):
"""
Simple test template.
"""
super().__init__(thread_parameters, use_cache)
self.to_skip = []
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.
:return:
"""
self.set_status("running", "The test will begin shortly, please wait...")
@ -234,40 +226,69 @@ 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.")
return self.finish()
def walk(self):
def walk(self) -> list:
"""
Walks the given path and returns a list of all files and directories.
:return: List of all files and directories
:return:
:return: List of all files
"""
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):
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
:param testname: Name of the test
:param result: Result of the test
:return: The result of the test
"""
path = self.agnostic_path.get_short_path(path)
return self.add_to_new_data(path, testname, result)
def get_test_data(self, path: str, testname: str) -> any:
"""
Gets the test data from the data dictionary.
:param path: Path to the file being tested
:param testname: Name of the test
"""
return self.get_from_new_data(self.agnostic_path.get_short_path(path), testname)
def get_expected_result(self, path: str, testname: str) -> Union[str, None]:
"""
Gets the expected result from the data dictionary.
:param path: Path to the file being tested
:param testname: Name of the test
"""
if self.test_data:
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):
"""
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
:type path: agnostic_path.AgnosticPath
:param entry_name: Name of the entry in the test data
:type entry_name: str
:param function: Function to use on the path
:type function: function
:param args: Arguments to use on the function
:type args: list
:param kwargs: Keyword arguments to use on the function
:type kwargs: dict
:param cmp_function: Function compare both results
:type cmp_function: function
"""
if self.agnostic_path.get_short_path(path) in self.to_skip:
return True
if self.use_cache:
kwargs["cached_data"] = self.agnostic_path.cached_file(path)
else:
kwargs["cached_data"] = None
data_origin = self.add_test_result(path, entry_name, function(path, *args, **kwargs))
expected_data = self.get_expected_result(path, entry_name)
@ -286,15 +307,73 @@ 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: internal_io.thread_parameters, use_cache: bool = False):
"""
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, use_cache)
self.to_skip = [r"modules\discord_dispatch-1\discord_dispatch\dispatch.log"]
class TestWalkTemplateSimpleFunction(TestWalkTemplateNoLogs):
def __init__(self, thread_parameters: internal_io.thread_parameters,
function: Callable, unit_test: str, use_cache: bool = False):
"""
A test template that runs a simple function on every file, and compares the result with the expected data.
:param thread_parameters: Thread parameters
:param function: Function to use on every file
:param unit_test: A descriptor of what the test returns
"""
super().__init__(thread_parameters, use_cache)
self.function = function
self.test_name = self.name()
self.unit_test = unit_test
def run_test(self) -> bool:
"""
Walk all files and check their size.
:return: Whether any of the files are larger than the expected size.
"""
self.set_status("running")
size = self.agnostic_path.size
error_msg = ""
for i, path in enumerate(self.walk()):
self.progress = int(100*i / size)
short_path = self.agnostic_path.get_short_path(path)
if os.path.isfile(path):
if not self.compare(path, self.test_name, self.function, (), {}):
res = self.get_test_data(path, self.test_name)
self.add_failure(path, f"Test {self.name()} failed on {short_path}")
error_msg += f"{short_path} is " \
f"({res}{self.unit_test}) not ({self.get_expected_result(path, self.test_name)}" \
f"{self.unit_test}).\n"
# 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, self.test_name)}"
f" {self.unit_test}, but it is {self.get_expected_result(path, self.test_name)}"
f"{self.unit_test}.")
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, self.test_name)}"
f"{self.unit_test}, but it is {os.path.getsize(path)}{self.unit_test}")
self.progress = 100
if self.is_infected:
return self.finish(
"failure",
error_msg
)
elif self.is_unknown:
return self.finish(
"problem",
error_msg
)
return self.finish("success", "Your discord is not infected.")

11
tox.ini Normal file
View File

@ -0,0 +1,11 @@
[flake8]
ignore = D203, E226
exclude =
.git,
__pycache__,
docs/source/conf.py,
old,
build,
dist
max-complexity = 16
max_line_length = 127