Merge pull request #8 from idle-org/develop

Develop
This commit is contained in:
Maximilien Rigaut 2022-06-22 10:43:02 +02:00 committed by GitHub
commit 200ac53737
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 269 additions and 139 deletions

View File

@ -7,14 +7,33 @@ import sys
class AgnosticPaths:
def __init__(self, ptb):
"""
An agnostic path object, containing all methods to access the files and folders in a standard discord install
"""
def __init__(self, ptb, force_path=""):
"""
:param ptb: Whether the discord is a public beta install (ptb="PTB") or not (ptb="")
:type ptb: str
:param forced_path: An alternative discord install path, usefull to test the script on a non standard install
:type forced_path: str
"""
self.ptb = ptb
self.os = self.get_os()
self.main_path = self.get_path()
self.versions = self.get_versions()
self.latest_version = self.get_latest_version()
self.force_path = force_path[0]
self.main_path = self._get_path()
self.version = self.get_version()
self._update_path()
def get_os(self):
"""
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...
:return: ("windows", "linux", "mac")
:rtype: str
"""
platform = sys.platform
if platform.startswith('win'):
self.os = 'windows'
@ -24,38 +43,64 @@ class AgnosticPaths:
self.os = 'mac'
else:
raise OSError("This script can only check for Spideys on Windows, Linux and Mac.")
if self.os == 'linux' or self.os == 'mac':
raise OSError("This script can only check for Spideys on Windows for now.")
return self.os
def get_path(self):
def _get_path(self):
"""
Return the base path of the install, 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
"""
if self.force_path != "":
return self.force_path
if self.os == 'windows':
return os.path.join(os.path.expanduser('~'), "AppData", "Local", f"Discord{self.ptb}")
elif self.os == 'linux':
return ""
return os.path.join("/", "opt", "discord")
# return os.path.join("usr","share","discord")
elif self.os == 'mac':
return ""
raise OSError("Cannot detect discord PATH")
def get_versions(self):
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
"""
versions = []
for element in os.listdir(self.main_path):
if re.match(r"app-[\d\.]+", element):
versions.append(element)
if not versions:
raise FileNotFoundError("Could not find discord version folder.")
versions.sort()
return versions
if self.os == 'windows':
for element in os.listdir(self._get_path()):
if re.match(r"app-[\d.]+", element):
versions.append(element)
if not versions:
raise FileNotFoundError("Could not find discord version folder.")
versions.sort()
return versions[-1]
elif self.os == 'linux':
from json import load
with open(self('resources', 'build_info.json'), "r") as versionFile:
versions = load(versionFile)
return versions['version']
else:
raise OSError("Can't find for version on your OS.")
def get_latest_version(self):
return self.versions[-1]
def _update_path(self):
"""
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):
"""
Lists all files in the given path.
:param args: The path
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
:rtype: list[str]
"""
return os.listdir(self(*args))
@ -75,26 +120,48 @@ class AgnosticPaths:
files.append(element)
return dirs, files
def __call__(self, *args, version=None):
if version is None:
_path = os.path.join(self.main_path, *args)
elif version == "LATEST":
_path = os.path.join(self.main_path, self.latest_version, *args)
else:
_path = os.path.join(self.main_path, version, *args)
def __call__(self, *args):
"""
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
:return: The path is it exists
:rtype: str
:raises: FileNotFoundError if the path doesn't exists
"""
_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):
"""
The main path of the discord install
:return: self.main_path
:rtype: str
"""
return self.main_path
def __repr__(self):
return f"AgnosticPaths(ptb={self.ptb}, os={self.os}, main_path={self.main_path}, version={self.latest_version})"
"""
: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):
"""
:return: The main path of the discord install
:rtype: str
"""
return self.main_path
if __name__ == '__main__':
path = AgnosticPaths("")
print(path)
print(path.list_dir_files())
print(path.list())
print(path.version)
print(path.list())
print(path())
print(path("resources", "bootstrap")) # Return the main_path plus resources, bootstrap
print(path.list_dir_files("resources", "bootstrap")) # List the base_path/resources/bootstrap and return [[folders], [files]]

View File

@ -1,102 +0,0 @@
import os
import re
import sys
class SpideyDetector:
def __init__(self, args):
"""
:param ptb: Whether you're using discord Public Test Version
:type ptb: bool
"""
if args.ptb:
self.ptb = "PTB"
else:
self.ptb = ""
self.is_windows = self.check_os()
self.is_infected = False
self.paths = self.check_paths(*self.get_path())
self.spidey_check()
def check_os(self): # noqa
if not sys.platform.startswith('win'):
raise OSError("This script can only check for Spideys on Windows.")
return True
def get_path(self):
"""
Gets the path of the two folders we need to check
:return: Two paths.
:rtype: str
"""
pre_version_path = os.path.join(os.path.expanduser('~'), "AppData", "Local", f"Discord{self.ptb}")
version = self.get_version(pre_version_path)
discord_modules = os.path.join(pre_version_path, version,
"modules", "discord_modules-1", "discord_modules")
discord_desktop_core = os.path.join(pre_version_path, version,
"modules", "discord_desktop_core-1", "discord_desktop_core")
return discord_modules, discord_desktop_core
def get_version(self, pre_version_path): # noqa I swear this one is not static :(
"""
Looks for the version file in the discord folder
:param pre_version_path: the /discord/ path.
:type pre_version_path: str
:return: The folder in /discord/ that's only made of ints and dots.
:rtype: str
"""
version = None
for element in os.listdir(pre_version_path):
if re.match(r"app-[\d\.]+", element):
version = element
if not version:
raise FileNotFoundError("Could not find discord version folder.")
return version
def check_paths(self, discord_modules, discord_desktop_core): # noqa
if not os.path.isfile(os.path.join(discord_modules, 'index.js')):
raise FileNotFoundError(f"Could not find index.js in {discord_modules}")
if not os.path.isfile(os.path.join(discord_desktop_core, 'index.js')):
raise FileNotFoundError(f"Could not find index.js in {discord_desktop_core}")
return discord_modules, discord_desktop_core
def spidey_check(self):
"""
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
"""
lines = 0
with open(os.path.join(self.paths[0], "index.js")) as f:
for line in f:
lines = lines + 1
if lines > 1:
self.is_infected = True
lines = 0
with open(os.path.join(self.paths[1], "index.js")) as f:
for line in f:
lines = lines + 1
if lines > 1:
self.is_infected = True
if self.is_infected:
print("\n!!! WARNING !!!\n"
"Unless you've installed a plugin you really trust, chances are your discord install "
"is corrupted. We suggest uninstalling discord and deleting all its files before reinstalling.\n"
"If you've recently downloaded a .exe directly sent from someone, "
"do also consider a clean windows reinstall.")
return self.is_infected
def run_check(ptb):
spd = SpideyDetector(ptb)
if not spd.is_infected:
return 0
else:
return 1
if __name__ == "__main__":
pass

78
modules/spidey_test.py Normal file
View File

@ -0,0 +1,78 @@
import os
class SpideyTest:
def __init__(self, args, agnpath, test_data):
"""
Simple test runner, for testing the detection of Spidey viruses.
: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
"""
self.ptb = args.ptb
self.agnostic_path = agnpath
self.os_name = agnpath.os
self.main_path = agnpath.main_path
self.test_data = test_data
def run_test(self):
"""
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
"""
paths = self.get_path()
self.is_infected = False
lines = 0
with open(os.path.join(paths[0], "index.js")) as f:
for line in f:
lines += 1
if lines > 1:
self.is_infected = True
lines = 0
with open(os.path.join(paths[1], "index.js")) as f:
for line in f:
lines += 1
if lines > 1:
self.is_infected = True
if self.is_infected:
print("\n!!! WARNING !!!\n"
"Unless you've installed a plugin you really trust, chances are your discord install "
"is corrupted. We suggest uninstalling discord and deleting all its files before reinstalling.\n"
"If you've recently downloaded a .exe directly sent from someone, "
"do also consider a clean windows reinstall.")
return self.is_infected
def get_path(self):
"""
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")
return discord_modules, discord_desktop_core
def get_status_code(self):
"""
The status code of the test
:return: 0: The test was not run, 1: The test is running, 2: The test is a success, 3: Test has failed, 4: Test found problems
:rtype: int
"""
# TODO: Add this to a global_dict
return 0
def get_status(self):
"""
Return the status of the test, as a string, as the test is ran
:return: "Test is running", "Test was not run", "Test was run and nothing was detected", "Test was run and some problems were detected (list of problems)"
:rtype: (int, str)
"""
# TODO: Make use of a global_dict
return (self.get_status_code(), "")

83
modules/test_interface.py Normal file
View File

@ -0,0 +1,83 @@
import os
import re
import sys
import importlib
"""
All modules that can be tested
Associate the arguments passed to the command line with the modules to be loaded
argparse argument : [module_name, class_name]
"""
_TEST_MODULES = {
"spidey": ["spidey_test", "SpideyTest"],
}
class TestRunner:
def __init__(self, args, agnpath):
"""
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
"""
self.ptb = args.ptb
self.args = args
self.agnostic_path = agnpath
self.os_name = agnpath.os
self.main_path = agnpath.main_path
self.version = agnpath.version
self.is_infected = 0
self.detections = 0
self.test_run = {}
self.loaded_test_modules = {}
self.loaded_test_classes = {}
self.update_module_list()
self.exec_all_tests()
def update_module_list(self):
"""
Gets the list of modules to be loaded (in accordance to the config)
:return: List of modules
:rtype: list
"""
modules = {}
classes = {}
try:
for module_name, values in _TEST_MODULES.items():
print(values[0])
if self.args.__getattribute__(module_name):
modules[values[0]] = importlib.import_module(f"modules.{values[0]}")
classes[values[0]] = getattr(modules[values[0]], values[1])
except AttributeError:
print(f"The module {module_name} was not loaded because it was not specified in the config.")
self.loaded_test_modules.update(modules)
self.loaded_test_classes.update(classes)
def exec_all_tests(self):
"""
Executes all the tests (later in parallel), get their result as they finishes
:return: The number of test ran, success, failures, skipped (with ran = success+failures+skip)
:rtype: (int,int,int,int) # TODO: Change this to a nametuple
"""
for module_name, test_class in self.loaded_test_classes.items():
tc = test_class(self.args, self.agnostic_path, None)
tc.run_test()
print(tc)
def run_check(args, agnpath): # Todo, skip the is_infected check and defer everything to the exec_all_tests
spd = TestRunner(args, agnpath)
if not spd.is_infected:
return 0
else:
return 1
if __name__ == "__main__":
pass

View File

@ -2,20 +2,21 @@
""" Main program """
from modules import spidey_detector
from modules import test_interface, agnostic_paths
import argparse
import sys
def parse(_args):
def parse(_args): # TODO: Move this to a arg_parsing module
parser = argparse.ArgumentParser(
prog="Spidey Detector",
description='Checks for corrupt discord install'
)
parser.add_argument('--ptb', action='store_true', help='Use Public Test Version')
parser.add_argument('--ptb', action='store_const', const="PTB", default="", help='Use Public Test Version')
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('--spidey', action='store_true', help='Runs the spidey 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")
@ -27,13 +28,16 @@ def parse(_args):
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('--launch', action='store_true', help="Launch the discord client after the tests are done")
parser.add_argument("--force-path", nargs=1, default="", help="Bypass the automatic path discovery with given path")
return parser.parse_args(_args)
if __name__ == "__main__":
args = parse(sys.argv[1:])
agnostic_path = agnostic_paths.AgnosticPaths(ptb=args.ptb, force_path=args.force_path)
try:
spd = spidey_detector.run_check(args)
spd = test_interface.run_check(args, agnostic_path)
except FileNotFoundError as er:
print(er)
sys.exit(1)
@ -42,5 +46,5 @@ if __name__ == "__main__":
sys.exit(1)
if spd == 0:
print("SpideyDetector could not find anything wrong with your discord install!")
print("TestRunner could not find anything wrong with your discord install!") # TODO: Everything should be in the run_all_tests()
sys.exit(spd)